Compare commits

...
Author SHA1 Message Date
shadowdaoandClaude Sonnet 5.5 a41ad107a1 Donate form: fill container width, centre block, left-align text inside theme-centred modules
Test and Release / test (push) Successful in 2m1s
Test and Release / release (push) Successful in 14s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0185ukXhhC8xipsBR7e3o76i
2026-11-16 06:48:30 -08:00
shadowdaoandClaude Sonnet 5.5 f19ed5c5f2 Fix moderation redirect after last approval; add going-live and chargeback docs
Test and Release / test (push) Successful in 1m20s
Test and Release / release (push) Successful in 16s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 21:44:47 -08:00
shadowdaoandClaude Sonnet 5.5 9f33ea7975 Progress bar: use accent gradient fill so a full bar is visible
Test and Release / test (push) Successful in 1m18s
Test and Release / release (push) Successful in 4s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 17:53:34 -08:00
shadowdaoandClaude Sonnet 5.5 b80010f422 Add goal progress bar to donate form and [streamgoals_progress] shortcode
Test and Release / test (push) Successful in 1m17s
Test and Release / release (push) Successful in 13s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 17:48:37 -08:00
shadowdaoandClaude Sonnet 5.5 353f7ca5be Hold donations with flagged donor names for moderation; reconcile lost side effects (schema v6)
Test and Release / test (push) Successful in 1m28s
Test and Release / release (push) Successful in 7s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 17:07:32 -08:00
shadowdaoandClaude Sonnet 5.5 473fe192cd Security review fixes: keep pending-capture ids, ship uninstall.php (+verify step), webhook guard, IPv6 /64 + global order throttle, token-safe redirects, honest refund wording, request-id and overlay-token hardening
Test and Release / test (push) Successful in 1m23s
Test and Release / release (push) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 14:07:44 -08:00
43 changed files with 1857 additions and 85 deletions

No files matched your search

+13
View File
@@ -93,6 +93,7 @@ jobs:
PKG=/tmp/streamgoals-donate
mkdir -p "$PKG"
cp streamgoals-donate.php "$PKG"/
cp uninstall.php "$PKG"/
cp -r includes assets "$PKG"/
[ -d languages ] && cp -r languages "$PKG"/ || true
[ -f LICENSE ] && cp LICENSE "$PKG"/ || true
@@ -101,6 +102,18 @@ jobs:
(cd /tmp && zip -r -q "$GITHUB_WORKSPACE/streamgoals-donate.zip" streamgoals-donate)
unzip -l streamgoals-donate.zip | tail -n 15
- name: Verify package contents
run: |
set -e
LIST=$(unzip -l streamgoals-donate.zip)
for f in streamgoals-donate/streamgoals-donate.php streamgoals-donate/uninstall.php streamgoals-donate/includes/Core/Uninstaller.php streamgoals-donate/LICENSE; do
if ! echo "$LIST" | grep -qE "[[:space:]]${f}\$"; then
echo "::error::release zip is missing $f"
exit 1
fi
done
echo "package contents verified"
- name: Create release
uses: softprops/action-gh-release@v2
with:
+32 -2
View File
@@ -30,6 +30,23 @@ You need two values from PayPal: a **Client ID** and a **Secret**.
Start in **Sandbox**, make a test donation using a PayPal sandbox buyer account, then repeat the steps
with the Live credentials and switch the mode to Live in Settings.
### Going live
1. In the PayPal developer dashboard (Apps & Credentials), switch to **Live** and create a Live app (type Merchant).
2. In StreamGoals > Settings, paste the Live **Client ID** and **Secret**.
3. Switch the mode to **Live**, then **Save and test connection**.
4. Webhook: the plugin registers it for you when the test succeeds (changing mode or credentials clears the old one, so
the Live webhook is created fresh). It points to `https://YOUR-SITE/wp-json/streamgoals/v1/webhook` and listens for
`PAYMENT.CAPTURE.COMPLETED`. If the message says it could not register it (needs a public https site, or a webhook
for that address already exists), add it by hand in your Live app in the PayPal dashboard with that URL and that event.
5. Make a small real donation and check it appears under Donations and on your goal, then refund yourself in PayPal if you like.
6. Set the visitor IP header if needed (Settings > Advanced; Cloudflare is detected automatically).
7. Add the overlays in OBS as Browser Sources (StreamGoals > Overlays).
8. Turn on two-factor authentication for both your PayPal and WordPress accounts.
### Chargebacks and refunds
Chargebacks and refunds are handled manually in PayPal. The plugin does not track them, so totals, timers, counters
and tiers are not reduced. If you need to compensate, adjust the goal or its rules yourself by editing them.
### Behind Cloudflare?
Nothing to do: the plugin recognises Cloudflare automatically (by its published addresses) so each visitor is rate
limited separately. For another proxy, choose it in StreamGoals > Settings > Advanced; the panel there shows what your
@@ -45,6 +62,12 @@ server sees.
## Using it
- **Donation page:** add the shortcode `[streamgoals_donate]` to a page (or `[streamgoals_donate goal="ID"]` to pin one goal).
- `show_progress="no"` hides the progress bar above the form (default `yes`; also accepts `true/false/1/0`).
- `[streamgoals_progress]` (or `[streamgoals_progress goal="ID"]`) shows just the progress bar, e.g. in a sidebar or a stream page.
The bar shows raised / target, the percentage and, for tiered goals, the current tier and its target, using the same
numbers as the overlay (base amounts, or including fees only if the goal counts fees). It refreshes after a donation and
about every 30 seconds while the tab is visible, from the public `GET /wp-json/streamgoals/v1/progress?goal=ID` (totals only).
The first render is server-side HTML, so page caches and Cloudflare are fine.
- **Goals:** StreamGoals → Goals. Create as many as you like; each can have its own rules.
- **Rules (time and counters):** per goal, e.g. "+60 seconds per $1" (subathon timer), "+1 per $10" (counter),
or a bonus event above a minimum amount. Amounts can be measured on the base donation or including fee cover.
@@ -74,10 +97,17 @@ server sees.
## Privacy and moderation
- Donors choose a name or "Anonymous". For anonymous donors the **name is never stored**.
- Optional message approval queue and a streamer-controlled profanity filter (whole-word, your own word list).
- The filter masks bad words in messages and in donor names (anonymous donors have no stored name). If a **donor name**
trips the filter, the donation still completes and counts towards the goal, timer, counters, rewards and tiers, but it
is **held on the Moderation screen** (flagged "Name", "Message" or "Name and message") even when message moderation is
off. A held donation shows no alert (name or message) and no public donor-feed entry until you approve it; approving
shows the already-masked name. Rejecting it means it is never shown.
- If the server dies right after a payment is recorded, a five-minute background job re-applies any timer, counter,
reward and tier effects that were missed (never twice).
## Not supported
- **Refunds and chargebacks are not tracked.** If you refund someone in PayPal, goal totals, timers and
counters are not adjusted.
- **Refunds and chargebacks are not tracked.** Refunds and chargebacks done in PayPal are NOT reflected in goal
totals, timers, counters or tiers. The donation keeps counting as if it had been paid.
## Transparent alerts
In StreamGoals > Alerts, tick **Frameless** on an alert to drop the dark box, border and glow so only your picture or
+12 -1
View File
@@ -1,4 +1,4 @@
.sg-donate{max-width:min(100%,440px);font:inherit}
.sg-donate{width:100%;max-width:min(100%,440px);margin-left:auto;margin-right:auto;box-sizing:border-box;text-align:left;font:inherit}
.sg-donate .sg-row{margin:0 0 .9rem}
.sg-donate label{display:block;font-weight:600;margin-bottom:.25rem}
.sg-donate label.sg-inline{display:flex;gap:.5rem;align-items:center;font-weight:400}
@@ -42,3 +42,14 @@
.sg-donate .sg-presets.sg-actions{padding:0 5px}
.sg-donate .sg-notice{margin:.6rem 0 0;font-size:.9em;line-height:1.4;opacity:.85;overflow-wrap:anywhere}
/* Progress bar (theme-neutral: inherits text colour; fill uses currentColor so it follows the theme). */
.sg-donate .sg-progress{margin:0 0 .9rem;max-width:100%;box-sizing:border-box}
.sg-donate .sg-progress-bar{position:relative;height:14px;border:1px solid rgba(128,128,128,.45);border-radius:999px;background:rgba(128,128,128,.22);overflow:hidden;box-shadow:inset 0 1px 2px rgba(0,0,0,.18)}
.sg-donate .sg-progress-fill{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--sg-accent,#7c5cff),var(--sg-accent2,#22d3ee));min-width:0;border-radius:999px;transition:width .6s ease}
.sg-donate .sg-progress-text{display:flex;flex-wrap:wrap;justify-content:space-between;gap:.25rem .75rem;margin-top:.35rem;font-weight:600;line-height:1.4;overflow-wrap:anywhere}
.sg-donate .sg-progress-tier,.sg-donate .sg-progress-done{margin:.25rem 0 0;font-size:.9em;line-height:1.4;overflow-wrap:anywhere}
.sg-donate .sg-progress-done{font-weight:700}
.sg-donate .sg-progress [hidden]{display:none}
.sg-donate.sg-progress-only .sg-progress{margin-bottom:0}
@media (prefers-reduced-motion:reduce){.sg-donate .sg-progress-fill{transition:none}}
+61 -5
View File
@@ -1,9 +1,12 @@
/* StreamGoals donate form (vanilla JS). Config comes from window.StreamGoalsDonate. */
(function () {
'use strict';
var C = window.StreamGoalsDonate;
if (!C) { return; }
var T = C.i18n || {};
var C = window.StreamGoalsDonate; // donate form config (absent on pages with only [streamgoals_progress])
var PC = window.StreamGoalsProgress; // progress bar config (rest url, labels, poll interval)
if (!C && !PC) { return; }
var T = (C && C.i18n) || {};
var PT = (PC && PC.i18n) || {};
var REST = (C && C.restUrl) || (PC && PC.restUrl) || '';
var sdkPromise = null, sdkCurrency = null;
function el(tag, attrs, children) {
@@ -18,7 +21,7 @@
function api(path, opts) {
opts = opts || {};
return fetch(C.restUrl + path, {
return fetch(REST + path, {
method: opts.method || 'GET',
headers: { 'Content-Type': 'application/json' },
body: opts.body ? JSON.stringify(opts.body) : undefined,
@@ -62,12 +65,60 @@
}
function sprintf1(tpl, v) { return String(tpl || '%s').replace('%s', v); }
/* ---- Progress bar: server renders the markup, this keeps it fresh (same code for form and [streamgoals_progress]). ---- */
function tpl(str, a, b) {
return String(str || '').replace('%1$s', function () { return a; }).replace('%2$s', function () { return b; });
}
function applyBar(box, p) {
if (!box || !p) { return; }
var pct = Math.max(0, Math.min(100, parseInt(p.percent, 10) || 0));
var bar = box.querySelector('.sg-progress-bar');
var of = tpl(PT['of'] || '%1$s / %2$s', p.raised_display, p.target_display);
box.setAttribute('data-goal', String(p.goal_id));
box.className = 'sg-progress' + (p.reached ? ' sg-progress-reached' : '');
bar.setAttribute('aria-valuenow', String(pct));
bar.setAttribute('aria-valuetext', p.reached ? (PT.reached || '') : of + ' (' + pct + '%)');
bar.setAttribute('aria-label', String(PT.label || '%s').replace('%s', function () { return p.title; }));
bar.firstChild.style.width = pct + '%';
box.querySelector('.sg-progress-amounts').textContent = of;
box.querySelector('.sg-progress-pct').textContent = pct + '%';
var tier = box.querySelector('.sg-progress-tier'), done = box.querySelector('.sg-progress-done');
tier.hidden = !p.tier;
tier.textContent = p.tier ? tpl(PT.tier, p.tier.title, p.tier.target_display) : '';
done.hidden = !p.reached;
done.textContent = p.reached ? (PT.reached || '') : '';
}
function refreshGoal(id, bust) {
return api('/progress?goal=' + encodeURIComponent(id) + (bust ? '&t=' + Date.now() : '')).then(function (p) {
Array.prototype.forEach.call(document.querySelectorAll('.sg-progress'), function (b) {
if (b.getAttribute('data-goal') === String(p.goal_id)) { applyBar(b, p); }
});
}, function () { /* keep showing the last known numbers */ });
}
function refreshAll(bust) {
var seen = {};
Array.prototype.forEach.call(document.querySelectorAll('.sg-progress'), function (b) {
var id = b.getAttribute('data-goal');
if (id && id !== '0' && !seen[id]) { seen[id] = true; refreshGoal(id, bust); }
});
}
function startPolling() {
if (!REST || !document.querySelector('.sg-progress')) { return; }
var every = Math.max(15000, (PC && PC.pollMs) || 30000);
setInterval(function () { if (document.visibilityState !== 'hidden') { refreshAll(false); } }, every);
document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible') { refreshAll(true); } });
refreshAll(true); // a cached page may hold old numbers
}
// After a successful donation: refresh now, and again shortly (a pending capture can finalize a moment later).
function afterDonation() { refreshAll(true); setTimeout(function () { refreshAll(true); }, 5000); }
function init(root) {
var pinned = parseInt(root.getAttribute('data-goal'), 10) || 0;
var goals = C.goals.filter(function (g) { return !pinned || g.id === pinned; });
if (!goals.length) { return; }
var uid = 'sg' + Math.random().toString(36).slice(2, 8);
var state = { goal: goals[0], renderToken: 0, quote: null };
var barBox = root.querySelector('.sg-progress');
var goalSel = el('select', { id: uid + '-goal' });
goals.forEach(function (g) { goalSel.appendChild(el('option', { value: g.id, text: g.title + ' (' + g.currency + ')' })); });
@@ -227,6 +278,7 @@
onApprove: function (data) {
return api('/orders/' + encodeURIComponent(data.orderID) + '/capture', { method: 'POST' }).then(function (r) {
say(r.status === 'completed' ? T.thanks : T.processing, 'sg-ok');
afterDonation();
});
},
onError: function (err) { say((err && err.message) || T.error, 'sg-error'); }
@@ -236,11 +288,15 @@
goalSel.addEventListener('change', function () {
state.goal = goals.filter(function (g) { return String(g.id) === goalSel.value; })[0] || goals[0];
if (barBox && state.goal.progress) { applyBar(barBox, state.goal.progress); refreshGoal(state.goal.id, true); }
showNext(); buildPresets(); refresh(); renderButtons();
});
showNext(); buildPresets(); refresh(); renderButtons();
}
function boot() { Array.prototype.forEach.call(document.querySelectorAll('.sg-donate'), init); }
function boot() {
if (C) { Array.prototype.forEach.call(document.querySelectorAll('.sg-donate:not(.sg-progress-only)'), init); }
startPolling();
}
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot); } else { boot(); }
})();
+18 -2
View File
@@ -20,7 +20,7 @@ Namespace `StreamGoals\`, PSR-4 rooted at `includes/`. Text domain `streamgoals-
## Database (created by `Core\Installer`, version in option `sg_db_version`)
- `sg_goals`: id, title, target_minor, currency, status(active|paused|complete), starts_at, ends_at NULL, counts_fees TINYINT(0 = base amount only), created_at
- `sg_donations`: id, goal_id, paypal_order_id, paypal_capture_id UNIQUE, base_minor, fee_minor, total_minor, currency, donor_name, is_anonymous, message, status(pending|completed|refunded|reversed), moderation(approved|pending|rejected), created_at
- `sg_donations`: id, goal_id, paypal_order_id, paypal_capture_id UNIQUE, base_minor, fee_minor, total_minor, currency, donor_name, is_anonymous, message, status(pending|completed|refunded|reversed), moderation(approved|pending|rejected), moderation_flags, effects_applied_at NULL (v6), created_at
- `sg_rules`: id, goal_id, type(add_time|counter|bonus), config JSON, enabled, sort
- `sg_rule_events`: id, rule_id, donation_id, delta (seconds or count), reversed TINYINT, created_at — UNIQUE(rule_id, donation_id) for idempotency
- `sg_state`: goal_id, key, value — timer `ends_at`, counter totals, carry-over remainders
@@ -32,7 +32,7 @@ Money::fromDecimalString(string $amount, string $currency): Money; // "10.50" -
FeeCalculator::grossUp(int $baseMinor, FeeRates $rates): int; // total so recipient nets base
// total = ceil((base + fixed) / (1 - pct)) — rates configurable, default US 3.49% + 49c
```
Rules engine entry point (Agent 2 implements, Agent 1 calls after a capture is recorded and on refund):
Rules engine entry point (Agent 2 implements, Agent 1 calls after a capture is recorded; refunds/chargebacks are NOT tracked - nothing calls reverseDonation, and refunds done in PayPal are not reflected in goal totals, timers, counters or tiers):
```php
Rules\Engine::applyDonation(Donation $d): void; // idempotent via sg_rule_events UNIQUE
Rules\Engine::reverseDonation(Donation $d): void; // honors per-rule "reverse on refund"
@@ -47,6 +47,8 @@ Rule `config` examples (`max_total_seconds` caps what one rule has added over ti
## Public REST (namespace `streamgoals/v1`)
- `POST /orders` (create order; server computes total incl. optional fee cover), `POST /orders/{id}/capture`
- `POST /webhook` (PayPal signature verified; deduped by capture id)
- `GET /progress?goal=ID` — public, read-only, rate limited (60/min per visitor). Returns `Overlay\Progress::payload()` only: `goal_id,title,currency,raised_minor,target_minor,percent,raised_display,target_display,reached,tier|null` (`tier` = `{index,count,title,target_minor,target_display}`). No donor data. 404 unless goal status is active/complete. `Cache-Control: public, max-age=10`.
Shortcodes `[streamgoals_donate show_progress="yes|no"]` (default yes) and `[streamgoals_progress goal=""]` server-render `Progress::html()` (role=progressbar); `donate.js` updates it in place (after a donation, every 30 s while the tab is visible, and once on load for cached pages). Numbers come from `Payloads::goal()`, so they match the overlay; reached = closed at target, all tiers reached, or raised >= target.
- `GET /overlay/{token}/{widget}` — ETag'd JSON, polled every 2–3 s; widgets: `goal`, `timer`, `counter`, `alerts`
## Fee cover
@@ -92,3 +94,17 @@ A goal may have ordered TIERS; each is a cumulative target with an item/unlock (
- "Current tier" = the first tier (by target) with reached_at IS NULL. Goal bar progress for a tiered goal = (raised - floor) / (target - floor) clamped 0..1, where floor = previous tier's target (0 for the first); the cumulative raised and the current tier target are still displayed.
- Reached tiers: title/description editable, target locked; a new tier's target must be above the goal's current raised total and unique.
- Overlay `goal` payload for a tiered goal adds `tiers: {count, index (1-based current), current:{title,description,target_minor,target_display,floor_minor}|null, all_reached}`; untiered goals are unchanged. Alert payloads gain `tiers: [{title}]` = tiers whose reached_donation_id is that donation, shown as a "TIER UNLOCKED: title" pill.
## Schema v6 (Installer, DB_VERSION 6): donor-name flagging + effects reconciliation
Only our own `sg_donations` table changes (two columns, added by dbDelta):
- `moderation_flags VARCHAR(16) NOT NULL DEFAULT ''`: why a row is held. `''` (legacy/approved), `message`, `name` or `name,message`. Display only (`Admin\Format::flaggedLabel`); `moderation` stays the single source of truth for visibility. A held row with `''` flags is shown as "Message" (before v6 only messages were held).
- `effects_applied_at DATETIME NULL`: set (UTC) once ALL side effects of a completed donation finished without error.
### Donor-name flagging
`OrderValidator::validate` runs the streamer's `ProfanityFilter` over `donor_name` (non-anonymous only; anonymous names are blanked first and never stored). `ProfanityFilter::matches()` shares the scan with `filter()`. The filter has a single mode, MASK: the stored name is already masked (`f***`), exactly like messages. A tripped name sets `moderation='pending'` and `moderation_flags` includes `name`, independent of the `moderate_messages` setting; a non-empty message with `moderate_messages` on adds `message`. The donation completes and counts for goal/timer/counter/rewards/tiers as usual (moderation never gates those).
Alerts: `Overlay\Payloads::alerts` (and `WpdbDataSource`, `DonationRepository::recentApproved`) only emit `completed` + `approved` rows, so a held donation emits NO alert at all (the whole alert is held, same as a held message). It is never shown as "Anonymous". After Approve the alert shows the masked name; Reject = never shown.
### Reconciliation of "completed but side effects lost"
`DonationStore::notify_applied($id): bool` runs engine (rules/timer/counter), `Actions\Recorder`, `Tiers\Recorder` (before the close check), then end-at-target, and only if every step succeeded calls `mark_effects_applied` (`UPDATE ... WHERE effects_applied_at IS NULL`). `CaptureFinalizer` is unchanged: `mark_completed` stays the atomic single-winner pending->completed step and both the capture endpoint and the webhook call `notify_applied` only for the winner, so a replay never re-runs it inline.
`Maintenance::reconcile_effects` (cron `sg_reconcile_effects`, every 5 min, single-flight via `GET_LOCK`) selects up to 25 `status='completed' AND effects_applied_at IS NULL AND goal_id>0` rows created more than 2 minutes and less than 30 days ago and calls `notify_applied` again. Replay safety: rules via `sg_rule_events` UNIQUE(rule_id,donation_id) (event inserted first, state only touched if new, under the goal lock); rewards via `INSERT IGNORE` on UNIQUE(donation_id,action_id); tiers via `UPDATE ... WHERE reached_at IS NULL`; close-at-target via `UPDATE ... WHERE status='active'`.
Upgrade: `Installer::maybe_upgrade` passes the stored version to `install_schema`; when it is < 6 (or absent) it backfills `effects_applied_at` for every already-completed row BEFORE writing `sg_db_version`, so history is never replayed and a failed backfill is retried on the next load. Known gap (unchanged): in `Engine::applyRule` the event row is recorded before state is updated, so a death between those two statements loses that single rule's effect and a replay skips it.
+9 -3
View File
@@ -6,21 +6,27 @@ namespace StreamGoals\Actions;
/** Queues the on-stream actions a completed donation triggers. */
final class Recorder {
/** Never throws. Idempotent: replays are ignored by the UNIQUE key on sg_action_events. */
public static function forDonation( int $donationId ): void {
/**
* Never throws. Idempotent: replays are ignored by the UNIQUE key on sg_action_events.
*
* @return bool False only when something failed (so the caller must not mark the donation's effects as applied).
*/
public static function forDonation( int $donationId ): bool {
try {
global $wpdb;
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT id, goal_id, base_minor, status FROM ' . $wpdb->prefix . 'sg_donations WHERE id = %d', $donationId ), ARRAY_A );
if ( ! is_array( $row ) || 'completed' !== ( $row['status'] ?? '' ) ) {
return;
return true;
}
$repo = new ActionRepository( $wpdb );
$matches = Matcher::match( (int) $row['base_minor'], $repo->enabledForGoal( (int) $row['goal_id'] ) );
if ( $matches ) {
$repo->recordEvents( $donationId, $matches );
}
return true;
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: Recorder failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return false;
}
}
}
+1 -1
View File
@@ -171,7 +171,7 @@ final class Admin {
echo '<div class="wrap sg-admin"><h1>' . esc_html( $title ) . '</h1>';
self::notices();
if ( PayPalConnector::isConnected() && '' === (string) Settings::get( 'paypal_webhook_id', '' ) ) {
echo '<div class="notice notice-warning"><p>' . esc_html( 'PayPal is connected, but the webhook is not set up yet, so refunds/reversals will not be noticed. Open Settings and press "Save and test connection" to register it.' ) . '</p></div>';
echo '<div class="notice notice-warning"><p>' . esc_html( 'PayPal is connected, but the webhook is not set up yet, so payments that PayPal confirms later (for example under review) will not be completed automatically. Note that refunds and chargebacks done in PayPal are NOT reflected in goal totals, timers, counters or tiers, with or without the webhook. Open Settings and press "Save and test connection" to register it.' ) . '</p></div>';
}
}
+13 -7
View File
@@ -52,7 +52,7 @@ final class DonationsPage {
echo Admin::td( 'Donor' ) . esc_html( Format::donorName( $r ) ) . ( $test ? ' <span class="sg-badge sg-test">TEST</span>' : '' ) . '</td>';
echo Admin::td( 'Amount' ) . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td>' . Admin::td( 'Fee' ) . esc_html( Format::money( (int) $r['fee_minor'], $cur ) ) . '</td>' . Admin::td( 'Total paid' ) . esc_html( Format::money( (int) $r['total_minor'], $cur ) ) . '</td>';
echo Admin::td( 'Goal' ) . esc_html( $test ? '(test)' : ( $goals[ (int) $r['goal_id'] ] ?? '#' . (int) $r['goal_id'] ) ) . '</td>';
echo Admin::td( 'Status' ) . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' <span class="sg-badge sg-' . esc_attr( (string) $r['moderation'] ) . '">message ' . esc_html( (string) $r['moderation'] ) . '</span>' ) . '</td>';
echo Admin::td( 'Status' ) . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' <span class="sg-badge sg-' . esc_attr( (string) $r['moderation'] ) . '">' . esc_html( strtolower( Format::flaggedLabel( $r ) ) . ' ' . (string) $r['moderation'] ) . '</span>' ) . '</td>';
echo Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '</td></tr>';
}
echo Admin::tableClose();
@@ -72,22 +72,22 @@ final class DonationsPage {
}
public static function renderModeration(): void {
Admin::open( 'Message moderation' );
Admin::open( 'Moderation' );
if ( ! Settings::get( 'moderate_messages' ) ) {
echo '<div class="notice notice-info inline"><p>Message moderation is currently off in Settings, so new messages are shown without review. Anything still waiting below was submitted while it was on.</p></div>';
echo '<div class="notice notice-info inline"><p>Message moderation is currently off in Settings, so new messages are shown without review. A donor name that trips the profanity filter is still held here, and anything else waiting below was submitted earlier.</p></div>';
}
echo '<p class="description">Approved messages can appear in alerts. Rejected messages are hidden. The donation itself still counts towards your goal either way.</p>';
echo '<p class="description">Held donations stay out of alerts (and the public donor feed) until you approve them. Rejected ones are never shown. A donor name that trips the profanity filter is held here too; it is already masked (for example f***), and approving shows it masked. The donation itself still counts towards your goal, timer and counters either way.</p>';
$res = Store::searchDonations( array( 'status' => 'completed', 'moderation' => 'pending' ), 1, 100 );
if ( ! $res['rows'] ) {
echo '<div class="sg-card"><p>Nothing waiting for review.</p></div>';
Admin::close();
return;
}
echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Message', 'Decision' ), 'Messages waiting for review' );
echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Message', 'Flagged', 'Decision' ), 'Donations waiting for review' );
foreach ( $res['rows'] as $r ) {
$cur = Format::currency( $r['currency'] );
echo '<tr>' . Admin::td( 'Date' ) . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '</td>' . Admin::td( 'Donor' ) . esc_html( Format::donorName( $r ) ) . '</td>';
echo Admin::td( 'Amount' ) . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td>' . Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '</td>' . Admin::td( 'Decision', 'sg-actions' );
echo Admin::td( 'Amount' ) . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td>' . Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '</td>' . Admin::td( 'Flagged' ) . esc_html( Format::flaggedLabel( $r ) ) . '</td>' . Admin::td( 'Decision', 'sg-actions' );
foreach ( array( 'approved' => 'Approve', 'rejected' => 'Reject' ) as $to => $lbl ) {
Admin::form( 'sg_moderate', array( 'donation_id' => (int) $r['id'], 'decision' => $to ), 'sg-inline' );
echo '<button class="button' . ( 'approved' === $to ? ' button-primary' : '' ) . '">' . esc_html( $lbl ) . '</button></form> ';
@@ -98,13 +98,19 @@ final class DonationsPage {
Admin::close();
}
/** Moderation submenu exists only when moderation is on or items are pending (see Admin::menu); otherwise land on Donations. */
public static function afterModerationPage( bool $moderationOn, int $pending ): string {
return ( $moderationOn || $pending > 0 ) ? 'streamgoals-moderation' : 'streamgoals-donations';
}
public static function handleModerate(): void {
Admin::guard( 'sg_moderate' );
$post = Admin::post_raw();
$id = isset( $post['donation_id'] ) ? absint( $post['donation_id'] ) : 0;
$to = isset( $post['decision'] ) && is_string( $post['decision'] ) ? $post['decision'] : '';
$ok = $id && Store::setModeration( $id, $to );
Admin::redirect( Admin::url( 'streamgoals-moderation' ), $ok ? 'success' : 'error', $ok ? ( 'approved' === $to ? 'Message approved.' : 'Message rejected.' ) : 'That message could not be updated (it may already be reviewed).' );
$page = self::afterModerationPage( (bool) Settings::get( 'moderate_messages' ), Store::pendingModerationCount() );
Admin::redirect( Admin::url( $page ), $ok ? 'success' : 'error', $ok ? ( 'approved' === $to ? 'Donation approved.' : 'Donation rejected.' ) : 'That donation could not be updated (it may already be reviewed).' );
}
public static function handleExport(): void {
+11
View File
@@ -61,4 +61,15 @@ final class Format {
}
return (string) $row['donor_name'];
}
/**
* What is being held for review, from sg_donations.moderation_flags: 'Name', 'Message' or 'Name and message'.
* Rows held before flags existed (empty value) were always held for their message.
*/
public static function flaggedLabel( array $row ): string {
$flags = array_filter( array_map( 'trim', explode( ',', (string) ( $row['moderation_flags'] ?? '' ) ) ) );
$name = in_array( 'name', $flags, true );
$msg = in_array( 'message', $flags, true ) || ! $name;
return $name && $msg ? 'Name and message' : ( $name ? 'Name' : 'Message' );
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ final class OverlaysPage {
/** @return array{url:string,base:string,sep:string} */
public static function widgetUrl( string $widget ): array {
$token = OverlayController::token();
$token = OverlayController::ensure_token();
if ( get_option( 'permalink_structure' ) ) {
$base = home_url( '/streamgoals-overlay/' . rawurlencode( $token ) . '/' . rawurlencode( $widget ) . '/' );
return array( 'url' => $base, 'base' => $base, 'sep' => '?' );
+1 -1
View File
@@ -44,7 +44,7 @@ final class SettingsPage {
echo '<div class="sg-card"><h2>Messages</h2><table class="form-table" role="presentation">';
echo '<tr><th scope="row">Moderation</th><td><label><input type="checkbox" name="moderate_messages" value="1"' . checked( ! empty( $s['moderate_messages'] ), true, false ) . '> Hold messages for my approval before they can be shown in alerts</label></td></tr>';
echo '<tr><th scope="row">Profanity filter</th><td><label><input type="checkbox" name="profanity_filter" value="1"' . checked( ! empty( $s['profanity_filter'] ), true, false ) . '> Filter bad language in messages and names</label><br>';
echo '<tr><th scope="row">Profanity filter</th><td><label><input type="checkbox" name="profanity_filter" value="1"' . checked( ! empty( $s['profanity_filter'] ), true, false ) . '> Mask bad language in messages and donor names</label> <span class="description">A donor name that trips the filter is masked and the donation is held on the Moderation screen before its alert can show (it still counts towards your goal).</span><br>';
echo '<label><input type="checkbox" name="profanity_use_builtin" value="1"' . checked( ! empty( $s['profanity_use_builtin'] ), true, false ) . '> Use the built-in word list</label>';
echo '<p><label for="sg_words">Your own words to block (one per line)</label><br><textarea id="sg_words" name="profanity_words" rows="6" class="large-text code">' . esc_textarea( (string) $s['profanity_words'] ) . '</textarea></p></td></tr></table></div>';
+23
View File
@@ -54,6 +54,29 @@ final class ClientIp {
return $fromHeader ?? $remote ?? 'unknown';
}
/**
* Rate-limit BUCKET KEY for a resolved address (never use it as the "real" IP): IPv4 unchanged, IPv4-mapped IPv6
* becomes its IPv4, any other IPv6 collapses to its /64 (one subscriber/host can rotate freely inside a /64),
* 'unknown' stays, anything unparsable becomes 'unknown'.
*/
public static function bucketKey( string $ip ): string {
$ip = trim( $ip );
if ( 'unknown' === $ip || false === filter_var( $ip, FILTER_VALIDATE_IP ) ) {
return 'unknown';
}
if ( false === filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) {
return $ip;
}
$bin = inet_pton( $ip );
if ( false === $bin || 16 !== strlen( $bin ) ) {
return 'unknown';
}
if ( str_repeat( "\0", 10 ) . "\xff\xff" === substr( $bin, 0, 12 ) ) {
return (string) inet_ntop( substr( $bin, 12 ) );
}
return bin2hex( substr( $bin, 0, 8 ) ) . '/64';
}
private static function valid( mixed $v ): ?string {
if ( ! is_string( $v ) ) {
return null;
+1 -1
View File
@@ -22,7 +22,7 @@ final class DonationRepository {
/** @return int|null new id, or null on failure (e.g. duplicate capture id). */
public function insert( array $d ): ?int {
$allowed = array( 'goal_id', 'paypal_order_id', 'paypal_capture_id', 'base_minor', 'fee_minor', 'total_minor', 'currency', 'donor_name', 'is_anonymous', 'message', 'status', 'moderation' );
$allowed = array( 'goal_id', 'paypal_order_id', 'paypal_capture_id', 'base_minor', 'fee_minor', 'total_minor', 'currency', 'donor_name', 'is_anonymous', 'message', 'status', 'moderation', 'moderation_flags' );
$row = array_intersect_key( $d, array_flip( $allowed ) );
$row += array( 'status' => 'pending', 'moderation' => 'approved', 'fee_minor' => 0 );
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
+34 -5
View File
@@ -8,23 +8,45 @@ namespace StreamGoals\Core;
*/
final class Installer {
public const DB_VERSION = '5';
public const DB_VERSION = '6';
public static function activate(): void {
self::install_schema();
self::install_schema( get_option( 'sg_db_version' ) );
if ( false === get_option( 'sg_settings' ) ) {
add_option( 'sg_settings', Settings::defaults(), '', false );
}
Settings::ensure_overlay_token(); // never generated by a public request (see OverlayController)
}
/** Run on plugins_loaded so upgrades apply without re-activation. */
public static function maybe_upgrade(): void {
if ( get_option( 'sg_db_version' ) !== self::DB_VERSION ) {
self::install_schema();
$from = get_option( 'sg_db_version' );
if ( $from !== self::DB_VERSION ) {
self::install_schema( $from );
}
}
private static function install_schema(): void {
/** Schema v6 added sg_donations.effects_applied_at; rows completed before that must not be replayed. */
public static function needsEffectsBackfill( mixed $from ): bool {
return false === $from || '' === $from || version_compare( (string) $from, '6', '<' );
}
/**
* One-time upgrade step: every donation that is ALREADY completed had its side effects applied by the code that
* completed it (or was lost before this feature existed and is not worth replaying), so stamp it. Without this the
* reconciler would replay the whole history. Only touches NULL rows, so re-running is harmless. False on DB error.
*/
public static function backfill_effects_applied(): bool {
global $wpdb;
$n = $wpdb->query( $wpdb->prepare(
'UPDATE ' . $wpdb->prefix . "sg_donations SET effects_applied_at = %s WHERE status = 'completed' AND effects_applied_at IS NULL",
gmdate( 'Y-m-d H:i:s' )
) );
return false !== $n;
}
/** @param mixed $from Previously installed sg_db_version (false when never installed). */
private static function install_schema( mixed $from = false ): void {
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$c = $wpdb->get_charset_collate();
@@ -58,6 +80,8 @@ final class Installer {
message VARCHAR(500) NOT NULL DEFAULT '',
status VARCHAR(12) NOT NULL DEFAULT 'pending',
moderation VARCHAR(10) NOT NULL DEFAULT 'approved',
moderation_flags VARCHAR(16) NOT NULL DEFAULT '',
effects_applied_at DATETIME NULL,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY capture (paypal_capture_id),
@@ -158,6 +182,11 @@ final class Installer {
KEY reached_donation (reached_donation_id)
) $c;" );
// Backfill BEFORE recording the new version: if it fails, the next load retries instead of replaying history.
if ( self::needsEffectsBackfill( $from ) && ! self::backfill_effects_applied() ) {
return;
}
update_option( 'sg_db_version', self::DB_VERSION );
}
}
+91
View File
@@ -14,15 +14,106 @@ final class Maintenance {
public const HOOK = 'sg_purge_abandoned';
public const MAX_AGE_DAYS = 7;
/** Reconcile "completed but side effects lost" donations (see reconcile_effects()). */
public const RECONCILE_HOOK = 'sg_reconcile_effects';
public const RECONCILE_SCHEDULE = 'sg_five_minutes';
/** A donation must be this old before it is replayed, so a request still applying its effects is left alone. */
public const RECONCILE_MIN_AGE = 120;
/** Older donations are not retried (a row that can never succeed must not be replayed forever). */
public const RECONCILE_MAX_AGE_DAYS = 30;
public const RECONCILE_BATCH = 25;
public static function register(): void {
add_action( self::HOOK, array( self::class, 'purge_abandoned' ) );
if ( ! wp_next_scheduled( self::HOOK ) ) {
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::HOOK );
}
add_filter( 'cron_schedules', array( self::class, 'cron_schedules' ) );
add_action( self::RECONCILE_HOOK, array( self::class, 'reconcile_effects' ) );
if ( ! wp_next_scheduled( self::RECONCILE_HOOK ) ) {
wp_schedule_event( time() + 300, self::RECONCILE_SCHEDULE, self::RECONCILE_HOOK );
}
}
/** @param array $schedules @return array */
public static function cron_schedules( $schedules ): array {
$schedules = is_array( $schedules ) ? $schedules : array();
$schedules[ self::RECONCILE_SCHEDULE ] = array( 'interval' => 300, 'display' => 'Every five minutes (StreamGoals)' );
return $schedules;
}
public static function unschedule(): void {
wp_clear_scheduled_hook( self::HOOK );
wp_clear_scheduled_hook( self::RECONCILE_HOOK );
}
/**
* Replays the side effects (rules/timer/counter, rewards, tiers, end-at-target) of completed donations whose request
* died before DonationStore::notify_applied() could stamp effects_applied_at. Safe by construction: every effect is
* idempotent per (rule, donation) / (donation, action) / tier, and the donation row itself is never touched here.
* Single-flight through a MySQL named lock so overlapping cron runs do not pile up.
*
* @return int Donations whose effects were confirmed applied by this run.
*/
public static function reconcile_effects(): int {
global $wpdb;
$locked = $wpdb && 1 === (int) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', 'sg_reconcile_effects' ) );
if ( ! $locked ) {
return 0;
}
try {
return self::reconcile(
time(),
array( \StreamGoals\PayPal\DonationStore::class, 'unapplied_completed_ids' ),
array( \StreamGoals\PayPal\DonationStore::class, 'notify_applied' )
);
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: reconcile failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return 0;
} finally {
$wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', 'sg_reconcile_effects' ) );
}
}
/**
* Pure orchestration (unit-tested).
*
* @param callable $find fn(string $notAfter, string $notBefore, int $limit): int[]
* @param callable $apply fn(int $donationId): bool true once the donation is stamped as applied
*/
public static function reconcile( int $now, callable $find, callable $apply ): int {
$notAfter = gmdate( 'Y-m-d H:i:s', $now - self::RECONCILE_MIN_AGE );
$notBefore = gmdate( 'Y-m-d H:i:s', $now - self::RECONCILE_MAX_AGE_DAYS * 86400 );
$done = 0;
foreach ( (array) $find( $notAfter, $notBefore, self::RECONCILE_BATCH ) as $id ) {
try {
if ( $apply( (int) $id ) ) {
++$done;
}
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: reconcile of donation ' . (int) $id . ' failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
}
}
return $done;
}
/**
* The single definition of "abandoned checkout", mirrored by the DELETE below (MaintenancePurgeTest checks both).
* Never purgeable: not pending, younger than MAX_AGE_DAYS, a test row (goal_id 0), or ANY row carrying PayPal capture
* evidence (a capture id, even from a PENDING/under-review capture: PayPal may still finalize it by webhook).
*
* @param array|object $row status, goal_id, paypal_capture_id, created_at (UTC 'Y-m-d H:i:s')
*/
public static function isPurgeable( array|object $row, int $now ): bool {
$r = (array) $row;
if ( 'pending' !== (string) ( $r['status'] ?? '' ) || (int) ( $r['goal_id'] ?? 0 ) <= 0 ) {
return false;
}
if ( '' !== trim( (string) ( $r['paypal_capture_id'] ?? '' ) ) ) {
return false;
}
$created = strtotime( (string) ( $r['created_at'] ?? '' ) . ' UTC' );
return false !== $created && $created < $now - self::MAX_AGE_DAYS * DAY_IN_SECONDS;
}
/** @return int Number of rows removed. */
+17 -1
View File
@@ -58,8 +58,23 @@ final class ProfanityFilter {
return $this->enabled && array() !== $this->words;
}
/**
* True when at least one word of $text is listed, i.e. filter() would change it. Same rules as filter()
* (whole words, leetspeak, case-insensitive). Used to hold a donor name for moderation. Never throws.
*/
public function matches( string $text ): bool {
$hit = false;
$this->scan( $text, $hit );
return $hit;
}
/** Mask every listed word; everything else is returned byte-for-byte (after UTF-8 scrubbing). */
public function filter( string $text ): string {
$hit = false;
return $this->scan( $text, $hit );
}
private function scan( string $text, bool &$hit ): string {
if ( ! $this->isEnabled() || '' === $text ) {
return $text;
}
@@ -70,13 +85,14 @@ final class ProfanityFilter {
$text = mb_scrub( $text, 'UTF-8' );
$out = preg_replace_callback(
'/[\p{L}\p{M}\p{N}@$!]+/u',
function ( array $m ): string {
function ( array $m ) use ( &$hit ): string {
$tok = $m[0];
// "!" is only a leet char inside a word; trailing/leading punctuation is not part of it.
$core = trim( $tok, '!' );
if ( '' === $core || ! $this->isListed( $core ) ) {
return $tok;
}
$hit = true;
$lead = (int) strspn( $tok, '!' );
$trail = strlen( $tok ) - strlen( rtrim( $tok, '!' ) );
return str_repeat( '!', $lead ) . str_repeat( '*', mb_strlen( $core ) ) . str_repeat( '!', $trail );
+10
View File
@@ -59,6 +59,16 @@ final class Settings {
update_option( 'sg_settings', array_merge( self::all(), $allowed ), false );
}
/** Generates the overlay token if none is stored (a DB write: only from activation or an authenticated admin screen). */
public static function ensure_overlay_token(): string {
$token = (string) self::get( 'overlay_token', '' );
if ( strlen( $token ) < 32 ) {
$token = bin2hex( random_bytes( 16 ) );
self::update( array( 'overlay_token' => $token ) );
}
return $token;
}
public static function fee_calculator(): FeeCalculator {
return new FeeCalculator( (int) self::get( 'fee_percent_bps' ), (int) self::get( 'fee_fixed_minor' ) );
}
+3 -2
View File
@@ -51,9 +51,9 @@ final class Uninstaller {
return array( 'sg_update_release' );
}
/** @return string[] Prefixes of transients whose names carry a suffix (rate limiter hashes, per-user notices). */
/** @return string[] Prefixes of transients whose names carry a suffix (rate limiter hashes, per-user notices, cached PayPal access token, webhook de-dupe markers). */
public static function transient_prefixes(): array {
return array( 'sg_rl_', 'sg_notice_' );
return array( 'sg_rl_', 'sg_notice_', 'sg_pp_token_', 'sg_wh_' );
}
/** Whether this site's saved settings ask for all data to be deleted. */
@@ -82,6 +82,7 @@ final class Uninstaller {
public static function run_site( object $wpdb ): void {
$delete = self::wants_data_deleted( get_option( 'sg_settings', array() ) );
wp_clear_scheduled_hook( self::CRON_HOOK );
wp_clear_scheduled_hook( Maintenance::RECONCILE_HOOK );
self::delete_dynamic_transients( $wpdb );
if ( $delete ) {
self::drop_tables( $wpdb );
+92
View File
@@ -0,0 +1,92 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
use StreamGoals\Core\GoalTargetPolicy;
use StreamGoals\Tiers\TierPolicy;
/**
* Pure, WordPress-free public progress view for the donate form / [streamgoals_progress] / GET /progress.
* Numbers come from Payloads::goal() so they match the overlay exactly. Public-safe fields only (no donor data).
*/
final class Progress {
/** Parse a shortcode yes/no attribute. Unknown or empty values fall back to $default. */
public static function flag( mixed $raw, bool $default ): bool {
if ( is_bool( $raw ) ) {
return $raw;
}
if ( is_array( $raw ) || null === $raw ) {
return $default;
}
$v = strtolower( trim( (string) $raw ) );
if ( in_array( $v, array( 'yes', 'true', '1', 'on' ), true ) ) {
return true;
}
if ( in_array( $v, array( 'no', 'false', '0', 'off' ), true ) ) {
return false;
}
return $default;
}
/**
* @param array<string,mixed> $goal sg_goals row
* @param array<int,array<string,mixed>>|null $tiers raw sg_goal_tiers rows
* @return array{goal_id:int,title:string,currency:string,raised_minor:int,target_minor:int,percent:int,raised_display:string,target_display:string,reached:bool,tier:?array}
*/
public static function payload( array $goal, int $raised, ?array $tiers = null ): array {
$g = Payloads::goal( $goal, $raised, $tiers ?: null );
$tier = null;
$reached = GoalTargetPolicy::isClosedAtTarget( $goal );
if ( isset( $g['tiers'] ) ) {
$cur = $g['tiers']['current'];
if ( null !== $cur ) {
$tier = array(
'index' => (int) $g['tiers']['index'],
'count' => (int) $g['tiers']['count'],
'title' => (string) $cur['title'],
'target_minor' => (int) $cur['target_minor'],
'target_display' => (string) $cur['target_display'],
);
}
$reached = $reached || ! empty( $g['tiers']['all_reached'] );
} else {
$reached = $reached || ( $g['target_minor'] > 0 && $g['raised_minor'] >= $g['target_minor'] );
}
return array(
'goal_id' => (int) ( $goal['id'] ?? 0 ),
'title' => $g['title'],
'currency' => $g['currency'],
'raised_minor' => $g['raised_minor'],
'target_minor' => $g['target_minor'],
'percent' => $reached ? 100 : $g['percent'],
'raised_display' => $g['raised_display'],
'target_display' => $g['target_display'],
'reached' => $reached,
'tier' => $tier,
);
}
/**
* Server-rendered bar (the JS updates this same markup in place). Labels are already translated.
*
* @param array<string,string> $labels reached, of (%1$s raised, %2$s target), tier (%1$s name, %2$s target), label (%s title)
*/
public static function html( array $p, array $labels ): string {
$e = static fn( string $s ): string => htmlspecialchars( $s, ENT_QUOTES, 'UTF-8' );
$pct = max( 0, min( 100, (int) $p['percent'] ) );
$sub = static fn( string $tpl, array $v ): string => (string) preg_replace_callback( '/%(\d)\$s/', static fn( array $m ): string => $v[ (int) $m[1] - 1 ] ?? '', $tpl );
$of = $sub( $labels['of'] ?? '%1$s / %2$s', array( $p['raised_display'], $p['target_display'] ) );
$out = '<div class="sg-progress' . ( $p['reached'] ? ' sg-progress-reached' : '' ) . '" data-goal="' . (int) $p['goal_id'] . '">';
$out .= '<div class="sg-progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' . $pct . '"'
. ' aria-valuetext="' . $e( $p['reached'] ? ( $labels['reached'] ?? '' ) : $of . ' (' . $pct . '%)' ) . '"'
. ' aria-label="' . $e( str_replace( '%s', (string) $p['title'], $labels['label'] ?? '%s' ) ) . '">'
. '<span class="sg-progress-fill" style="width:' . $pct . '%"></span></div>';
$out .= '<div class="sg-progress-text"><span class="sg-progress-amounts">' . $e( $of ) . '</span> <span class="sg-progress-pct">' . $pct . '%</span></div>';
$out .= '<p class="sg-progress-tier"' . ( $p['tier'] ? '' : ' hidden' ) . '>'
. ( $p['tier'] ? $e( $sub( $labels['tier'] ?? '%1$s (%2$s)', array( $p['tier']['title'], $p['tier']['target_display'] ) ) ) : '' ) . '</p>';
$out .= '<p class="sg-progress-done"' . ( $p['reached'] ? '' : ' hidden' ) . '>' . $e( $p['reached'] ? ( $labels['reached'] ?? '' ) : '' ) . '</p>';
return $out . '</div>';
}
}
+13 -3
View File
@@ -23,17 +23,20 @@ final class CaptureFinalizer {
* @param object|array $row Donation row (status, total_minor, currency).
* @param callable $markCompleted fn(int $id, string $captureId): bool atomic pending->completed
* @param callable $notifyApplied fn(int $id): void
* @param callable|null $recordCapture fn(int $id, string $captureId): void Called when PayPal returned a capture id but the
* donation is NOT finalized (PENDING/under review/amount mismatch). Persists the id so the
* row is never mistaken for an abandoned checkout and the later webhook can find it.
*/
public static function finalize( object|array $row, string $paypalStatus, string $captureId, ?Money $amount, callable $markCompleted, callable $notifyApplied ): string {
public static function finalize( object|array $row, string $paypalStatus, string $captureId, ?Money $amount, callable $markCompleted, callable $notifyApplied, ?callable $recordCapture = null ): string {
$r = (object) $row;
if ( 'pending' !== (string) $r->status ) {
return self::DUPLICATE;
}
if ( 'COMPLETED' !== $paypalStatus || '' === $captureId ) {
return self::PENDING;
return self::pendingWith( $r, $captureId, $recordCapture );
}
if ( ! $amount || $amount->minor !== (int) $r->total_minor || $amount->currency !== (string) $r->currency ) {
return self::PENDING;
return self::pendingWith( $r, $captureId, $recordCapture );
}
if ( $markCompleted( (int) $r->id, $captureId ) ) {
$notifyApplied( (int) $r->id );
@@ -41,4 +44,11 @@ final class CaptureFinalizer {
}
return self::DUPLICATE;
}
private static function pendingWith( object $r, string $captureId, ?callable $recordCapture ): string {
if ( '' !== $captureId && null !== $recordCapture ) {
$recordCapture( (int) $r->id, $captureId );
}
return self::PENDING;
}
}
+4 -3
View File
@@ -116,9 +116,10 @@ final class Client {
* @param array<string,mixed> $headers Incoming webhook request headers (any case; '-' or '_').
*/
public function verifyWebhook( array $headers, string $rawBody, string $webhookId ): bool {
$h = array();
foreach ( $headers as $k => $v ) {
$h[ strtolower( str_replace( '-', '_', (string) $k ) ) ] = is_array( $v ) ? (string) ( $v[0] ?? '' ) : (string) $v;
$h = WebhookGuard::normalizeHeaders( $headers );
// Local pre-checks (headers present, paypal.com cert_url, replay window, size): never spend an outbound call on junk.
if ( null !== WebhookGuard::check( $headers, $rawBody, time() ) ) {
return false;
}
$event = json_decode( $rawBody );
if ( ! is_object( $event ) || '' === $webhookId ) {
+67 -16
View File
@@ -60,9 +60,10 @@ final class DonationStore {
'message' => $v['message'],
'status' => 'pending',
'moderation' => $v['moderation'],
'moderation_flags' => (string) ( $v['moderation_flags'] ?? '' ),
'created_at' => gmdate( 'Y-m-d H:i:s' ),
),
array( '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s' )
array( '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s' )
);
return $ok ? (int) $wpdb->insert_id : 0;
}
@@ -84,37 +85,85 @@ final class DonationStore {
return 1 === $n;
}
/** Hand a freshly completed donation to the rules engine (if present). Never throws. */
public static function notify_applied( int $id ): void {
self::call_engine( 'applyDonation', $id );
/**
* Remember the PayPal capture id of a capture that is not final yet (PENDING / under review). Only touches a
* still-pending row that has no capture id; never changes the status. This is the "PayPal took the money" evidence
* that keeps Maintenance::purge_abandoned away and lets the COMPLETED webhook find the row by capture id.
*/
public static function record_capture_id( int $id, string $captureId ): bool {
global $wpdb;
if ( '' === $captureId ) {
return false;
}
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET paypal_capture_id = %s WHERE id = %d AND status = 'pending' AND (paypal_capture_id IS NULL OR paypal_capture_id = '')", $captureId, $id ) );
return 1 === $n;
}
/**
* Run every side effect of a completed donation (rules/timer/counter, rewards, tiers, end-at-target) and, only if ALL of
* them finished without error, stamp sg_donations.effects_applied_at. Never throws. Every step is idempotent, so this is
* also what Maintenance::reconcile_effects() replays for a donation whose request died after mark_completed().
*
* @return bool True when the donation is (now) marked as fully applied.
*/
public static function notify_applied( int $id ): bool {
$ok = self::call_engine( 'applyDonation', $id );
// Donation actions (rewards). Not under the goal lock: events are idempotent via a UNIQUE key. Never throws.
try {
\StreamGoals\Actions\Recorder::forDonation( $id );
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: Recorder failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
if ( ! \StreamGoals\Actions\Recorder::forDonation( $id ) ) {
$ok = false;
}
// Goal tiers: unlock every tier this donation reaches. MUST run before the close-at-target check below
// (the final tier's target is the goal target). Own try/catch; never throws, never delays a capture.
try {
\StreamGoals\Tiers\Recorder::forDonation( $id );
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: tier unlock failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
if ( null === \StreamGoals\Tiers\Recorder::forDonationChecked( $id ) ) {
$ok = false;
}
self::close_goal_if_target_reached( $id );
if ( ! self::close_goal_if_target_reached( $id ) ) {
$ok = false;
}
return $ok && self::mark_effects_applied( $id );
}
/** Stamp "side effects applied" once. Only a completed row with a NULL stamp is touched (first stamp wins). */
public static function mark_effects_applied( int $id ): bool {
global $wpdb;
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET effects_applied_at = %s WHERE id = %d AND status = 'completed' AND effects_applied_at IS NULL", gmdate( 'Y-m-d H:i:s' ), $id ) );
return false !== $n;
}
/**
* Completed donations whose side effects were never confirmed: completed, effects_applied_at NULL, a real goal
* (test rows use goal_id 0), created between $notBefore and $notAfter (UTC 'Y-m-d H:i:s'; the lower bound keeps a
* permanently failing row from being retried forever, the upper bound leaves in-flight requests alone). Oldest first.
*
* @return int[]
*/
public static function unapplied_completed_ids( string $notAfter, string $notBefore, int $limit ): array {
global $wpdb;
$ids = $wpdb->get_col( $wpdb->prepare(
'SELECT id FROM ' . self::t( 'donations' ) . " WHERE status = 'completed' AND effects_applied_at IS NULL AND goal_id > 0 AND created_at < %s AND created_at >= %s ORDER BY id ASC LIMIT %d",
$notAfter,
$notBefore,
max( 1, $limit )
) );
return array_map( 'intval', (array) $ids );
}
/**
* "End at target": runs after the donation is already completed and counted, so it can never refuse or
* undo a capture. Failures are logged and swallowed. Idempotent (atomic UPDATE ... WHERE status='active').
*
* @return bool False when the check failed.
*/
public static function close_goal_if_target_reached( int $donationId ): void {
public static function close_goal_if_target_reached( int $donationId ): bool {
try {
$row = self::find( $donationId );
if ( $row && (int) $row->goal_id > 0 ) {
( new \StreamGoals\Core\GoalRepository() )->closeIfTargetReached( (int) $row->goal_id );
}
return true;
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: end-at-target check failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return false;
}
}
@@ -124,10 +173,10 @@ final class DonationStore {
return (array) $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'complete' AND close_at_target = 1 ORDER BY id DESC LIMIT 20", ARRAY_A );
}
private static function call_engine( string $method, int $id ): void {
private static function call_engine( string $method, int $id ): bool {
$row = self::find( $id );
if ( ! $row ) {
return;
return false; // vanished row: nothing to apply, and never claim success
}
try {
$donation = \StreamGoals\Core\DonationRepository::toDonation( (array) $row );
@@ -137,8 +186,10 @@ final class DonationStore {
\StreamGoals\Rules\Engine::default()->$method( $donation );
}
);
return true;
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: Engine::' . $method . ' failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return false;
}
}
}
+17 -5
View File
@@ -19,7 +19,7 @@ final class OrderValidator {
* @param array $input Raw client params (goal_id, amount, display_name, anonymous, message, cover_fees).
* @param array $goal sg_goals row as array (id, currency, status, starts_at, ends_at).
* @param array $settings Settings::all()-shaped array.
* @return array{goal_id:int,currency:string,base_minor:int,fee_minor:int,total_minor:int,donor_name:string,is_anonymous:bool,message:string,cover_fees:bool,moderation:string}
* @return array{goal_id:int,currency:string,base_minor:int,fee_minor:int,total_minor:int,donor_name:string,is_anonymous:bool,message:string,cover_fees:bool,moderation:string,moderation_flags:string}
* @throws ValidationException
*/
public static function validate( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array {
@@ -59,9 +59,20 @@ final class OrderValidator {
}
// Mask profanity before anything is stored (same-length masking, so length checks above still hold).
$filter = new ProfanityFilter( $settings );
$name = $filter->filter( $name );
$message = $filter->filter( $message );
// A donor name that trips the filter is stored masked AND held for moderation (the donation still completes
// and counts). Anonymous names were blanked above, so they can never flag.
$filter = new ProfanityFilter( $settings );
$nameFlagged = '' !== $name && $filter->matches( $name );
$name = $filter->filter( $name );
$message = $filter->filter( $message );
$msgHeld = ! empty( $settings['moderate_messages'] ) && '' !== $message;
$flags = array();
if ( $nameFlagged ) {
$flags[] = 'name';
}
if ( $msgHeld ) {
$flags[] = 'message';
}
return array(
'goal_id' => (int) $goal['id'],
@@ -73,7 +84,8 @@ final class OrderValidator {
'is_anonymous' => $anon,
'message' => $message,
'cover_fees' => $cover,
'moderation' => ( ! empty( $settings['moderate_messages'] ) && '' !== $message ) ? 'pending' : 'approved',
'moderation' => $flags ? 'pending' : 'approved',
'moderation_flags' => implode( ',', $flags ), // '', 'name', 'message' or 'name,message' (why it is held)
);
}
+20
View File
@@ -0,0 +1,20 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/**
* PayPal-Request-Id (idempotency key) builder. Not derivable from the reusable auto-increment id alone: it is an HMAC
* keyed with the site's secret salt over kind + donation id + created_at, so a re-used id (after rows are deleted and
* AUTO_INCREMENT resets) gets a different key, while a retry for the SAME donation stays identical.
*/
final class RequestId {
public const MAX_LENGTH = 108;
public static function make( string $kind, int $donationId, string $createdAt, string $salt ): string {
$kind = preg_replace( '/[^a-z]/', '', strtolower( $kind ) ) ?: 'req';
$h = hash_hmac( 'sha256', $kind . '|' . $donationId . '|' . $createdAt, $salt );
return substr( 'sg-' . $kind . '-' . $h, 0, self::MAX_LENGTH );
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/**
* Cheap, local, pure pre-checks for the public webhook endpoint. They run BEFORE any outbound PayPal call so an
* anonymous flood cannot make this site hit PayPal's API. They are only a filter: PayPal's own
* verify-webhook-signature call stays the authority on whether an event is genuine.
*/
final class WebhookGuard {
public const MAX_BODY_BYTES = 65536;
public const MAX_SKEW_SECONDS = 3600;
public const IP_LIMIT = 120; // per visitor bucket per minute (PayPal retries and uses several IPs)
public const GLOBAL_LIMIT = 600; // whole site per minute
public const WINDOW = 60;
public const REQUIRED = array( 'paypal_transmission_id', 'paypal_transmission_time', 'paypal_transmission_sig', 'paypal_cert_url', 'paypal_auth_algo' );
/** Per-bucket then global fixed-window limit. True when the request may proceed. */
public static function admit( RateLimiter $limiter, string $ipBucket ): bool {
return $limiter->allow( 'webhook|' . $ipBucket, self::IP_LIMIT, self::WINDOW )
&& $limiter->allow( 'webhook|*global*', self::GLOBAL_LIMIT, self::WINDOW );
}
/** Lower-cases header names and maps '-' to '_'. @param array<string,mixed> $headers @return array<string,string> */
public static function normalizeHeaders( array $headers ): array {
$h = array();
foreach ( $headers as $k => $v ) {
$h[ strtolower( str_replace( '-', '_', (string) $k ) ) ] = is_array( $v ) ? (string) ( $v[0] ?? '' ) : (string) $v;
}
return $h;
}
/**
* @param array<string,mixed> $headers
* @return array{status:int,code:string}|null Null when the request may be sent on to PayPal for verification.
*/
public static function check( array $headers, string $rawBody, int $now ): ?array {
if ( strlen( $rawBody ) > self::MAX_BODY_BYTES ) {
return array( 'status' => 413, 'code' => 'sg_webhook_too_large' );
}
$h = self::normalizeHeaders( $headers );
foreach ( self::REQUIRED as $n ) {
if ( '' === trim( $h[ $n ] ?? '' ) ) {
return array( 'status' => 401, 'code' => 'sg_webhook_headers' );
}
}
if ( ! self::isPayPalCertUrl( $h['paypal_cert_url'] ) ) {
return array( 'status' => 401, 'code' => 'sg_webhook_cert_url' );
}
if ( ! self::timeWithinWindow( $h['paypal_transmission_time'], $now ) ) {
return array( 'status' => 401, 'code' => 'sg_webhook_time' );
}
return null;
}
/** https, no credentials/odd port, host is paypal.com or a subdomain of it. */
public static function isPayPalCertUrl( string $url ): bool {
$p = parse_url( trim( $url ) );
if ( ! is_array( $p ) || 'https' !== strtolower( (string) ( $p['scheme'] ?? '' ) ) || isset( $p['user'] ) || isset( $p['pass'] ) ) {
return false;
}
if ( isset( $p['port'] ) && 443 !== (int) $p['port'] ) {
return false;
}
$host = strtolower( (string) ( $p['host'] ?? '' ) );
return 'paypal.com' === $host || ( strlen( $host ) > 11 && str_ends_with( $host, '.paypal.com' ) );
}
/** ISO-8601 timestamp within +-MAX_SKEW_SECONDS of $now; unparsable is rejected. */
public static function timeWithinWindow( string $iso, int $now ): bool {
$iso = trim( $iso );
if ( 1 !== preg_match( '/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})$/', $iso ) ) {
return false;
}
$t = strtotime( $iso );
return false !== $t && abs( $now - $t ) <= self::MAX_SKEW_SECONDS;
}
}
+123 -11
View File
@@ -6,12 +6,14 @@ namespace StreamGoals\Rest;
use StreamGoals\Core\GoalTargetPolicy;
use StreamGoals\Core\Money;
use StreamGoals\Core\Settings;
use StreamGoals\Overlay\Progress;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\Client;
use StreamGoals\PayPal\DonationStore;
use StreamGoals\PayPal\OrderValidator;
use StreamGoals\PayPal\PayPalException;
use StreamGoals\PayPal\RateLimiter;
use StreamGoals\PayPal\RequestId;
use StreamGoals\PayPal\ValidationException;
use StreamGoals\PayPal\WpCache;
@@ -20,9 +22,13 @@ final class DonateController {
private const NS = 'streamgoals/v1';
/** Generous site-wide ceiling for POST /orders (all visitors together). */
public const GLOBAL_ORDERS_PER_MIN = 120;
public static function register(): void {
add_action( 'rest_api_init', array( self::class, 'routes' ) );
add_shortcode( 'streamgoals_donate', array( self::class, 'shortcode' ) );
add_shortcode( 'streamgoals_progress', array( self::class, 'progress_shortcode' ) );
}
public static function routes(): void {
@@ -53,14 +59,44 @@ final class DonateController {
'permission_callback' => '__return_true',
)
);
register_rest_route(
self::NS,
'/progress',
array(
'methods' => 'GET',
'callback' => array( self::class, 'progress_route' ),
'permission_callback' => '__return_true',
'args' => array( 'goal' => array( 'sanitize_callback' => 'absint' ) ),
)
);
}
/* ---------------------------------------------------------------- REST */
/** Public, read-only totals for the progress bar. Whitelisted goal figures only; never donor data. */
public static function progress_route( \WP_REST_Request $req ) {
if ( $limited = self::limit( 'progress', 60, 60 ) ) {
return $limited;
}
$goal = DonationStore::goal( (int) $req->get_param( 'goal' ) );
if ( ! $goal || ! in_array( (string) $goal['status'], array( 'active', 'complete' ), true ) ) {
return new \WP_Error( 'sg_goal_not_found', __( 'Goal not found.', 'streamgoals-donate' ), array( 'status' => 404 ) );
}
$res = rest_ensure_response( self::progress_for( $goal ) );
// Short shared cache lets a CDN collapse bursts; the page JS adds a cache-busting parameter after a donation.
$res->header( 'Cache-Control', 'public, max-age=10, s-maxage=10' );
return $res;
}
public static function create_order( \WP_REST_Request $req ) {
if ( $limited = self::limit( 'order', 10, 300 ) ) {
return $limited;
}
// Site-wide ceiling (checked after the per-visitor limit so one noisy visitor cannot burn it): rotating addresses
// (botnet, IPv6) still cannot flood the pending table or PayPal.
if ( ! ( new RateLimiter( new WpCache() ) )->allow( 'order|*global*', self::GLOBAL_ORDERS_PER_MIN, 60 ) ) {
return new \WP_Error( 'sg_rate_limited', __( 'Too many requests. Please wait a moment.', 'streamgoals-donate' ), array( 'status' => 429 ) );
}
$goal = DonationStore::goal( (int) $req->get_param( 'goal_id' ) );
if ( ! $goal ) {
return new \WP_Error( 'sg_goal_not_found', __( 'Goal not found.', 'streamgoals-donate' ), array( 'status' => 404 ) );
@@ -76,7 +112,7 @@ final class DonateController {
return new \WP_Error( 'sg_db', __( 'Could not start the donation. Please try again.', 'streamgoals-donate' ), array( 'status' => 500 ) );
}
try {
$orderId = Client::fromSettings()->createOrder( new Money( $v['total_minor'], $v['currency'] ), (string) $id, 'sg-order-' . $id );
$orderId = Client::fromSettings()->createOrder( new Money( $v['total_minor'], $v['currency'] ), (string) $id, self::request_id( 'order', $id ) );
} catch ( PayPalException $e ) {
DonationStore::delete( $id );
error_log( 'StreamGoals: create order failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
@@ -104,7 +140,7 @@ final class DonateController {
}
try {
$cap = Client::fromSettings()->captureOrder( $orderId, 'sg-capture-' . $row->id );
$cap = Client::fromSettings()->captureOrder( $orderId, self::request_id( 'capture', (int) $row->id, (string) $row->created_at ) );
} catch ( PayPalException $e ) {
if ( 'ORDER_ALREADY_CAPTURED' === $e->paypalName ) {
$fresh = DonationStore::find( (int) $row->id );
@@ -120,7 +156,8 @@ final class DonateController {
(string) $cap['capture_id'],
$cap['amount'],
array( DonationStore::class, 'mark_completed' ),
array( DonationStore::class, 'notify_applied' )
array( DonationStore::class, 'notify_applied' ),
array( DonationStore::class, 'record_capture_id' )
);
if ( CaptureFinalizer::PENDING === $res ) {
// PENDING capture (e-check/review) or amount mismatch: stay pending; the COMPLETED webhook finalizes it.
@@ -149,8 +186,9 @@ final class DonateController {
/* ----------------------------------------------------------- Shortcode */
public static function shortcode( $atts ): string {
$atts = shortcode_atts( array( 'goal' => '' ), (array) $atts, 'streamgoals_donate' );
$atts = shortcode_atts( array( 'goal' => '', 'show_progress' => 'yes' ), (array) $atts, 'streamgoals_donate' );
$pinned = (int) $atts['goal'];
$showP = Progress::flag( $atts['show_progress'], true );
$s = Settings::all();
if ( '' === (string) $s['paypal_client_id'] ) {
return '<p class="sg-donate-unavailable">' . esc_html__( 'Donations are not available right now.', 'streamgoals-donate' ) . '</p>';
@@ -169,13 +207,15 @@ final class DonateController {
'currency' => strtoupper( (string) $g['currency'] ),
'exp' => Money::exponent( (string) $g['currency'] ),
'actions' => $actions[ (int) $g['id'] ] ?? array(),
);
) + ( $showP ? array( 'progress' => self::progress_for( $g ) ) : array() );
}
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>';
$rg = $pinned ? DonationStore::goal( $pinned ) : ( DonationStore::reached_goals()[0] ?? null );
$bar = ( $showP && $rg ) ? self::progress_markup( self::progress_for( $rg ) ) : '';
return $bar . '<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>';
}
@@ -221,11 +261,68 @@ final class DonateController {
);
wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsDonate=' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' );
return '<div class="sg-donate" data-goal="' . esc_attr( (string) $pinned ) . '"></div>';
self::enqueue_progress();
$first = $showP ? $goals[0]['progress'] : null;
return '<div class="sg-donate" data-goal="' . esc_attr( (string) $pinned ) . '"' . ( $showP ? ' data-progress="1"' : '' ) . '>'
. ( $first ? self::progress_markup( $first ) : '' ) . '</div>';
}
/** [streamgoals_progress goal=""]: the same bar without the form. Server-rendered; JS refreshes it. */
public static function progress_shortcode( $atts ): string {
$atts = shortcode_atts( array( 'goal' => '' ), (array) $atts, 'streamgoals_progress' );
$id = (int) $atts['goal'];
$goal = $id ? DonationStore::goal( $id ) : ( DonationStore::active_goals()[0] ?? ( DonationStore::reached_goals()[0] ?? null ) );
if ( ! $goal || ! in_array( (string) $goal['status'], array( 'active', 'complete' ), true ) ) {
return '';
}
self::enqueue_progress();
return '<div class="sg-donate sg-progress-only">' . self::progress_markup( self::progress_for( $goal ) ) . '</div>';
}
/* ------------------------------------------------------------- Helpers */
/** @return array<string,mixed> Progress::payload() for a goal row (same raised basis and tiers as the overlay). */
private static function progress_for( array $goal ): array {
global $wpdb;
$id = (int) $goal['id'];
$tiers = array();
try {
$tiers = ( new \StreamGoals\Tiers\TierRepository( $wpdb ) )->forGoal( $id );
} catch ( \Throwable $e ) {
$tiers = array();
}
return Progress::payload( $goal, ( new \StreamGoals\Overlay\WpdbDataSource() )->raisedMinor( $goal ), $tiers ?: null );
}
private static function progress_i18n(): array {
return array(
'reached' => __( 'Goal reached', 'streamgoals-donate' ),
/* translators: 1: formatted amount raised, 2: formatted target */
'of' => __( '%1$s of %2$s', 'streamgoals-donate' ),
/* translators: 1: current tier name, 2: formatted tier target */
'tier' => __( 'Current tier: %1$s (target %2$s)', 'streamgoals-donate' ),
/* translators: %s: goal title */
'label' => __( 'Progress towards %s', 'streamgoals-donate' ),
);
}
private static function progress_markup( array $p ): string {
return Progress::html( $p, self::progress_i18n() );
}
/** Enqueue assets and the (once per page) config the bar's JS needs. */
private static function enqueue_progress(): void {
static $done = false;
wp_enqueue_style( 'streamgoals-donate', STREAMGOALS_URL . 'assets/donate/donate.css', array(), STREAMGOALS_VERSION );
wp_enqueue_script( 'streamgoals-donate', STREAMGOALS_URL . 'assets/donate/donate.js', array(), STREAMGOALS_VERSION, true );
if ( $done ) {
return;
}
$done = true;
$cfg = array( 'restUrl' => esc_url_raw( rest_url( self::NS ) ), 'i18n' => self::progress_i18n(), 'pollMs' => 30000 );
wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsProgress=' . wp_json_encode( $cfg, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' );
}
/**
* "Next unlock" hint for a tiered goal: the current (first unreached) tier's title and the amount still needed, in minor units.
* Null for goals without tiers or with every tier reached. Computed when the page renders.
@@ -302,7 +399,25 @@ final class DonateController {
);
}
/** Idempotency key, stable per donation (created_at is stored), not derivable from the id alone. */
private static function request_id( string $kind, int $id, ?string $createdAt = null ): string {
if ( null === $createdAt ) {
$row = DonationStore::find( $id );
$createdAt = $row ? (string) $row->created_at : '';
}
return RequestId::make( $kind, $id, $createdAt, wp_salt( 'auth' ) );
}
private static function limit( string $bucket, int $max, int $window ): ?\WP_Error {
$ip = self::visitor_bucket();
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
return null;
}
return new \WP_Error( 'sg_rate_limited', __( 'Too many requests. Please wait a moment.', 'streamgoals-donate' ), array( 'status' => 429 ) );
}
/** Rate-limit bucket for the current visitor (resolved IP, IPv6 collapsed to its /64). */
public static function visitor_bucket(): string {
$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 ] ) ) {
@@ -310,9 +425,6 @@ final class DonateController {
}
}
$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;
}
return new \WP_Error( 'sg_rate_limited', __( 'Too many requests. Please wait a moment.', 'streamgoals-donate' ), array( 'status' => 429 ) );
return \StreamGoals\Core\ClientIp::bucketKey( $ip );
}
}
+17 -8
View File
@@ -30,18 +30,27 @@ final class OverlayController {
) );
}
/** Lazily generates the token (32 hex chars) on first use. */
public static function token(): string {
/** Read-only. The stored token, or '' when none is configured. Safe for public requests. */
public static function current_token(): string {
$token = (string) Settings::get( 'overlay_token', '' );
if ( strlen( $token ) < 32 ) {
$token = bin2hex( random_bytes( 16 ) );
Settings::update( array( 'overlay_token' => $token ) );
}
return $token;
return strlen( $token ) >= 32 ? $token : '';
}
/**
* Token for the admin screens; generates one (a DB write) if missing, but ONLY for a user who can manage options.
* Public requests must never reach this; they use verify_token(), which never writes.
*/
public static function ensure_token(): string {
if ( ! current_user_can( 'manage_options' ) ) {
return '';
}
return Settings::ensure_overlay_token();
}
/** Read-only compare; with no token configured nothing matches (callers answer 404). */
public static function verify_token( string $given ): bool {
return hash_equals( self::token(), $given );
$token = self::current_token();
return '' !== $token && hash_equals( $token, $given );
}
public static function handle( \WP_REST_Request $req ): \WP_REST_Response|\WP_Error {
+9
View File
@@ -7,7 +7,9 @@ use StreamGoals\Core\Settings;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\Client;
use StreamGoals\PayPal\DonationStore;
use StreamGoals\PayPal\RateLimiter;
use StreamGoals\PayPal\WebhookEvent;
use StreamGoals\PayPal\WebhookGuard;
use StreamGoals\PayPal\WpCache;
/** PayPal webhook receiver. Signature is verified through PayPal's API before anything is trusted. */
@@ -34,7 +36,14 @@ final class WebhookController {
if ( '' === $webhookId ) {
return new \WP_Error( 'sg_webhook_unconfigured', 'Webhook is not configured.', array( 'status' => 503 ) );
}
if ( ! WebhookGuard::admit( new RateLimiter( new WpCache() ), DonateController::visitor_bucket() ) ) {
return new \WP_Error( 'sg_rate_limited', 'Too many requests.', array( 'status' => 429 ) );
}
$raw = $req->get_body();
$bad = WebhookGuard::check( $req->get_headers(), $raw, time() );
if ( null !== $bad ) {
return new \WP_Error( $bad['code'], 'Rejected.', array( 'status' => $bad['status'] ) );
}
if ( ! Client::fromSettings()->verifyWebhook( $req->get_headers(), $raw, $webhookId ) ) {
return new \WP_Error( 'sg_webhook_signature', 'Invalid signature.', array( 'status' => 401 ) );
}
+6 -1
View File
@@ -12,6 +12,11 @@ final class Recorder {
* @return int[] ids of the tiers this call unlocked.
*/
public static function forDonation( int $donationId ): array {
return self::forDonationChecked( $donationId ) ?? array();
}
/** Same as forDonation() but null (instead of an empty list) when something failed. Never throws. @return int[]|null */
public static function forDonationChecked( int $donationId ): ?array {
try {
global $wpdb;
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT id, goal_id, status FROM ' . $wpdb->prefix . 'sg_donations WHERE id = %d', $donationId ), ARRAY_A );
@@ -27,7 +32,7 @@ final class Recorder {
return $repo->markReached( $goalId, $raised, $donationId );
} catch ( \Throwable $e ) {
error_log( 'StreamGoals: tier unlock failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
return array();
return null;
}
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Update;
/**
* Pure decisions for redirects of token-bearing update requests. The access token may only ever travel to the pinned
* host over https; a redirect is followed (by Updater) only when it stays on that host, with a small hop limit.
*/
final class RedirectPolicy {
public const MAX_HOPS = 3;
/**
* @param string $current URL that answered with a 3xx.
* @param string $location Its Location header (absolute or relative).
* @param string $pinnedHost Configured update host (lower case).
* @param int $hop Redirects already followed (0 for the first 3xx).
* @return string|null Absolute URL to follow with the token, or null to stop and NOT follow.
*/
public static function nextUrl( string $current, string $location, string $pinnedHost, int $hop ): ?string {
if ( $hop >= self::MAX_HOPS || '' === trim( $location ) || preg_match( '/[\x00-\x1f\x7f]/', $location ) ) {
return null;
}
$abs = self::resolve( $current, trim( $location ) );
if ( null === $abs || ! ReleaseParser::isAllowedUrl( $abs, $pinnedHost ) ) {
return null;
}
$port = parse_url( $abs, PHP_URL_PORT );
return null === $port || 443 === (int) $port ? $abs : null;
}
/** Whether the token may be attached to a request for $url. */
public static function tokenAllowed( string $url, string $pinnedHost ): bool {
if ( ! ReleaseParser::isAllowedUrl( $url, $pinnedHost ) ) {
return false;
}
$port = parse_url( $url, PHP_URL_PORT );
return null === $port || 443 === (int) $port;
}
private static function resolve( string $base, string $loc ): ?string {
if ( 1 === preg_match( '#^[a-z][a-z0-9+.\-]*://#i', $loc ) ) {
return $loc;
}
$b = parse_url( $base );
if ( ! is_array( $b ) || ! isset( $b['scheme'], $b['host'] ) ) {
return null;
}
if ( str_starts_with( $loc, '//' ) ) {
return $b['scheme'] . ':' . $loc;
}
$origin = $b['scheme'] . '://' . $b['host'] . ( isset( $b['port'] ) ? ':' . $b['port'] : '' );
if ( str_starts_with( $loc, '/' ) ) {
return $origin . $loc;
}
$dir = preg_replace( '#/[^/]*$#', '/', (string) ( $b['path'] ?? '/' ) );
return $origin . $dir . $loc;
}
}
+46 -1
View File
@@ -29,6 +29,7 @@ final class Updater {
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_filter( 'pre_http_request', array( self::class, 'followSafely' ), 10, 3 );
add_action( 'upgrader_process_complete', array( self::class, 'afterUpgrade' ), 10, 2 );
add_action( 'admin_post_' . self::ACTION_CHECK, array( self::class, 'handleCheck' ) );
}
@@ -170,7 +171,7 @@ final class Updater {
}
$token = trim( (string) Settings::get( 'update_token', '' ) );
$host = self::repo()['host'];
if ( '' === $token || ! ReleaseParser::isAllowedUrl( $url, $host ) ) {
if ( '' === $token || ! RedirectPolicy::tokenAllowed( $url, $host ) ) {
return $args;
}
$args['headers'] = is_array( $args['headers'] ?? null ) ? $args['headers'] : array();
@@ -181,6 +182,50 @@ final class Updater {
return $args;
}
private static bool $following = false;
/**
* Token-bearing requests never let HTTP redirect handling carry the Authorization header anywhere: we send the
* request with redirection disabled and follow a 3xx ourselves ONLY while it stays on the pinned host (max 3 hops).
* A redirect to any other host is not followed at all, so the token cannot leak and the update fails closed.
*/
public static function followSafely( mixed $pre, mixed $args, mixed $url ): mixed {
if ( false !== $pre || self::$following || ! is_array( $args ) || ! is_string( $url ) ) {
return $pre;
}
$headers = is_array( $args['headers'] ?? null ) ? $args['headers'] : array();
$has = false;
foreach ( array_keys( $headers ) as $k ) {
$has = $has || 'authorization' === strtolower( (string) $k );
}
$host = self::repo()['host'];
if ( ! $has || ! RedirectPolicy::tokenAllowed( $url, $host ) ) {
return $pre;
}
self::$following = true;
try {
$current = $url;
$resp = null;
for ( $hop = 0; $hop <= RedirectPolicy::MAX_HOPS; $hop++ ) {
$a = $args;
$a['redirection'] = 0;
$resp = wp_remote_request( $current, $a );
$code = is_wp_error( $resp ) ? 0 : (int) wp_remote_retrieve_response_code( $resp );
if ( $code < 300 || $code >= 400 || is_wp_error( $resp ) ) {
return $resp;
}
$next = RedirectPolicy::nextUrl( $current, (string) wp_remote_retrieve_header( $resp, 'location' ), $host, $hop );
if ( null === $next ) {
return $resp; // not followed: the caller sees the 3xx and fails
}
$current = $next;
}
return $resp;
} finally {
self::$following = false;
}
}
public static function afterUpgrade( mixed $upgrader, mixed $options ): void {
if ( is_array( $options ) && ( $options['type'] ?? '' ) === 'plugin' ) {
self::clearCache();
+8
View File
@@ -5,6 +5,7 @@ namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Admin\Csv;
use StreamGoals\Admin\DonationsPage;
use StreamGoals\Admin\Format;
use StreamGoals\Admin\Input;
use StreamGoals\Admin\RuleConfig;
@@ -133,4 +134,11 @@ final class AdminLogicTest extends TestCase {
$this->assertTrue( Format::isTest( array( 'paypal_order_id' => 'TEST-abc' ) ) );
$this->assertFalse( Format::isTest( array( 'paypal_order_id' => '5O1234' ) ) );
}
public function test_after_moderation_redirect_only_to_registered_page(): void {
$this->assertSame( 'streamgoals-donations', DonationsPage::afterModerationPage( false, 0 ) );
$this->assertSame( 'streamgoals-moderation', DonationsPage::afterModerationPage( false, 2 ) );
$this->assertSame( 'streamgoals-moderation', DonationsPage::afterModerationPage( true, 0 ) );
$this->assertSame( 'streamgoals-moderation', DonationsPage::afterModerationPage( true, 5 ) );
}
}
+25 -1
View File
@@ -79,5 +79,29 @@ final class ClientIpTest extends TestCase {
$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' ) ) );
}
}
public function test_bucket_key_ipv4_unchanged_and_unknown_stays(): void {
$this->assertSame( '203.0.113.9', ClientIp::bucketKey( '203.0.113.9' ) );
$this->assertSame( 'unknown', ClientIp::bucketKey( 'unknown' ) );
}
public function test_bucket_key_ipv6_collapses_to_slash_64(): void {
$a = ClientIp::bucketKey( '2001:db8:abcd:12::1' );
$b = ClientIp::bucketKey( '2001:0db8:abcd:0012:ffff:eeee:dddd:cccc' );
$this->assertSame( $a, $b, 'same /64 must share a bucket' );
$this->assertSame( '20010db8abcd0012/64', $a );
$this->assertNotSame( $a, ClientIp::bucketKey( '2001:db8:abcd:13::1' ), 'different /64 must differ' );
$this->assertNotSame( $a, ClientIp::bucketKey( '203.0.113.9' ) );
}
public function test_bucket_key_ipv4_mapped_ipv6_maps_to_the_ipv4(): void {
$this->assertSame( '203.0.113.9', ClientIp::bucketKey( '::ffff:203.0.113.9' ) );
$this->assertSame( '203.0.113.9', ClientIp::bucketKey( '::ffff:cb00:7109' ) );
}
public function test_bucket_key_garbage_becomes_unknown(): void {
foreach ( array( '', 'garbage', '999.1.1.1', '<script>', 'fe80::1%eth0' ) as $g ) {
$this->assertSame( 'unknown', ClientIp::bucketKey( $g ), $g );
}
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Admin\Format;
use StreamGoals\Core\FeeCalculator;
use StreamGoals\Core\ProfanityFilter;
use StreamGoals\Core\Settings;
use StreamGoals\Overlay\Payloads;
use StreamGoals\PayPal\OrderValidator;
/** A donor name that trips the profanity filter is masked, the donation is held for moderation, and no alert shows it. */
final class DonorNameFlaggingTest extends TestCase {
private function validate( array $in, array $settings = array() ): array {
$goal = array( 'id' => 3, 'currency' => 'USD', 'status' => 'active', 'starts_at' => null, 'ends_at' => null );
return OrderValidator::validate( $in + array( 'amount' => '10.00' ), $goal, array_merge( Settings::defaults(), array( 'moderate_messages' => false ), $settings ), new FeeCalculator( 349, 49 ), 1800000000 );
}
public function test_matches_agrees_with_filter(): void {
$f = new ProfanityFilter( array( 'profanity_words' => 'jerk' ) );
$this->assertTrue( $f->matches( 'Big Jerk' ) );
$this->assertTrue( $f->matches( 'sh1t head' ), 'leetspeak counts' );
$this->assertFalse( $f->matches( 'Scunthorpe class' ) );
$this->assertFalse( $f->matches( '' ) );
$this->assertFalse( ( new ProfanityFilter( array( 'profanity_filter' => false ) ) )->matches( 'shit' ) );
}
public function test_flagged_name_is_masked_and_held_even_when_message_moderation_is_off(): void {
$v = $this->validate( array( 'display_name' => 'Big Jerk', 'message' => 'thanks' ), array( 'profanity_words' => 'jerk' ) );
$this->assertSame( 'Big ****', $v['donor_name'] );
$this->assertSame( 'pending', $v['moderation'] );
$this->assertSame( 'name', $v['moderation_flags'] );
}
public function test_clean_name_and_off_switch_stay_approved(): void {
$v = $this->validate( array( 'display_name' => 'Ann', 'message' => 'hi' ) );
$this->assertSame( array( 'approved', '' ), array( $v['moderation'], $v['moderation_flags'] ) );
$v = $this->validate( array( 'display_name' => 'shit', 'message' => '' ), array( 'profanity_filter' => false ) );
$this->assertSame( array( 'approved', '' ), array( $v['moderation'], $v['moderation_flags'] ) );
$this->assertSame( 'shit', $v['donor_name'] );
}
public function test_message_only_and_both_flags(): void {
$v = $this->validate( array( 'display_name' => 'Ann', 'message' => 'hello' ), array( 'moderate_messages' => true ) );
$this->assertSame( array( 'pending', 'message' ), array( $v['moderation'], $v['moderation_flags'] ) );
$v = $this->validate( array( 'display_name' => 'shit', 'message' => 'hello' ), array( 'moderate_messages' => true ) );
$this->assertSame( array( 'pending', 'name,message' ), array( $v['moderation'], $v['moderation_flags'] ) );
$v = $this->validate( array( 'display_name' => 'shit', 'message' => '' ), array( 'moderate_messages' => true ) );
$this->assertSame( 'name', $v['moderation_flags'], 'empty message is never flagged' );
}
public function test_anonymous_donor_name_never_stored_and_never_flags(): void {
$v = $this->validate( array( 'display_name' => 'shit', 'anonymous' => true, 'message' => '' ) );
$this->assertSame( '', $v['donor_name'] );
$this->assertSame( array( 'approved', '' ), array( $v['moderation'], $v['moderation_flags'] ) );
$v = $this->validate( array( 'display_name' => 'shit', 'message' => '' ), array( 'anonymity_policy' => 'force_anonymous' ) );
$this->assertSame( 'approved', $v['moderation'] );
}
public function test_flagged_label(): void {
$this->assertSame( 'Name', Format::flaggedLabel( array( 'moderation_flags' => 'name' ) ) );
$this->assertSame( 'Message', Format::flaggedLabel( array( 'moderation_flags' => 'message' ) ) );
$this->assertSame( 'Name and message', Format::flaggedLabel( array( 'moderation_flags' => 'name,message' ) ) );
$this->assertSame( 'Message', Format::flaggedLabel( array( 'moderation_flags' => '' ) ), 'rows held before v6' );
$this->assertSame( 'Message', Format::flaggedLabel( array() ) );
}
public function test_alert_for_held_name_is_not_emitted_until_approved_then_shows_masked_name(): void {
$row = array( 'id' => 5, 'base_minor' => 500, 'currency' => 'USD', 'donor_name' => 'Big ****', 'is_anonymous' => 0,
'message' => '', 'status' => 'completed', 'moderation' => 'pending' );
foreach ( array( 'pending', 'rejected' ) as $m ) {
foreach ( array( false, true ) as $recent ) {
$out = Payloads::alerts( array( array( 'moderation' => $m ) + $row ), 0, 10, $recent );
$this->assertSame( array(), $out['alerts'], "$m (recent=" . (int) $recent . ') must hold the whole alert' );
}
}
$out = Payloads::alerts( array( array( 'moderation' => 'approved' ) + $row ), 0 );
$this->assertSame( 'Big ****', $out['alerts'][0]['name'] );
}
public function test_flags_are_wired_through_storage_and_data_sources(): void {
$root = dirname( __DIR__, 2 ) . '/includes/';
$this->assertStringContainsString( "'moderation_flags' => (string)", (string) file_get_contents( $root . 'PayPal/DonationStore.php' ) );
$this->assertStringContainsString( 'moderation_flags VARCHAR(16) NOT NULL DEFAULT', (string) file_get_contents( $root . 'Core/Installer.php' ) );
foreach ( array( 'Overlay/WpdbDataSource.php', 'Core/DonationRepository.php' ) as $f ) {
$this->assertStringContainsString( "moderation = 'approved'", (string) file_get_contents( $root . $f ), $f );
}
}
}
+339
View File
@@ -0,0 +1,339 @@
<?php
declare( strict_types=1 );
namespace {
if ( ! defined( 'ARRAY_A' ) ) {
define( 'ARRAY_A', 'ARRAY_A' );
}
if ( ! class_exists( 'wpdb' ) ) {
/** Scripted stand-in so DonationStore::notify_applied() can run its real wiring without WordPress. */
class wpdb {
public string $prefix = 'wp_';
public array $sql = array();
public bool $failRules = false;
public array $ids = array( 7 );
public function prepare( string $q, ...$args ): string {
$i = 0;
return (string) preg_replace_callback( '/%[dsf]/', static function ( $m ) use ( &$i, $args ) {
$v = $args[ $i++ ];
return '%s' === $m[0] ? "'" . $v . "'" : (string) $v;
}, $q );
}
public function get_row( string $q, $out = 'OBJECT' ) {
$this->sql[] = $q;
$row = array( 'id' => 7, 'goal_id' => 1, 'base_minor' => 500, 'fee_minor' => 0, 'total_minor' => 500, 'currency' => 'USD', 'status' => 'completed', 'close_at_target' => 0 );
return 'ARRAY_A' === $out ? $row : (object) $row;
}
public function get_results( string $q, $out = null ): array {
$this->sql[] = $q;
if ( $this->failRules && str_contains( $q, 'sg_rules' ) ) {
throw new \RuntimeException( 'db gone' );
}
return array();
}
public function get_var( string $q ) {
$this->sql[] = $q;
return str_contains( $q, 'GET_LOCK' ) ? 1 : null;
}
public function get_col( string $q ): array {
$this->sql[] = $q;
return $this->ids;
}
public function query( string $q ) {
$this->sql[] = $q;
return 1;
}
}
}
}
namespace StreamGoals\Tests\Unit {
use PHPUnit\Framework\TestCase;
use StreamGoals\Actions\ActionRepository;
use StreamGoals\Core\Installer;
use StreamGoals\Core\Maintenance;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\DonationStore;
use StreamGoals\Rules\Donation;
use StreamGoals\Rules\Engine;
use StreamGoals\Rules\RuleDef;
use StreamGoals\Tiers\TierRepository;
final class EffectsReconciliationTest extends TestCase {
private $prevDb;
protected function setUp(): void {
$this->prevDb = $GLOBALS['wpdb'] ?? null;
$GLOBALS['wpdb'] = new \wpdb();
}
protected function tearDown(): void {
$GLOBALS['wpdb'] = $this->prevDb;
}
private function stamps( object $db ): array {
return array_values( array_filter( $db->sql, static fn( $q ) => str_contains( $q, 'SET effects_applied_at' ) ) );
}
// ---- stamping ---------------------------------------------------------------------------------------
public function test_notify_applied_stamps_only_when_every_step_succeeded(): void {
$db = $GLOBALS['wpdb'];
$this->assertTrue( DonationStore::notify_applied( 7 ) );
$stamps = $this->stamps( $db );
$this->assertCount( 1, $stamps );
$this->assertStringContainsString( "WHERE id = 7 AND status = 'completed' AND effects_applied_at IS NULL", $stamps[0] );
$db->sql = array();
$db->failRules = true; // simulates the engine dying
$this->assertFalse( DonationStore::notify_applied( 7 ) );
$this->assertSame( array(), $this->stamps( $db ), 'a failed side effect must leave effects_applied_at NULL so reconcile retries' );
}
public function test_stamp_is_the_last_step_of_notify_applied(): void {
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/PayPal/DonationStore.php' );
$start = strpos( $src, 'function notify_applied' );
$body = substr( $src, $start, strpos( $src, 'function mark_effects_applied' ) - $start );
$this->assertLessThan( strpos( $body, 'mark_effects_applied' ), strpos( $body, 'close_goal_if_target_reached' ) );
$this->assertLessThan( strpos( $body, 'close_goal_if_target_reached' ), strpos( $body, 'Tiers\\Recorder::forDonationChecked' ), 'tiers still before close-at-target' );
}
public function test_capture_finalizer_still_runs_effects_once_even_if_replayed(): void {
$row = array( 'id' => 7, 'status' => 'pending', 'total_minor' => 500, 'currency' => 'USD' );
$state = (object) array( 'status' => 'pending', 'applied' => 0 );
$mark = static function () use ( $state ): bool {
if ( 'pending' !== $state->status ) {
return false;
}
$state->status = 'completed';
return true;
};
$notify = static function () use ( $state ): void {
$state->applied++;
};
$m = new \StreamGoals\Core\Money( 500, 'USD' );
$this->assertSame( 'completed', CaptureFinalizer::finalize( $row, 'COMPLETED', 'C1', $m, $mark, $notify ) );
$this->assertSame( 'duplicate', CaptureFinalizer::finalize( $row, 'COMPLETED', 'C1', $m, $mark, $notify ), 'webhook replay on a stale pending snapshot' );
$this->assertSame( 'duplicate', CaptureFinalizer::finalize( array( 'status' => 'completed' ) + $row, 'COMPLETED', 'C1', $m, $mark, $notify ) );
$this->assertSame( 1, $state->applied );
}
// ---- reconcile --------------------------------------------------------------------------------------
public function test_reconcile_window_batch_and_counting(): void {
$now = 1800000000;
$seen = array();
$n = Maintenance::reconcile(
$now,
function ( string $after, string $before, int $limit ) use ( &$seen ): array {
$seen = array( strtotime( $after . ' UTC' ), strtotime( $before . ' UTC' ), $limit );
return array( 4, 5, 6 );
},
static function ( int $id ): bool {
if ( 5 === $id ) {
throw new \RuntimeException( 'boom' );
}
return 4 === $id; // 6 "fails" (not stamped)
}
);
$this->assertSame( 1, $n, 'a throwing or failing donation neither aborts the batch nor counts as applied' );
$this->assertSame( $now - 120, $seen[0], 'only donations older than 2 minutes' );
$this->assertSame( $now - 30 * 86400, $seen[1] );
$this->assertSame( Maintenance::RECONCILE_BATCH, $seen[2] );
}
public function test_candidate_query_only_selects_completed_unstamped_real_goal_rows(): void {
$db = $GLOBALS['wpdb'];
$ids = DonationStore::unapplied_completed_ids( '2026-01-02 00:00:00', '2025-12-01 00:00:00', 25 );
$this->assertSame( array( 7 ), $ids );
$q = $db->sql[0];
$this->assertStringContainsString( "status = 'completed' AND effects_applied_at IS NULL AND goal_id > 0", $q );
$this->assertStringContainsString( "created_at < '2026-01-02 00:00:00' AND created_at >= '2025-12-01 00:00:00'", $q );
$this->assertStringNotContainsString( 'UPDATE', $q );
$this->assertStringNotContainsString( 'DELETE', $q );
}
public function test_reconcile_effects_is_single_flight_and_releases_the_lock(): void {
$db = $GLOBALS['wpdb'];
$this->assertSame( 1, Maintenance::reconcile_effects() ); // id 7 -> notify_applied -> stamped
$this->assertNotEmpty( array_filter( $db->sql, static fn( $q ) => str_contains( $q, 'RELEASE_LOCK' ) ) );
$this->assertCount( 1, $this->stamps( $db ) );
$busy = new class() extends \wpdb {
public function get_var( string $q ) {
$this->sql[] = $q;
return 0; // GET_LOCK denied
}
};
$GLOBALS['wpdb'] = $busy;
$this->assertSame( 0, Maintenance::reconcile_effects() );
$this->assertSame( array(), $this->stamps( $busy ) );
}
public function test_cron_schedule_and_hooks(): void {
$s = Maintenance::cron_schedules( array( 'daily' => array() ) );
$this->assertSame( 300, $s[ Maintenance::RECONCILE_SCHEDULE ]['interval'] );
$this->assertArrayHasKey( 'daily', $s );
$this->assertSame( 120, Maintenance::RECONCILE_MIN_AGE );
$root = dirname( __DIR__, 2 ) . '/includes/Core/';
$this->assertStringContainsString( 'wp_clear_scheduled_hook( self::RECONCILE_HOOK )', (string) file_get_contents( $root . 'Maintenance.php' ) );
$this->assertStringContainsString( 'Maintenance::RECONCILE_HOOK', (string) file_get_contents( $root . 'Uninstaller.php' ) );
}
// ---- upgrade ----------------------------------------------------------------------------------------
public function test_installer_v6_schema_and_backfill_ordering(): void {
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
$this->assertSame( '6', Installer::DB_VERSION );
$this->assertStringContainsString( 'effects_applied_at DATETIME NULL,', $src );
$this->assertStringContainsString( "moderation_flags VARCHAR(16) NOT NULL DEFAULT ''", $src );
$this->assertLessThan( strpos( $src, "update_option( 'sg_db_version'" ), strpos( $src, 'backfill_effects_applied()' ), 'version is only recorded after a successful backfill' );
}
public function test_backfill_runs_for_pre_v6_and_fresh_installs_only(): void {
foreach ( array( false, '', '1', '2', '5' ) as $from ) {
$this->assertTrue( Installer::needsEffectsBackfill( $from ), var_export( $from, true ) );
}
$this->assertFalse( Installer::needsEffectsBackfill( '6' ) );
$this->assertFalse( Installer::needsEffectsBackfill( '7' ) );
}
public function test_backfill_stamps_existing_completed_rows_once_and_reports_failure(): void {
$db = $GLOBALS['wpdb'];
$this->assertTrue( Installer::backfill_effects_applied() );
$q = $db->sql[0];
$this->assertStringContainsString( 'UPDATE wp_sg_donations SET effects_applied_at =', $q );
$this->assertStringContainsString( "WHERE status = 'completed' AND effects_applied_at IS NULL", $q );
$GLOBALS['wpdb'] = new class() extends \wpdb {
public function query( string $q ) {
return false;
}
};
$this->assertFalse( Installer::backfill_effects_applied() );
}
// ---- replay does not double-apply -------------------------------------------------------------------
private function rules(): array {
return array(
new RuleDef( 1, 1, 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ) ),
new RuleDef( 2, 1, 'counter', array( 'step' => 1, 'per_minor' => 1000, 'carry_over' => true ) ),
new RuleDef( 3, 1, 'bonus', array( 'min_minor' => 1000, 'event' => 'big' ) ),
);
}
public function test_engine_replay_after_full_apply_changes_nothing_and_fires_no_second_bonus(): void {
$state = new FakeStateRepository();
$ev = new FakeEventStore();
$fired = 0;
$e = new Engine( new FakeRuleStore( $this->rules() ), $ev, $state, fn(): int => 1000, function () use ( &$fired ): void {
$fired++;
} );
$d = new Donation( 10, 1, 2500, 0, 2500, 'USD' );
$e->applyDonation( $d );
$state1 = $state->data;
$ev1 = $ev->events;
$this->assertSame( 1, $fired );
for ( $i = 0; $i < 3; $i++ ) {
$e->applyDonation( $d );
}
$this->assertSame( $state1, $state->data, 'timer and counter untouched by replays' );
$this->assertSame( $ev1, $ev->events );
$this->assertSame( 1, $fired, 'bonus event fires once' );
}
public function test_engine_replay_after_partial_apply_only_applies_the_missing_rules(): void {
$state = new FakeStateRepository();
$ev = new FakeEventStore();
$d = new Donation( 10, 1, 2500, 0, 2500, 'USD' );
$rules = $this->rules();
// The process died after the timer rule (rule 1) but before the others.
( new Engine( new FakeRuleStore( array( $rules[0] ) ), $ev, $state, fn(): int => 1000 ) )->applyDonation( $d );
$timer = $state->getInt( 1, 'timer_ends_at' );
$this->assertSame( 2500, $timer );
// Later (clock moved on) the reconciler replays with all rules.
( new Engine( new FakeRuleStore( $rules ), $ev, $state, fn(): int => 5000 ) )->applyDonation( $d );
$this->assertSame( $timer, $state->getInt( 1, 'timer_ends_at' ), 'timer must not be added twice' );
$this->assertSame( 1500, $state->getInt( 1, 'timer_added:1' ) );
$this->assertSame( 2, $state->getInt( 1, 'counter:2' ), 'the lost counter effect is recovered' );
$this->assertSame( array( '1:10', '2:10', '3:10' ), array_keys( $ev->events ) );
}
public function test_action_events_replay_is_insert_ignore_on_the_unique_key(): void {
$db = new class() {
public string $prefix = 'wp_';
public array $rows = array();
public function prepare( string $q, ...$args ): string {
$i = 0;
return (string) preg_replace_callback( '/%[dsf]/', static function ( $m ) use ( &$i, $args ) {
$v = $args[ $i++ ];
return '%s' === $m[0] ? "'" . $v . "'" : (string) $v;
}, $q );
}
public function query( string $q ) {
if ( ! str_starts_with( $q, 'INSERT IGNORE' ) || ! preg_match( '/VALUES \((\d+), (\d+),/', $q, $m ) ) {
return 0;
}
$k = $m[1] . ':' . $m[2];
if ( isset( $this->rows[ $k ] ) ) {
return 0; // UNIQUE(donation_id, action_id) swallowed it
}
$this->rows[ $k ] = $q;
return 1;
}
};
$repo = new ActionRepository( $db );
$matches = array( array( 'action_id' => 4, 'title' => 'Beans', 'times' => 5 ), array( 'action_id' => 9, 'title' => 'Pushups', 'times' => 1 ) );
$repo->recordEvents( 10, $matches );
$repo->recordEvents( 10, $matches );
$this->assertCount( 2, $db->rows, 'one queued event per (donation, action) no matter how often it is replayed' );
$this->assertStringContainsString( 'UNIQUE KEY donation_action (donation_id,action_id)', (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' ) );
}
public function test_tier_marks_replay_does_not_reassign_or_re_mark(): void {
$db = new class() {
public string $prefix = 'wp_';
public array $tiers = array(
1 => array( 'id' => '1', 'goal_id' => '7', 'target_minor' => '10000', 'title' => 'A', 'description' => '', 'reached_at' => null, 'reached_donation_id' => null, 'created_at' => '2026-01-01 00:00:00' ),
2 => array( 'id' => '2', 'goal_id' => '7', 'target_minor' => '90000', 'title' => 'B', 'description' => '', 'reached_at' => null, 'reached_donation_id' => null, 'created_at' => '2026-01-01 00:00:00' ),
);
public function prepare( string $q, ...$args ): string {
$i = 0;
return (string) preg_replace_callback( '/%[dsf]/', static function ( $m ) use ( &$i, $args ) {
$v = $args[ $i++ ];
return '%s' === $m[0] ? "'" . $v . "'" : (string) $v;
}, $q );
}
public function get_results( string $q, $o = null ): array {
return array_values( $this->tiers );
}
public function query( string $q ) {
if ( ! preg_match( "/SET reached_at = '([^']+)', reached_donation_id = (\\d+) WHERE id = (\\d+) AND reached_at IS NULL/", $q, $m ) ) {
return 0;
}
if ( null !== $this->tiers[ (int) $m[3] ]['reached_at'] ) {
return 0;
}
$this->tiers[ (int) $m[3] ]['reached_at'] = $m[1];
$this->tiers[ (int) $m[3] ]['reached_donation_id'] = $m[2];
return 1;
}
};
$repo = new TierRepository( $db );
$this->assertSame( array( 1 ), $repo->markReached( 7, 20000, 55 ) );
$this->assertSame( array(), $repo->markReached( 7, 20000, 55 ), 'replay marks nothing' );
$this->assertSame( array(), $repo->markReached( 7, 20000, 56 ), 'a later replay never steals the unlock from donation 55' );
$this->assertSame( '55', $db->tiers[1]['reached_donation_id'] );
$this->assertNull( $db->tiers[2]['reached_at'] );
}
public function test_goal_close_is_conditional_so_replay_cannot_reclose(): void {
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/GoalRepository.php' );
$this->assertStringContainsString( "AND status = 'active' AND close_at_target = 1", $src );
$this->assertStringContainsString( "'active' !== \$goal['status']", $src );
}
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
declare( strict_types=1 );
namespace {
if ( ! function_exists( 'get_option' ) ) {
function get_option( $k, $d = false ) { return array_key_exists( $k, $GLOBALS['sg_test_opts'] ) ? $GLOBALS['sg_test_opts'][ $k ] : $d; }
}
if ( ! function_exists( 'update_option' ) ) {
function update_option( $k, $v, $a = null ) { $GLOBALS['sg_test_opts'][ $k ] = $v; $GLOBALS['sg_test_writes'] = ( $GLOBALS['sg_test_writes'] ?? 0 ) + 1; return true; }
}
if ( ! function_exists( 'current_user_can' ) ) {
function current_user_can( $cap ) { return (bool) ( $GLOBALS['sg_test_can'] ?? false ); }
}
}
namespace StreamGoals\Tests\Unit {
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\Settings;
use StreamGoals\Rest\OverlayController;
/** L5: the overlay token is never created by an unauthenticated request. */
final class OverlayTokenTest extends TestCase {
protected function setUp(): void {
$GLOBALS['sg_test_opts'] = array();
$GLOBALS['sg_test_writes'] = 0;
$GLOBALS['sg_test_can'] = false;
}
public function test_public_verify_with_no_token_is_false_and_writes_nothing(): void {
$this->assertFalse( OverlayController::verify_token( 'anything' ) );
$this->assertFalse( OverlayController::verify_token( '' ) );
$this->assertSame( 0, $GLOBALS['sg_test_writes'], 'unauthenticated request must not write' );
$this->assertSame( '', OverlayController::current_token() );
}
public function test_ensure_token_refuses_without_capability(): void {
$this->assertSame( '', OverlayController::ensure_token() );
$this->assertSame( 0, $GLOBALS['sg_test_writes'] );
}
public function test_admin_generates_once_and_public_compare_then_works(): void {
$GLOBALS['sg_test_can'] = true;
$t = OverlayController::ensure_token();
$this->assertSame( 32, strlen( $t ) );
$this->assertSame( $t, OverlayController::ensure_token(), 'stable' );
$this->assertSame( 1, $GLOBALS['sg_test_writes'] );
$GLOBALS['sg_test_can'] = false;
$this->assertTrue( OverlayController::verify_token( $t ) );
$this->assertFalse( OverlayController::verify_token( str_repeat( 'a', 32 ) ) );
}
public function test_activation_helper_generates_when_missing_and_keeps_existing(): void {
$t = Settings::ensure_overlay_token();
$this->assertSame( 32, strlen( $t ) );
$this->assertSame( $t, Settings::ensure_overlay_token() );
$this->assertSame( 1, $GLOBALS['sg_test_writes'] );
}
}
}
+41 -2
View File
@@ -131,7 +131,7 @@ final class PayPalClientTest extends TestCase {
public function test_verify_webhook_success_and_failure(): void {
$headers = array(
'paypal_transmission_id' => array( 'T1' ), 'PAYPAL-TRANSMISSION-TIME' => '2026-01-01T00:00:00Z',
'paypal_transmission_id' => array( 'T1' ), 'PAYPAL-TRANSMISSION-TIME' => gmdate( 'Y-m-d\TH:i:s\Z' ),
'paypal_transmission_sig' => 'SIG', 'paypal_cert_url' => 'https://api.paypal.com/cert', 'paypal_auth_algo' => 'SHA256withRSA',
);
$raw = '{"id":"WH-1","event_type":"PAYMENT.CAPTURE.COMPLETED"}';
@@ -156,10 +156,49 @@ final class PayPalClientTest extends TestCase {
$c = $this->client();
$this->http->queue = array( new TransportException( 'boom' ) );
$headers['paypal_cert_url'] = 'x';
$headers['paypal_cert_url'] = 'https://api.paypal.com/cert';
$this->assertFalse( $c->verifyWebhook( $headers, $raw, 'WHID' ) );
}
/** @return array<string,string> */
private function goodWebhookHeaders(): array {
return array(
'paypal-transmission-id' => 'T1', 'paypal-transmission-time' => gmdate( 'Y-m-d\TH:i:s\Z' ),
'paypal-transmission-sig' => 'SIG', 'paypal-cert-url' => 'https://api.paypal.com/v1/notifications/certs/CERT-1', 'paypal-auth-algo' => 'SHA256withRSA',
);
}
/** M2: every locally rejectable request must be refused WITHOUT any outbound call (not even the OAuth token). */
public function test_verify_webhook_makes_no_outbound_call_for_locally_rejectable_requests(): void {
$raw = '{"id":"WH-1","event_type":"PAYMENT.CAPTURE.COMPLETED"}';
$cases = array();
foreach ( array_keys( $this->goodWebhookHeaders() ) as $missing ) {
$h = $this->goodWebhookHeaders();
unset( $h[ $missing ] );
$cases[ 'missing ' . $missing ] = array( $h, $raw );
}
foreach ( array( 'http://api.paypal.com/c', 'https://evil.example/c', 'https://paypal.com.evil.example/c', 'https://evilpaypal.com/c', 'https://api.paypal.com@evil.example/c', 'https://user@api.paypal.com/c', 'https://api.paypal.com:8443/c', 'ftp://api.paypal.com/c', 'not a url' ) as $u ) {
$cases[ 'cert ' . $u ] = array( array( 'paypal-cert-url' => $u ) + $this->goodWebhookHeaders(), $raw );
}
foreach ( array( gmdate( 'Y-m-d\TH:i:s\Z', time() - 7200 ), gmdate( 'Y-m-d\TH:i:s\Z', time() + 7200 ), 'yesterday', '', '0' ) as $t ) {
$cases[ 'time ' . $t ] = array( array( 'paypal-transmission-time' => $t ) + $this->goodWebhookHeaders(), $raw );
}
$cases['body too large'] = array( $this->goodWebhookHeaders(), '{"x":"' . str_repeat( 'a', 70000 ) . '"}' );
foreach ( $cases as $name => [ $headers, $body ] ) {
$c = $this->client();
$this->assertFalse( $c->verifyWebhook( $headers, $body, 'WHID' ), $name );
$this->assertCount( 0, $this->http->calls, "outbound call made for: $name" );
}
}
public function test_verify_webhook_still_calls_paypal_for_a_well_formed_request(): void {
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 200, array( 'verification_status' => 'SUCCESS' ) ) );
$this->assertTrue( $c->verifyWebhook( $this->goodWebhookHeaders(), '{"id":"WH-1"}', 'WHID' ) );
$this->assertCount( 2, $this->http->calls );
}
public function test_create_webhook_registers_only_completed_event(): void {
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 201, array( 'id' => 'WH77' ) ) );
+126
View File
@@ -0,0 +1,126 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\Maintenance;
use StreamGoals\Core\Money;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\WebhookEvent;
/** M5: a PENDING PayPal capture must keep its capture id, survive the purge, and be finalized exactly once by the webhook. */
final class PendingCaptureFlowTest extends TestCase {
/** @var array<int,array<string,mixed>> */
private array $rows = array();
private int $notified = 0;
protected function setUp(): void {
foreach ( array( 'HOUR_IN_SECONDS' => 3600, 'DAY_IN_SECONDS' => 86400 ) as $k => $v ) {
if ( ! defined( $k ) ) {
define( $k, $v );
}
}
$this->notified = 0;
$this->rows = array(
1 => array( 'id' => 1, 'goal_id' => 3, 'status' => 'pending', 'total_minor' => 1099, 'currency' => 'USD', 'paypal_order_id' => 'ORD1', 'paypal_capture_id' => null, 'created_at' => gmdate( 'Y-m-d H:i:s', time() - 30 * 86400 ) ),
);
}
private function record(): callable {
return function ( int $id, string $cap ): bool {
if ( 'pending' === $this->rows[ $id ]['status'] && empty( $this->rows[ $id ]['paypal_capture_id'] ) ) {
$this->rows[ $id ]['paypal_capture_id'] = $cap;
return true;
}
return false;
};
}
private function mark(): callable {
return function ( int $id, string $cap ): bool {
if ( 'pending' !== $this->rows[ $id ]['status'] ) {
return false;
}
$this->rows[ $id ]['status'] = 'completed';
$this->rows[ $id ]['paypal_capture_id'] = $cap;
return true;
};
}
private function notify(): callable {
return function ( int $id ): void { ++$this->notified; };
}
private function purge(): void {
foreach ( $this->rows as $id => $r ) {
if ( Maintenance::isPurgeable( $r, time() ) ) {
unset( $this->rows[ $id ] );
}
}
}
private function webhook(): string {
$ev = WebhookEvent::fromArray( array(
'id' => 'WH-1', 'event_type' => 'PAYMENT.CAPTURE.COMPLETED',
'resource' => array( 'id' => 'CAP1', 'custom_id' => '1', 'amount' => array( 'value' => '10.99', 'currency_code' => 'USD' ), 'supplementary_data' => array( 'related_ids' => array( 'order_id' => 'ORD1' ) ) ),
) );
$row = $this->rows[ (int) $ev->customId ] ?? null;
if ( ! $row ) {
foreach ( $this->rows as $r ) {
if ( $r['paypal_capture_id'] === $ev->captureId || $r['paypal_order_id'] === $ev->orderId ) {
$row = $r;
}
}
}
return $row ? CaptureFinalizer::finalize( $row, 'COMPLETED', $ev->captureId, $ev->amount, $this->mark(), $this->notify() ) : 'ignored';
}
public function test_pending_capture_is_stored_survives_purge_and_webhook_finalizes_once(): void {
$res = CaptureFinalizer::finalize( $this->rows[1], 'PENDING', 'CAP1', new Money( 1099, 'USD' ), $this->mark(), $this->notify(), $this->record() );
$this->assertSame( CaptureFinalizer::PENDING, $res );
$this->assertSame( 'CAP1', $this->rows[1]['paypal_capture_id'], 'PENDING capture id must be persisted' );
$this->assertSame( 'pending', $this->rows[1]['status'] );
$this->purge();
$this->assertArrayHasKey( 1, $this->rows, 'row with capture evidence must survive the purge even when old' );
$this->assertSame( CaptureFinalizer::COMPLETED, $this->webhook() );
$this->assertSame( 'completed', $this->rows[1]['status'] );
$this->assertSame( CaptureFinalizer::DUPLICATE, $this->webhook(), 'replayed webhook is a no-op' );
$this->assertSame( 1, $this->notified, 'side effects exactly once' );
}
public function test_without_recording_the_old_behaviour_would_lose_the_row(): void {
CaptureFinalizer::finalize( $this->rows[1], 'PENDING', 'CAP1', new Money( 1099, 'USD' ), $this->mark(), $this->notify() );
$this->assertNull( $this->rows[1]['paypal_capture_id'] );
$this->purge();
$this->assertArrayNotHasKey( 1, $this->rows );
}
public function test_amount_mismatch_also_records_capture_id(): void {
CaptureFinalizer::finalize( $this->rows[1], 'COMPLETED', 'CAP1', new Money( 5, 'USD' ), $this->mark(), $this->notify(), $this->record() );
$this->assertSame( 'CAP1', $this->rows[1]['paypal_capture_id'] );
$this->assertSame( 'pending', $this->rows[1]['status'] );
}
public function test_no_capture_id_means_nothing_recorded(): void {
$called = false;
CaptureFinalizer::finalize( $this->rows[1], 'PENDING', '', null, $this->mark(), $this->notify(), function () use ( &$called ) { $called = true; return true; } );
$this->assertFalse( $called );
}
public function test_is_purgeable_rules(): void {
$old = gmdate( 'Y-m-d H:i:s', time() - 8 * 86400 );
$new = gmdate( 'Y-m-d H:i:s', time() - 6 * 86400 );
$b = array( 'status' => 'pending', 'goal_id' => 1, 'paypal_capture_id' => null, 'created_at' => $old );
$this->assertTrue( Maintenance::isPurgeable( $b, time() ) );
$this->assertTrue( Maintenance::isPurgeable( array( 'paypal_capture_id' => '' ) + $b, time() ) );
$this->assertFalse( Maintenance::isPurgeable( array( 'created_at' => $new ) + $b, time() ) );
$this->assertFalse( Maintenance::isPurgeable( array( 'paypal_capture_id' => 'X' ) + $b, time() ) );
$this->assertFalse( Maintenance::isPurgeable( array( 'status' => 'completed' ) + $b, time() ) );
$this->assertFalse( Maintenance::isPurgeable( array( 'goal_id' => 0 ) + $b, time() ) );
$this->assertFalse( Maintenance::isPurgeable( array( 'created_at' => 'garbage' ) + $b, time() ) );
}
}
+134
View File
@@ -0,0 +1,134 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Overlay\Payloads;
use StreamGoals\Overlay\Progress;
final class ProgressTest extends TestCase {
private function goal( array $over = array() ): array {
return $over + array( 'id' => 7, 'title' => 'New mic', 'target_minor' => 10000, 'currency' => 'USD', 'status' => 'active', 'close_at_target' => 0, 'counts_fees' => 0 );
}
/** @dataProvider flags */
public function test_show_progress_attribute_parsing( $raw, bool $expected ): void {
$this->assertSame( $expected, Progress::flag( $raw, true ) );
}
public static function flags(): array {
return array(
array( 'yes', true ), array( 'YES', true ), array( 'true', true ), array( '1', true ), array( 1, true ), array( ' on ', true ),
array( 'no', false ), array( 'No', false ), array( 'false', false ), array( '0', false ), array( 0, false ), array( 'off', false ),
array( '', true ), array( null, true ), array( 'banana', true ), array( array( 'x' ), true ),
);
}
public function test_flag_default_is_respected_for_unknown_values(): void {
$this->assertFalse( Progress::flag( 'banana', false ) );
$this->assertFalse( Progress::flag( null, false ) );
}
public function test_percentage_is_clamped_and_target_zero_is_safe(): void {
$this->assertSame( 0, Progress::payload( $this->goal( array( 'target_minor' => 0 ) ), 500 )['percent'] );
$this->assertSame( 100, Progress::payload( $this->goal(), 999999 )['percent'] );
$this->assertSame( 0, Progress::payload( $this->goal(), -50 )['percent'] );
$this->assertSame( 25, Progress::payload( $this->goal(), 2500 )['percent'] );
}
public function test_numbers_match_the_overlay_goal_payload(): void {
$p = Progress::payload( $this->goal(), 2500 );
$o = Payloads::goal( $this->goal(), 2500 );
foreach ( array( 'raised_minor', 'target_minor', 'percent', 'raised_display', 'target_display', 'currency', 'title' ) as $k ) {
$this->assertSame( $o[ $k ], $p[ $k ], $k );
}
$this->assertSame( '$25.00', $p['raised_display'] );
$this->assertSame( '$100.00', $p['target_display'] );
$this->assertFalse( $p['reached'] );
$this->assertNull( $p['tier'] );
}
public function test_tiered_goal_shows_current_tier_and_matches_overlay(): void {
$tiers = array(
array( 'id' => 1, 'target_minor' => 5000, 'title' => 'Giveaway', 'description' => 'secret', 'reached_at' => '2026-01-01 00:00:00' ),
array( 'id' => 2, 'target_minor' => 20000, 'title' => 'Microphone', 'description' => 'secret', 'reached_at' => null ),
);
$g = $this->goal( array( 'target_minor' => 20000 ) );
$p = Progress::payload( $g, 8000, $tiers );
$o = Payloads::goal( $g, 8000, $tiers );
$this->assertSame( $o['percent'], $p['percent'] );
$this->assertSame( 20000, $p['target_minor'] );
$this->assertSame( array( 'index' => 2, 'count' => 2, 'title' => 'Microphone', 'target_minor' => 20000, 'target_display' => '$200.00' ), $p['tier'] );
$this->assertFalse( $p['reached'] );
$this->assertStringNotContainsString( 'secret', json_encode( $p ) );
}
public function test_reached_states(): void {
$closed = $this->goal( array( 'status' => 'complete', 'close_at_target' => 1 ) );
$this->assertTrue( Progress::payload( $closed, 10000 )['reached'] );
$this->assertTrue( Progress::payload( $closed, 0 )['reached'], 'closed at target wins even if numbers lag' );
$this->assertTrue( Progress::payload( $this->goal(), 10000 )['reached'], 'raised >= target' );
$this->assertFalse( Progress::payload( $this->goal( array( 'target_minor' => 0 ) ), 10000 )['reached'], 'no target never counts as reached' );
$done = array( array( 'id' => 1, 'target_minor' => 5000, 'title' => 'A', 'reached_at' => 'x' ) );
$p = Progress::payload( $this->goal( array( 'target_minor' => 5000 ) ), 5000, $done );
$this->assertTrue( $p['reached'] );
$this->assertNull( $p['tier'] );
}
public function test_public_payload_has_exactly_the_whitelisted_non_pii_keys(): void {
$goal = $this->goal() + array( 'paypal_secret' => 'x', 'notes' => 'private' );
$p = Progress::payload( $goal, 100 );
$this->assertSame(
array( 'currency', 'goal_id', 'percent', 'raised_display', 'raised_minor', 'reached', 'target_display', 'target_minor', 'tier', 'title' ),
( static function ( array $a ): array { ksort( $a ); return array_keys( $a ); } )( $p )
);
$json = json_encode( $p );
foreach ( array( 'paypal', 'notes', 'email', 'donor', 'message', 'display_name' ) as $bad ) {
$this->assertStringNotContainsString( $bad, $json );
}
}
public function test_html_is_accessible_and_escaped(): void {
$p = Progress::payload( $this->goal( array( 'title' => '<b>Mic</b>' ) ), 2500 );
$html = Progress::html( $p, array( 'reached' => 'Goal reached', 'of' => '%1$s of %2$s', 'tier' => 'Tier: %1$s (%2$s)', 'label' => 'Progress: %s' ) );
$this->assertStringContainsString( 'role="progressbar"', $html );
$this->assertStringContainsString( 'aria-valuenow="25"', $html );
$this->assertStringContainsString( 'aria-valuemin="0"', $html );
$this->assertStringContainsString( 'aria-valuemax="100"', $html );
$this->assertStringContainsString( 'aria-label="Progress: &lt;b&gt;Mic&lt;/b&gt;"', $html );
$this->assertStringContainsString( '$25.00 of $100.00', $html );
$this->assertStringContainsString( 'width:25%', $html );
$this->assertStringNotContainsString( '<b>', $html );
}
public function test_html_reached_and_tier_lines(): void {
$labels = array( 'reached' => 'Goal reached', 'of' => '%1$s of %2$s', 'tier' => 'Tier: %1$s (%2$s)', 'label' => 'Progress: %s' );
$closed = Progress::html( Progress::payload( $this->goal( array( 'status' => 'complete', 'close_at_target' => 1 ) ), 10000 ), $labels );
$this->assertStringContainsString( 'Goal reached', $closed );
$this->assertStringContainsString( 'sg-progress-reached', $closed );
$this->assertStringContainsString( 'aria-valuenow="100"', $closed );
$tiers = array( array( 'id' => 2, 'target_minor' => 20000, 'title' => 'Mic', 'reached_at' => null ) );
$t = Progress::html( Progress::payload( $this->goal( array( 'target_minor' => 20000 ) ), 100, $tiers ), $labels );
$this->assertStringContainsString( 'Tier: Mic ($200.00)', $t );
}
public function test_assets_support_reduced_motion_and_polling_rules(): void {
$root = dirname( __DIR__, 2 ) . '/assets/donate/';
$css = (string) file_get_contents( $root . 'donate.css' );
$js = (string) file_get_contents( $root . 'donate.js' );
$this->assertStringContainsString( 'prefers-reduced-motion', $css );
$this->assertStringContainsString( 'visibilityState', $js );
$this->assertStringContainsString( '30000', $js );
$this->assertStringNotContainsString( 'innerHTML', $js );
}
public function test_route_and_shortcodes_are_registered(): void {
$php = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Rest/DonateController.php' );
$this->assertStringContainsString( "'/progress'", $php );
$this->assertStringContainsString( "add_shortcode( 'streamgoals_progress'", $php );
$this->assertStringContainsString( "'show_progress' => 'yes'", $php );
$this->assertMatchesRegularExpression( "/function progress_route.*self::limit\( 'progress'/s", $php );
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\PayPal\RequestId;
final class RequestIdTest extends TestCase {
public function test_stable_per_donation_and_within_paypal_limit(): void {
$a = RequestId::make( 'order', 42, '2026-01-01 10:00:00', 'salt' );
$this->assertSame( $a, RequestId::make( 'order', 42, '2026-01-01 10:00:00', 'salt' ) );
$this->assertLessThanOrEqual( 108, strlen( $a ) );
$this->assertMatchesRegularExpression( '/^sg-order-[0-9a-f]{64}$/', $a );
}
public function test_reused_auto_increment_id_gets_a_different_key(): void {
$this->assertNotSame( RequestId::make( 'order', 42, '2026-01-01 10:00:00', 's' ), RequestId::make( 'order', 42, '2026-01-02 10:00:00', 's' ) );
}
public function test_not_derivable_without_the_salt_and_kinds_differ(): void {
$this->assertNotSame( RequestId::make( 'order', 42, 't', 'salt1' ), RequestId::make( 'order', 42, 't', 'salt2' ) );
$this->assertNotSame( RequestId::make( 'order', 42, 't', 's' ), RequestId::make( 'capture', 42, 't', 's' ) );
$this->assertStringNotContainsString( 'sg-order-42', RequestId::make( 'order', 42, 't', 's' ) );
}
}
+9 -2
View File
@@ -58,12 +58,19 @@ final class UninstallerTest extends TestCase {
$dyn = array_merge( $dyn, $b[1] );
preg_match_all( "/'(sg_rl_)'\s*\./", $src, $c );
$dyn = array_merge( $dyn, $c[1] );
// Cache-seam keys (WpCache -> transients): $key = 'sg_xxx_' . md5(...)
preg_match_all( "/'(sg_\w+?_)'\s*\.\s*md5/", $src, $d );
$dyn = array_merge( $dyn, $d[1] );
}
$this->assertContains( 'sg_update_release', $fixed, 'scan sanity check' );
$this->assertSame( array(), array_values( array_diff( array_unique( $fixed ), Uninstaller::site_transients() ) ) );
$this->assertSame( array(), array_values( array_diff( array_unique( $dyn ), Uninstaller::transient_prefixes() ) ) );
$this->assertContains( 'sg_rl_', Uninstaller::transient_prefixes() );
$this->assertContains( 'sg_notice_', Uninstaller::transient_prefixes() );
$this->assertContains( 'sg_pp_token_', Uninstaller::transient_prefixes(), 'cached PayPal access token' );
$this->assertContains( 'sg_wh_', Uninstaller::transient_prefixes(), 'webhook de-dupe markers' );
$this->assertContains( 'sg_pp_token_', $dyn, 'scan sanity check' );
$this->assertContains( 'sg_wh_', $dyn, 'scan sanity check' );
$this->assertSame( Maintenance::HOOK, Uninstaller::CRON_HOOK );
}
@@ -104,10 +111,10 @@ final class UninstallerTest extends TestCase {
public function test_dynamic_transient_cleanup_only_targets_plugin_prefixes(): void {
$db = $this->fakeDb();
Uninstaller::delete_dynamic_transients( $db );
$this->assertCount( 4, $db->queries );
$this->assertCount( 2 * count( Uninstaller::transient_prefixes() ), $db->queries );
foreach ( $db->queries as $q ) {
$this->assertStringStartsWith( 'DELETE FROM wp7_options WHERE option_name LIKE', $q );
$this->assertMatchesRegularExpression( '/_transient_(timeout_)?sg_(rl|notice)_%/', str_replace( '\\', '', $q ) );
$this->assertMatchesRegularExpression( '/_transient_(timeout_)?sg_(rl|notice|pp_token|wh)_%/', str_replace( '\\', '', $q ) );
}
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Update\RedirectPolicy;
final class UpdateRedirectPolicyTest extends TestCase {
private const H = 'repo.example.net';
public function test_same_host_redirects_are_followed_relative_and_absolute(): void {
$cur = 'https://repo.example.net/a/b/c.zip';
$this->assertSame( 'https://repo.example.net/x/y.zip', RedirectPolicy::nextUrl( $cur, 'https://repo.example.net/x/y.zip', self::H, 0 ) );
$this->assertSame( 'https://repo.example.net/x/y.zip', RedirectPolicy::nextUrl( $cur, '/x/y.zip', self::H, 0 ) );
$this->assertSame( 'https://repo.example.net/a/b/d.zip', RedirectPolicy::nextUrl( $cur, 'd.zip', self::H, 1 ) );
$this->assertSame( 'https://repo.example.net/q', RedirectPolicy::nextUrl( $cur, '//repo.example.net/q', self::H, 0 ) );
}
public function test_other_hosts_and_downgrades_are_never_followed(): void {
$cur = 'https://repo.example.net/a.zip';
foreach ( array( 'https://evil.example/a.zip', 'http://repo.example.net/a.zip', '//evil.example/a', 'https://repo.example.net.evil.example/a', 'https://repo.example.net@evil.example/a', 'https://user@repo.example.net/a', 'https://repo.example.net:8443/a', 'ftp://repo.example.net/a', '', "/ok\r\nX: y" ) as $loc ) {
$this->assertNull( RedirectPolicy::nextUrl( $cur, $loc, self::H, 0 ), $loc );
}
}
public function test_hop_limit(): void {
$this->assertNotNull( RedirectPolicy::nextUrl( 'https://repo.example.net/a', '/b', self::H, 2 ) );
$this->assertNull( RedirectPolicy::nextUrl( 'https://repo.example.net/a', '/b', self::H, 3 ) );
}
public function test_token_allowed_only_for_https_pinned_host_default_port(): void {
$this->assertTrue( RedirectPolicy::tokenAllowed( 'https://repo.example.net/x', self::H ) );
$this->assertTrue( RedirectPolicy::tokenAllowed( 'https://REPO.example.net:443/x', self::H ) );
$this->assertFalse( RedirectPolicy::tokenAllowed( 'https://repo.example.net:8443/x', self::H ) );
$this->assertFalse( RedirectPolicy::tokenAllowed( 'http://repo.example.net/x', self::H ) );
$this->assertFalse( RedirectPolicy::tokenAllowed( 'https://cdn.example.net/x', self::H ) );
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\PayPal\ArrayCache;
use StreamGoals\PayPal\RateLimiter;
use StreamGoals\PayPal\WebhookGuard;
final class WebhookGuardTest extends TestCase {
public function test_per_ip_limit_then_429_and_other_ips_unaffected(): void {
$l = new RateLimiter( new ArrayCache() );
for ( $i = 0; $i < WebhookGuard::IP_LIMIT; $i++ ) {
$this->assertTrue( WebhookGuard::admit( $l, '203.0.113.1' ) );
}
$this->assertFalse( WebhookGuard::admit( $l, '203.0.113.1' ), 'over the per-IP limit' );
$this->assertTrue( WebhookGuard::admit( $l, '203.0.113.2' ), 'PayPal\'s other addresses keep working' );
}
public function test_global_cap(): void {
$l = new RateLimiter( new ArrayCache() );
$ok = 0;
for ( $i = 0; $i < WebhookGuard::GLOBAL_LIMIT + 50; $i++ ) {
$ok += WebhookGuard::admit( $l, '10.0.' . intdiv( $i, 100 ) . '.' . ( $i % 100 ) ) ? 1 : 0; // every request from a fresh bucket
}
$this->assertSame( WebhookGuard::GLOBAL_LIMIT, $ok );
}
public function test_rejections_have_the_expected_status(): void {
$good = array( 'paypal-transmission-id' => 'T', 'paypal-transmission-time' => gmdate( 'Y-m-d\TH:i:s\Z' ), 'paypal-transmission-sig' => 'S', 'paypal-cert-url' => 'https://api.sandbox.paypal.com/c', 'paypal-auth-algo' => 'A' );
$this->assertNull( WebhookGuard::check( $good, '{}', time() ) );
$this->assertSame( 413, WebhookGuard::check( $good, str_repeat( 'a', 65537 ), time() )['status'] );
$this->assertNull( WebhookGuard::check( $good, str_repeat( 'a', 65536 ), time() ) );
$this->assertSame( 401, WebhookGuard::check( array_diff_key( $good, array( 'paypal-auth-algo' => 1 ) ), '{}', time() )['status'] );
$this->assertSame( 401, WebhookGuard::check( array( 'paypal-cert-url' => 'https://evil.test/' ) + $good, '{}', time() )['status'] );
$this->assertSame( 401, WebhookGuard::check( array( 'paypal-transmission-time' => '2020-01-01T00:00:00Z' ) + $good, '{}', time() )['status'] );
$this->assertSame( 401, WebhookGuard::check( array( 'paypal-transmission-time' => 'garbage' ) + $good, '{}', time() )['status'] );
}
public function test_time_window_boundaries_and_offsets(): void {
$now = 1800000000;
$this->assertTrue( WebhookGuard::timeWithinWindow( gmdate( 'Y-m-d\TH:i:s\Z', $now - 3600 ), $now ) );
$this->assertFalse( WebhookGuard::timeWithinWindow( gmdate( 'Y-m-d\TH:i:s\Z', $now - 3601 ), $now ) );
$this->assertFalse( WebhookGuard::timeWithinWindow( gmdate( 'Y-m-d\TH:i:s\Z', $now + 3601 ), $now ) );
$this->assertTrue( WebhookGuard::timeWithinWindow( gmdate( 'Y-m-d\TH:i:s', $now + 3600 ) . '+01:00', $now ) );
}
}