Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43106d9edc | ||
|
|
5ea1e1d273 | ||
|
|
1c6d93ad5f | ||
|
|
da1365f060 | ||
|
|
f8d6bc2195 | ||
|
|
e9e3265b22 | ||
|
|
b0b5012698 | ||
|
|
c62ac06b27 | ||
|
|
11ac72b23b | ||
|
|
f7ff1dc717 |
No files matched your search
@@ -45,6 +45,12 @@ with the Live credentials and switch the mode to Live in Settings.
|
||||
or a bonus event above a minimum amount. Amounts can be measured on the base donation or including fee cover.
|
||||
- **Overlays:** StreamGoals → Overlays. Copy a widget URL into OBS as a **Browser Source** (suggested 800×200
|
||||
for the goal bar; transparent background is built in). Keep the URL private; "Regenerate token" invalidates it.
|
||||
- **Rewards (actions for set amounts):** StreamGoals > Rewards. Add things you do on stream for a set amount, for example
|
||||
"$5: eat an every-flavor bean" or "$25: 25 pushups". Each reward is either *exactly this amount* or *every time the
|
||||
donation adds up to this amount* (a $10 donation triggers a $5 reward twice). Rewards appear as buttons on the donation
|
||||
form, as a **Rewards menu** overlay for OBS, and as a highlighted line in the donation alert. Triggered rewards land in a
|
||||
**queue** on the Rewards screen so you can tick them off as you do them. Rewards count the donation amount, not the
|
||||
optional fee cover, and must be at least your minimum donation.
|
||||
- **Test:** "Send test donation" on the Overlays screen shows an alert without touching real totals.
|
||||
|
||||
## Privacy and moderation
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/* StreamGoals rewards editor: live plain-English preview of what a donation would trigger. */
|
||||
( function () {
|
||||
'use strict';
|
||||
var dataEl = document.getElementById( 'sg-actions-data' );
|
||||
var form = document.querySelector( '.sg-action-form' );
|
||||
var out = document.getElementById( 'sg-action-preview' );
|
||||
var tryEl = document.getElementById( 'sg-action-try' );
|
||||
if ( ! dataEl || ! form || ! out || ! tryEl ) { return; }
|
||||
var cfg = { currency: 'USD', exp: 2, actions: [] };
|
||||
try { cfg = JSON.parse( dataEl.textContent ); } catch ( e ) { /* keep defaults */ }
|
||||
|
||||
function toMinor( raw ) {
|
||||
var s = String( raw == null ? '' : raw ).replace( /[,\s$€£¥]/g, '' );
|
||||
var m = /^(\d+)(?:\.(\d+))?$/.exec( s );
|
||||
if ( ! m ) { return null; }
|
||||
var frac = m[ 2 ] || '';
|
||||
if ( frac.length > cfg.exp ) { return null; }
|
||||
while ( frac.length < cfg.exp ) { frac += '0'; }
|
||||
var n = parseInt( m[ 1 ] + frac, 10 );
|
||||
return isFinite( n ) ? n : null;
|
||||
}
|
||||
|
||||
function money( minor ) {
|
||||
var s = String( minor );
|
||||
if ( cfg.exp === 0 ) { return cfg.currency + ' ' + s; }
|
||||
while ( s.length <= cfg.exp ) { s = '0' + s; }
|
||||
return cfg.currency + ' ' + s.slice( 0, -cfg.exp ) + '.' + s.slice( -cfg.exp );
|
||||
}
|
||||
|
||||
function current() {
|
||||
var mode = form.querySelector( 'input[name="mode"]:checked' );
|
||||
return {
|
||||
id: cfg.editId || -1,
|
||||
goal_id: parseInt( form.elements.goal_id.value, 10 ) || 0,
|
||||
title: form.elements.title.value.trim() || 'This reward',
|
||||
amount_minor: toMinor( form.elements.amount.value ) || 0,
|
||||
mode: mode ? mode.value : 'exact'
|
||||
};
|
||||
}
|
||||
|
||||
function match( base, list ) {
|
||||
var res = [];
|
||||
if ( base <= 0 ) { return res; }
|
||||
list.forEach( function ( a ) {
|
||||
if ( a.amount_minor <= 0 ) { return; }
|
||||
var times = a.mode === 'every' ? Math.floor( base / a.amount_minor ) : ( base === a.amount_minor ? 1 : 0 );
|
||||
if ( times >= 1 ) { res.push( a.title + ' x' + times ); }
|
||||
} );
|
||||
return res;
|
||||
}
|
||||
|
||||
function render() {
|
||||
var base = toMinor( tryEl.value );
|
||||
if ( base === null || base <= 0 ) { out.textContent = 'Type a donation amount to see which rewards it would trigger.'; return; }
|
||||
var me = current();
|
||||
var list = cfg.actions.filter( function ( a ) { return a.goal_id === 0 || me.goal_id === 0 || a.goal_id === me.goal_id; } );
|
||||
list.push( me );
|
||||
var hits = match( base, list );
|
||||
out.textContent = hits.length ? 'A ' + money( base ) + ' donation will trigger: ' + hits.join( ', ' ) : 'A ' + money( base ) + ' donation will not trigger any reward.';
|
||||
}
|
||||
|
||||
form.addEventListener( 'input', render );
|
||||
form.addEventListener( 'change', render );
|
||||
var amt = form.elements.amount.value;
|
||||
if ( amt && ! tryEl.value ) { tryEl.value = amt; }
|
||||
render();
|
||||
}() );
|
||||
@@ -5,7 +5,9 @@
|
||||
.sg-donate input[type=text],.sg-donate input[type=number],.sg-donate select,.sg-donate textarea{width:100%;box-sizing:border-box}
|
||||
.sg-donate .sg-presets{display:flex;flex-wrap:wrap;gap:.4rem;margin-bottom:.4rem}
|
||||
.sg-donate .sg-presets button{cursor:pointer}
|
||||
.sg-donate .sg-presets button[aria-pressed=true]{font-weight:700;outline:2px solid currentColor}
|
||||
.sg-donate .sg-presets button{position:relative}
|
||||
.sg-donate .sg-presets button[aria-pressed=true]{font-weight:700;outline:0;box-shadow:0 0 0 2px #fff,0 0 0 5px #1d2327}
|
||||
.sg-donate .sg-presets button[aria-pressed=true]::after{content:"\2713";position:absolute;top:.35rem;right:.6rem;font-weight:700}
|
||||
.sg-donate .sg-total{font-weight:700}
|
||||
.sg-donate .sg-msg{margin-top:.6rem}
|
||||
.sg-donate .sg-msg.sg-error{color:#b32d2e}
|
||||
@@ -17,3 +19,8 @@
|
||||
.sg-donate .sg-info{flex:none;width:1.4rem;height:1.4rem;padding:0;border-radius:50%;border:1.5px solid currentColor;background:transparent;color:inherit;font:italic 700 .85rem/1 Georgia,serif;cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
|
||||
.sg-donate .sg-info:focus-visible{outline:2px solid currentColor;outline-offset:2px}
|
||||
.sg-donate .sg-tip{margin-top:.4rem;padding:.6rem .75rem;border:1px solid rgba(128,128,128,.5);border-radius:.4rem;font-size:.9em;line-height:1.4}
|
||||
.sg-donate .sg-presets.sg-actions{flex-direction:column;flex-wrap:nowrap;align-items:stretch}
|
||||
.sg-donate .sg-presets button.sg-action{display:flex;flex-direction:column;align-items:flex-start;gap:.15rem;width:100%;text-align:left;padding:.55rem .75rem;min-height:2.75rem;box-sizing:border-box;overflow-wrap:anywhere}
|
||||
.sg-donate .sg-act-title{font-weight:600}
|
||||
.sg-donate .sg-act-desc{font-size:.85em;font-weight:400;opacity:.8}
|
||||
.sg-donate .sg-presets button.sg-action:focus-visible{outline:2px solid currentColor;outline-offset:2px}
|
||||
@@ -115,9 +115,34 @@
|
||||
function anonNow() { return anon.checked; }
|
||||
anon.addEventListener('change', function () { nameRow.hidden = anon.checked || C.policy === 'force_anonymous'; });
|
||||
|
||||
// Actions (rewards) for the selected goal, minus any below the minimum. They replace the generic presets.
|
||||
function goalActions() {
|
||||
return (state.goal.actions || []).filter(function (a) {
|
||||
return a && a.amount_minor > 0 && a.amount_minor >= (C.minMinor || 0);
|
||||
});
|
||||
}
|
||||
function minorToStr(minor, exp) { return (minor / Math.pow(10, exp)).toFixed(exp); }
|
||||
function amountMinorNow() {
|
||||
var typed = parseFloat(amountStr());
|
||||
return isFinite(typed) ? Math.round(typed * Math.pow(10, state.goal.exp)) : -1;
|
||||
}
|
||||
function buildPresets() {
|
||||
presetBox.textContent = '';
|
||||
hint.textContent = sprintf1(T.minHint, fmt(C.minMinor || 0, state.goal.exp, state.goal.currency));
|
||||
var acts = goalActions();
|
||||
presetBox.className = 'sg-presets' + (acts.length ? ' sg-actions' : '');
|
||||
if (acts.length) {
|
||||
acts.forEach(function (a) {
|
||||
var money = fmt(a.amount_minor, state.goal.exp, state.goal.currency);
|
||||
var lead = a.mode === 'every' ? sprintf1(T.everyLabel || 'Every %s', money) : money;
|
||||
var kids = [el('span', { 'class': 'sg-act-title', text: lead + ': ' + a.title })];
|
||||
if (a.description) { kids.push(el('span', { 'class': 'sg-act-desc', text: a.description })); }
|
||||
var b = el('button', { type: 'button', 'class': 'sg-action', 'aria-pressed': 'false' }, kids);
|
||||
b.addEventListener('click', function () { amount.value = minorToStr(a.amount_minor, state.goal.exp); refresh(); });
|
||||
presetBox.appendChild(b);
|
||||
});
|
||||
return;
|
||||
}
|
||||
presets(state.goal.exp).forEach(function (p) {
|
||||
var b = el('button', { type: 'button', 'aria-pressed': 'false', text: fmt(state.goal.exp === 0 ? p : p * 100, state.goal.exp, state.goal.currency) });
|
||||
b.addEventListener('click', function () { amount.value = String(p); refresh(); });
|
||||
@@ -125,6 +150,14 @@
|
||||
});
|
||||
}
|
||||
function markPresets() {
|
||||
var acts = goalActions();
|
||||
if (acts.length) {
|
||||
var now = amountMinorNow();
|
||||
Array.prototype.forEach.call(presetBox.children, function (b, i) {
|
||||
b.setAttribute('aria-pressed', String(!!acts[i] && acts[i].amount_minor === now));
|
||||
});
|
||||
return;
|
||||
}
|
||||
var cur = amountStr();
|
||||
Array.prototype.forEach.call(presetBox.children, function (b, i) {
|
||||
b.setAttribute('aria-pressed', String(String(presets(state.goal.exp)[i]) === cur));
|
||||
|
||||
@@ -36,3 +36,14 @@ body.sg-offline #sg-root{opacity:.6}
|
||||
@keyframes sg-out{to{opacity:0;transform:translateY(-30%) scale(.95)}}
|
||||
@keyframes sg-blink{50%{opacity:.4}}
|
||||
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out,.sg-alert.sg-bonus,.sg-alert.sg-bonus.sg-out{animation:none}.sg-alert.sg-bonus{box-shadow:0 0 .8em var(--sg-accent2)}}
|
||||
.sg-w-actions #sg-root{align-items:flex-start}
|
||||
.sg-w-actions #sg-root:empty{display:none}
|
||||
.sg-menu{height:auto;display:flex;flex-direction:column;overflow:hidden;font-size:calc(1em * var(--sg-menu-scale,1))}
|
||||
.sg-menu-view{flex:none;min-height:0;overflow:hidden}
|
||||
.sg-menu-list{list-style:none;margin:0;padding:0}
|
||||
.sg-menu-item{padding:.3em 0;font-weight:600;overflow-wrap:anywhere}
|
||||
.sg-menu-item b{color:var(--sg-accent2);font-weight:800}
|
||||
.sg-menu-desc{display:block;font-size:.75em;font-weight:400;opacity:.8}
|
||||
.sg-menu-track.sg-scrolling{animation:sg-scroll var(--sg-scroll-s,20s) linear infinite}
|
||||
@keyframes sg-scroll{from{transform:translateY(0)}to{transform:translateY(-50%)}}
|
||||
@media (prefers-reduced-motion:reduce){.sg-menu-track.sg-scrolling{animation:none}}
|
||||
@@ -5,7 +5,7 @@
|
||||
var endpoint = body.getAttribute('data-endpoint');
|
||||
var poll = Math.max(1000, parseInt(body.getAttribute('data-poll'), 10) || 2500);
|
||||
var root = document.getElementById('sg-root');
|
||||
var etag = null, failures = 0, since = null, skew = 0, timerState = null;
|
||||
var etag = null, failures = 0, skew = 0, timerState = null;
|
||||
var queue = [], showing = false;
|
||||
|
||||
function el(tag, cls, text) {
|
||||
@@ -92,9 +92,25 @@
|
||||
}
|
||||
|
||||
// ---- alerts ----
|
||||
// Why not a `since` cursor: with moderation, a held donation keeps a low id. If a newer donation is shown
|
||||
// first, the cursor moves past it and the later approval would never be returned. So we poll ?recent=1
|
||||
// (newest 20 approved alerts) and dedupe by id here. First successful poll only seeds seenIds, so
|
||||
// refreshing OBS never replays old alerts. Limit: a message approved after 20+ newer donations is
|
||||
// no longer in the window and is not shown.
|
||||
var seenIds = {}, seenOrder = [], firstAlertPoll = true, SEEN_MAX = 200;
|
||||
function markSeen(id) {
|
||||
seenIds[id] = true; seenOrder.push(id);
|
||||
while (seenOrder.length > SEEN_MAX) delete seenIds[seenOrder.shift()];
|
||||
}
|
||||
function renderAlerts(d) {
|
||||
since = d.last_id;
|
||||
for (var i = 0; i < d.alerts.length; i++) queue.push(d.alerts[i]);
|
||||
var list = (d.alerts || []).slice().sort(function (a, b) { return a.id - b.id; });
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
var a = list[i];
|
||||
if (seenIds[a.id]) continue;
|
||||
markSeen(a.id);
|
||||
if (!firstAlertPoll) queue.push(a);
|
||||
}
|
||||
firstAlertPoll = false;
|
||||
next();
|
||||
}
|
||||
function next() {
|
||||
@@ -115,6 +131,12 @@
|
||||
card.appendChild(el('div', 'sg-bonus-line', 'BONUS: ' + String(bonuses[j]) + '!'));
|
||||
}
|
||||
}
|
||||
var acts = Array.isArray(a.actions) ? a.actions : [];
|
||||
if (acts.length) card.classList.add('sg-bonus');
|
||||
for (var k = 0; k < acts.length; k++) {
|
||||
var times = parseInt(acts[k].times, 10) || 1;
|
||||
card.appendChild(el('div', 'sg-bonus-line', 'ACTION: ' + String(acts[k].title) + (times > 1 ? ' x' + times : '')));
|
||||
}
|
||||
if (a.message) card.appendChild(el('div', 'sg-alert-msg', a.message));
|
||||
root.appendChild(card);
|
||||
setTimeout(function () {
|
||||
@@ -123,10 +145,76 @@
|
||||
}, 6500);
|
||||
}
|
||||
|
||||
// ---- actions (reward menu) ----
|
||||
// Renders nothing visible when there are no actions. The card hugs its content and the text is scaled to the
|
||||
// LARGEST size that still fits the browser-source window (shrinks for long lists, grows for short ones), and
|
||||
// re-fits when the window is resized. Only if even the smallest size does not fit does it fall back to a gentle scroll.
|
||||
var actionsSig = null, menuEls = null, fitTimer = 0;
|
||||
var MENU_MIN = 0.5, MENU_MAX = 1.8;
|
||||
function fitMenu() {
|
||||
if (!menuEls) return;
|
||||
var card = menuEls.card, view = menuEls.view, track = menuEls.track, ul = menuEls.ul;
|
||||
// reset any previous scroll fallback
|
||||
track.classList.remove('sg-scrolling');
|
||||
while (track.children.length > 1) track.removeChild(track.lastChild);
|
||||
view.style.height = '';
|
||||
var cs = getComputedStyle(root);
|
||||
var inner = root.clientHeight - parseFloat(cs.paddingTop) - parseFloat(cs.paddingBottom);
|
||||
if (inner <= 0) return;
|
||||
function fits(scale) {
|
||||
card.style.setProperty('--sg-menu-scale', String(scale));
|
||||
return card.offsetHeight <= inner;
|
||||
}
|
||||
var lo = MENU_MIN, hi = MENU_MAX, best = null;
|
||||
if (fits(hi)) { best = hi; }
|
||||
else if (!fits(lo)) { best = null; }
|
||||
else { for (var i = 0; i < 9; i++) { var mid = (lo + hi) / 2; if (fits(mid)) { lo = mid; } else { hi = mid; } } best = lo; }
|
||||
if (best !== null) { card.style.setProperty('--sg-menu-scale', String(best)); return; }
|
||||
// Even the smallest size overflows: use the smallest and scroll gently inside the window.
|
||||
card.style.setProperty('--sg-menu-scale', String(MENU_MIN));
|
||||
var chrome = card.offsetHeight - view.offsetHeight;
|
||||
view.style.height = Math.max(40, inner - chrome) + 'px';
|
||||
var dup = ul.cloneNode(true);
|
||||
dup.setAttribute('aria-hidden', 'true');
|
||||
track.appendChild(dup);
|
||||
track.style.setProperty('--sg-scroll-s', Math.max(8, menuEls.count * 3) + 's');
|
||||
track.classList.add('sg-scrolling');
|
||||
}
|
||||
function scheduleFit() { clearTimeout(fitTimer); fitTimer = setTimeout(fitMenu, 120); }
|
||||
window.addEventListener('resize', scheduleFit);
|
||||
if (typeof ResizeObserver === 'function') { try { new ResizeObserver(scheduleFit).observe(document.documentElement); } catch (e) { /* resize event is the fallback */ } }
|
||||
function renderActions(d) {
|
||||
var list = Array.isArray(d.actions) ? d.actions : [];
|
||||
var sig = JSON.stringify(list);
|
||||
if (sig === actionsSig) return;
|
||||
actionsSig = sig;
|
||||
root.textContent = '';
|
||||
menuEls = null;
|
||||
if (!d.active || !list.length) return;
|
||||
var card = el('div', 'sg-card sg-menu');
|
||||
var view = el('div', 'sg-menu-view');
|
||||
var ul = el('ul', 'sg-menu-list');
|
||||
list.forEach(function (a) {
|
||||
var li = el('li', 'sg-menu-item');
|
||||
var lead = (a.mode === 'every' ? 'Every ' : '') + a.amount_display;
|
||||
li.appendChild(el('b', null, lead));
|
||||
li.appendChild(document.createTextNode(' \u2014 ' + String(a.title)));
|
||||
if (a.description) li.appendChild(el('span', 'sg-menu-desc', String(a.description)));
|
||||
ul.appendChild(li);
|
||||
});
|
||||
var track = el('div', 'sg-menu-track');
|
||||
track.appendChild(ul);
|
||||
view.appendChild(track);
|
||||
card.appendChild(view);
|
||||
root.appendChild(card);
|
||||
menuEls = { card: card, view: view, track: track, ul: ul, count: list.length };
|
||||
requestAnimationFrame(fitMenu);
|
||||
}
|
||||
|
||||
// ---- polling ----
|
||||
function url() {
|
||||
var u = endpoint;
|
||||
if (widget === 'alerts' && since !== null) u += (u.indexOf('?') < 0 ? '?' : '&') + 'since=' + encodeURIComponent(since);
|
||||
if (widget === 'alerts') u += (u.indexOf('?') < 0 ? '?' : '&') + 'recent=1';
|
||||
return u;
|
||||
}
|
||||
function schedule() {
|
||||
@@ -163,6 +251,7 @@
|
||||
else if (widget === 'timer') renderTimer(d, now);
|
||||
else if (widget === 'counter') renderCounter(d);
|
||||
else if (widget === 'alerts') renderAlerts(d);
|
||||
else if (widget === 'actions') renderActions(d);
|
||||
}
|
||||
|
||||
if (widget === 'timer') tickTimer();
|
||||
|
||||
@@ -54,3 +54,30 @@ A toggle on the donate form (default **off**). Form shows exact total before pay
|
||||
|
||||
## Defaults
|
||||
Currency USD (configurable per goal). Sandbox mode is the default until the owner switches to Live.
|
||||
|
||||
## Donation actions ("rewards") — contract
|
||||
Streamers attach on-stream actions to dollar amounts (e.g. $5 = "Eat an every-flavor bean", $25 = "25 pushups").
|
||||
|
||||
Tables (Installer, DB_VERSION 2):
|
||||
- `sg_actions`: id, goal_id (0 = applies to every goal), title VARCHAR(120), description VARCHAR(255), amount_minor BIGINT UNSIGNED,
|
||||
mode VARCHAR(8) `exact` (donation base amount == amount) | `every` (each whole multiple of amount: times = floor(base/amount)),
|
||||
enabled TINYINT, sort INT, created_at.
|
||||
- `sg_action_events`: id, donation_id, action_id, times INT, title VARCHAR(120) (snapshot at trigger time), status `queued`|`done`,
|
||||
created_at, done_at NULL. UNIQUE(donation_id, action_id) so a replayed capture/webhook never double-queues.
|
||||
|
||||
PHP (namespace `StreamGoals\Actions`):
|
||||
- `Matcher::match(int $baseMinor, array $actions): array` — PURE. `$actions` = rows with keys id, title, amount_minor, mode.
|
||||
Returns `[ ['action_id'=>int,'title'=>string,'times'=>int], ... ]`; a donation may trigger several actions (e.g. $25 matches "every $5" x5 and exact "$25"). amount_minor <= 0 never matches.
|
||||
- `ActionRepository` ($wpdb): `enabledForGoal(int $goalId): array` (enabled rows where goal_id IN (0,$goalId), ORDER BY sort, amount_minor), CRUD for admin,
|
||||
`recordEvents(int $donationId, array $matches): void` (INSERT IGNORE, idempotent), `queued(int $limit): array`, `markDone(int $eventId): bool`.
|
||||
- `Recorder::forDonation(int $donationId): void` — called after a donation becomes `completed` (same place the rules engine is applied); matches on the donation's BASE amount (not fee cover) using the goal's enabled actions and records events. Never throws.
|
||||
Public/overlay: the donate form shows each enabled action as a button (amount + title); the overlay has a new `actions` widget (the menu for the active goal) and alert payloads gain `actions`: `[ {title, times} ]` read from sg_action_events (anonymous donors' actions are still shown; names stay masked).
|
||||
Amounts must be >= Settings::effectiveMin().
|
||||
|
||||
## Schema v3 (Installer, DB_VERSION 3)
|
||||
- `sg_goals.close_at_target` TINYINT: when 1, the goal is closed to donors as soon as its raised total reaches or exceeds the target (status becomes `complete`, same as the manual "Complete" action).
|
||||
- `sg_alert_defs` — owner-defined alert presentations (media from the WordPress Media Library; attachment ids, never raw URLs):
|
||||
id, goal_id (0 = all goals), trigger_type `amount` | `reward`, min_minor (for `amount`: applies when the donation BASE amount >= min_minor; the highest matching min_minor wins),
|
||||
action_id (for `reward`: applies when that reward triggered; a reward definition wins over an amount definition), title (admin label),
|
||||
visual_id + visual_type (`image` | `video` | '' none), sound_id (audio attachment, 0 none), volume 0-100, duration_ms (how long an image/GIF stays; videos play to the end, capped),
|
||||
message (template with {name} {amount} {reward}; '' = default text), enabled, sort, created_at.
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Actions;
|
||||
|
||||
/** $wpdb access to sg_actions / sg_action_events. */
|
||||
final class ActionRepository {
|
||||
|
||||
private object $db;
|
||||
|
||||
public function __construct( ?object $db = null ) {
|
||||
$this->db = $db ?? $GLOBALS['wpdb'];
|
||||
}
|
||||
|
||||
private function t( string $name ): string {
|
||||
return $this->db->prefix . 'sg_' . $name;
|
||||
}
|
||||
|
||||
/** Normalise numeric columns. @return array{id:int,goal_id:int,title:string,description:string,amount_minor:int,mode:string,enabled:int,sort:int,created_at:string} */
|
||||
private static function cast( array $r ): array {
|
||||
return array(
|
||||
'id' => (int) ( $r['id'] ?? 0 ),
|
||||
'goal_id' => (int) ( $r['goal_id'] ?? 0 ),
|
||||
'title' => (string) ( $r['title'] ?? '' ),
|
||||
'description' => (string) ( $r['description'] ?? '' ),
|
||||
'amount_minor' => (int) ( $r['amount_minor'] ?? 0 ),
|
||||
'mode' => (string) ( $r['mode'] ?? 'exact' ),
|
||||
'enabled' => (int) ( $r['enabled'] ?? 0 ),
|
||||
'sort' => (int) ( $r['sort'] ?? 0 ),
|
||||
'created_at' => (string) ( $r['created_at'] ?? '' ),
|
||||
);
|
||||
}
|
||||
|
||||
/** Enabled actions for a goal (goal_id IN (0,$goalId)) ordered by sort, amount. */
|
||||
public function enabledForGoal( int $goalId ): array {
|
||||
$rows = $this->db->get_results(
|
||||
$this->db->prepare( 'SELECT * FROM ' . $this->t( 'actions' ) . ' WHERE enabled = 1 AND goal_id IN (0, %d) ORDER BY sort ASC, amount_minor ASC, id ASC', $goalId ),
|
||||
ARRAY_A
|
||||
);
|
||||
return array_map( array( self::class, 'cast' ), (array) $rows );
|
||||
}
|
||||
|
||||
/** All actions (enabled or not) for the admin list. */
|
||||
public function all(): array {
|
||||
$rows = $this->db->get_results( 'SELECT * FROM ' . $this->t( 'actions' ) . ' ORDER BY sort ASC, amount_minor ASC, id ASC', ARRAY_A );
|
||||
return array_map( array( self::class, 'cast' ), (array) $rows );
|
||||
}
|
||||
|
||||
public function find( int $id ): ?array {
|
||||
$row = $this->db->get_row( $this->db->prepare( 'SELECT * FROM ' . $this->t( 'actions' ) . ' WHERE id = %d', $id ), ARRAY_A );
|
||||
return $row ? self::cast( $row ) : null;
|
||||
}
|
||||
|
||||
public function nextSort(): int {
|
||||
return (int) $this->db->get_var( 'SELECT COALESCE(MAX(sort),0)+10 FROM ' . $this->t( 'actions' ) );
|
||||
}
|
||||
|
||||
/** @param array{goal_id:int,title:string,description:string,amount_minor:int,mode:string,sort:int} $d @return int new id (0 on failure) */
|
||||
public function create( array $d ): int {
|
||||
$ok = $this->db->insert(
|
||||
$this->t( 'actions' ),
|
||||
array(
|
||||
'goal_id' => (int) $d['goal_id'],
|
||||
'title' => (string) $d['title'],
|
||||
'description' => (string) $d['description'],
|
||||
'amount_minor' => (int) $d['amount_minor'],
|
||||
'mode' => (string) $d['mode'],
|
||||
'enabled' => 1,
|
||||
'sort' => (int) $d['sort'],
|
||||
'created_at' => gmdate( 'Y-m-d H:i:s' ),
|
||||
),
|
||||
array( '%d', '%s', '%s', '%d', '%s', '%d', '%d', '%s' )
|
||||
);
|
||||
return $ok ? (int) $this->db->insert_id : 0;
|
||||
}
|
||||
|
||||
public function update( int $id, array $d ): void {
|
||||
$this->db->update(
|
||||
$this->t( 'actions' ),
|
||||
array(
|
||||
'goal_id' => (int) $d['goal_id'],
|
||||
'title' => (string) $d['title'],
|
||||
'description' => (string) $d['description'],
|
||||
'amount_minor' => (int) $d['amount_minor'],
|
||||
'mode' => (string) $d['mode'],
|
||||
'sort' => (int) $d['sort'],
|
||||
),
|
||||
array( 'id' => $id ),
|
||||
array( '%d', '%s', '%s', '%d', '%s', '%d' ),
|
||||
array( '%d' )
|
||||
);
|
||||
}
|
||||
|
||||
public function setEnabled( int $id, bool $on ): void {
|
||||
$this->db->update( $this->t( 'actions' ), array( 'enabled' => $on ? 1 : 0 ), array( 'id' => $id ), array( '%d' ), array( '%d' ) );
|
||||
}
|
||||
|
||||
/** Past events keep their title snapshot, so history survives. */
|
||||
public function delete( int $id ): void {
|
||||
$this->db->delete( $this->t( 'actions' ), array( 'id' => $id ), array( '%d' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue triggered actions for a donation. INSERT IGNORE + UNIQUE(donation_id, action_id): replays do nothing.
|
||||
*
|
||||
* @param array[] $matches Output of Matcher::match().
|
||||
*/
|
||||
public function recordEvents( int $donationId, array $matches ): void {
|
||||
$now = gmdate( 'Y-m-d H:i:s' );
|
||||
foreach ( $matches as $m ) {
|
||||
$times = (int) ( $m['times'] ?? 0 );
|
||||
$aid = (int) ( $m['action_id'] ?? 0 );
|
||||
if ( $donationId <= 0 || $aid <= 0 || $times < 1 ) {
|
||||
continue;
|
||||
}
|
||||
$title = function_exists( 'mb_substr' ) ? mb_substr( (string) ( $m['title'] ?? '' ), 0, 120 ) : substr( (string) ( $m['title'] ?? '' ), 0, 120 );
|
||||
$this->db->query(
|
||||
$this->db->prepare(
|
||||
'INSERT IGNORE INTO ' . $this->t( 'action_events' ) . " (donation_id, action_id, times, title, status, created_at) VALUES (%d, %d, %d, %s, 'queued', %s)",
|
||||
$donationId,
|
||||
$aid,
|
||||
$times,
|
||||
$title,
|
||||
$now
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function eventSelect(): string {
|
||||
return 'SELECT e.*, d.donor_name, d.is_anonymous, d.message, d.base_minor, d.currency FROM ' . $this->t( 'action_events' ) . ' e LEFT JOIN ' . $this->t( 'donations' ) . ' d ON d.id = e.donation_id';
|
||||
}
|
||||
|
||||
/** Oldest first. Rows include donor_name, is_anonymous, message, base_minor, currency from the donation. */
|
||||
public function queued( int $limit ): array {
|
||||
return (array) $this->db->get_results( $this->db->prepare( $this->eventSelect() . " WHERE e.status = 'queued' ORDER BY e.id ASC LIMIT %d", $limit ), ARRAY_A );
|
||||
}
|
||||
|
||||
public function recentDone( int $limit ): array {
|
||||
return (array) $this->db->get_results( $this->db->prepare( $this->eventSelect() . " WHERE e.status = 'done' ORDER BY e.done_at DESC, e.id DESC LIMIT %d", $limit ), ARRAY_A );
|
||||
}
|
||||
|
||||
public function queuedCount(): int {
|
||||
return (int) $this->db->get_var( 'SELECT COUNT(*) FROM ' . $this->t( 'action_events' ) . " WHERE status = 'queued'" );
|
||||
}
|
||||
|
||||
public function markDone( int $eventId ): bool {
|
||||
$n = $this->db->query( $this->db->prepare( 'UPDATE ' . $this->t( 'action_events' ) . " SET status = 'done', done_at = %s WHERE id = %d AND status = 'queued'", gmdate( 'Y-m-d H:i:s' ), $eventId ) );
|
||||
return 1 === (int) $n;
|
||||
}
|
||||
|
||||
public function markAllDone(): int {
|
||||
return (int) $this->db->query( $this->db->prepare( 'UPDATE ' . $this->t( 'action_events' ) . " SET status = 'done', done_at = %s WHERE status = 'queued'", gmdate( 'Y-m-d H:i:s' ) ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Actions;
|
||||
|
||||
/** Pure: which actions does a donation of $baseMinor trigger, and how many times each. */
|
||||
final class Matcher {
|
||||
|
||||
public const EXACT = 'exact';
|
||||
public const EVERY = 'every';
|
||||
|
||||
/**
|
||||
* @param array[] $actions Rows with keys id, title, amount_minor, mode. Malformed rows are skipped.
|
||||
* @return array<int,array{action_id:int,title:string,times:int}> In the order of $actions.
|
||||
*/
|
||||
public static function match( int $baseMinor, array $actions ): array {
|
||||
$out = array();
|
||||
if ( $baseMinor <= 0 ) {
|
||||
return $out;
|
||||
}
|
||||
foreach ( $actions as $a ) {
|
||||
if ( ! is_array( $a ) || ! isset( $a['id'], $a['amount_minor'], $a['mode'], $a['title'] ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( ! is_numeric( $a['id'] ) || ! is_numeric( $a['amount_minor'] ) || ! is_string( $a['mode'] ) || ! is_scalar( $a['title'] ) ) {
|
||||
continue;
|
||||
}
|
||||
$id = (int) $a['id'];
|
||||
$amount = (int) $a['amount_minor'];
|
||||
if ( $id <= 0 || $amount <= 0 ) {
|
||||
continue;
|
||||
}
|
||||
if ( self::EXACT === $a['mode'] ) {
|
||||
$times = $baseMinor === $amount ? 1 : 0;
|
||||
} elseif ( self::EVERY === $a['mode'] ) {
|
||||
$times = intdiv( $baseMinor, $amount );
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
if ( $times >= 1 ) {
|
||||
$out[] = array( 'action_id' => $id, 'title' => (string) $a['title'], 'times' => $times );
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
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 {
|
||||
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;
|
||||
}
|
||||
$repo = new ActionRepository( $wpdb );
|
||||
$matches = Matcher::match( (int) $row['base_minor'], $repo->enabledForGoal( (int) $row['goal_id'] ) );
|
||||
if ( $matches ) {
|
||||
$repo->recordEvents( $donationId, $matches );
|
||||
}
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: Recorder failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Actions\Matcher;
|
||||
|
||||
/** Pure validation/sanitizing for the rewards form. */
|
||||
final class ActionInput {
|
||||
|
||||
/**
|
||||
* @param int[] $validGoalIds Existing goal ids (0 = all goals is always allowed).
|
||||
* @return array{data:?array,error:?string}
|
||||
*/
|
||||
public static function validate( array $post, int $minMinor, string $currency, array $validGoalIds, ?int $defaultSort = null ): array {
|
||||
$fail = static fn( string $m ): array => array( 'data' => null, 'error' => $m );
|
||||
$title = Input::text( $post['title'] ?? '', 200 );
|
||||
if ( '' === $title ) {
|
||||
return $fail( 'Please give the reward a title, for example "Eat a bean".' );
|
||||
}
|
||||
if ( self::len( $title ) > 120 ) {
|
||||
return $fail( 'The title can be at most 120 characters.' );
|
||||
}
|
||||
$desc = Input::text( $post['description'] ?? '', 400 );
|
||||
if ( self::len( $desc ) > 255 ) {
|
||||
return $fail( 'The description can be at most 255 characters.' );
|
||||
}
|
||||
$amount = Input::amountToMinor( $post['amount'] ?? '', $currency );
|
||||
if ( null === $amount || $amount <= 0 ) {
|
||||
return $fail( 'Please enter an amount greater than zero, for example 5.00.' );
|
||||
}
|
||||
if ( $amount < $minMinor ) {
|
||||
return $fail( 'The amount must be at least the minimum donation (' . Format::money( $minMinor, $currency ) . ').' );
|
||||
}
|
||||
$mode = is_scalar( $post['mode'] ?? null ) ? (string) $post['mode'] : '';
|
||||
if ( ! in_array( $mode, array( Matcher::EXACT, Matcher::EVERY ), true ) ) {
|
||||
return $fail( 'Please choose when the reward triggers.' );
|
||||
}
|
||||
$goalRaw = $post['goal_id'] ?? '0';
|
||||
$goal = Input::int( $goalRaw, 0, PHP_INT_MAX >> 1 );
|
||||
if ( null === $goal || ( 0 !== $goal && ! in_array( $goal, array_map( 'intval', $validGoalIds ), true ) ) ) {
|
||||
return $fail( 'Please choose all goals or one of your goals.' );
|
||||
}
|
||||
$sortRaw = $post['sort'] ?? '';
|
||||
$sort = ( is_scalar( $sortRaw ) && '' === trim( (string) $sortRaw ) ) ? ( $defaultSort ?? 0 ) : Input::int( $sortRaw, 0, 99999 );
|
||||
if ( null === $sort ) {
|
||||
return $fail( 'The sort order must be a whole number from 0 to 99999.' );
|
||||
}
|
||||
return array(
|
||||
'data' => array( 'goal_id' => $goal, 'title' => $title, 'description' => $desc, 'amount_minor' => $amount, 'mode' => $mode, 'sort' => $sort ),
|
||||
'error' => null,
|
||||
);
|
||||
}
|
||||
|
||||
private static function len( string $s ): int {
|
||||
return function_exists( 'mb_strlen' ) ? mb_strlen( $s ) : strlen( $s );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Actions\ActionRepository;
|
||||
use StreamGoals\Actions\Matcher;
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/** "Rewards": the menu of on-stream actions, and the queue of triggered ones. */
|
||||
final class ActionsPage {
|
||||
|
||||
public const PAGE = 'streamgoals-rewards';
|
||||
|
||||
private static function repo(): ActionRepository {
|
||||
return new ActionRepository();
|
||||
}
|
||||
|
||||
public static function minMinor(): int {
|
||||
return Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
|
||||
}
|
||||
|
||||
public static function queuedCount(): int {
|
||||
try {
|
||||
return self::repo()->queuedCount();
|
||||
} catch ( \Throwable ) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
private static function url( array $args = array() ): string {
|
||||
return Admin::url( self::PAGE, $args );
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- render */
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'Rewards' );
|
||||
$edit = Admin::get_int( 'edit' );
|
||||
if ( 'new' === Admin::get_str( 'view' ) || $edit ) {
|
||||
self::renderForm( $edit );
|
||||
} else {
|
||||
self::renderQueue();
|
||||
self::renderMenu();
|
||||
}
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
private static function renderQueue(): void {
|
||||
$cur = Admin::currency();
|
||||
$repo = self::repo();
|
||||
$queued = $repo->queued( 200 );
|
||||
echo '<div class="sg-card"><h2>Waiting to be done (' . count( $queued ) . ')</h2>';
|
||||
if ( ! $queued ) {
|
||||
echo '<p>Nothing in the queue. When a donation triggers a reward, it shows up here.</p>';
|
||||
} else {
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Donor</th><th>Amount</th><th>Reward</th><th>Time</th><th>Message</th><th></th></tr></thead><tbody>';
|
||||
foreach ( $queued as $e ) {
|
||||
echo '<tr><td>' . esc_html( Format::donorName( $e ) ) . '</td>';
|
||||
echo '<td>' . esc_html( Format::money( (int) ( $e['base_minor'] ?? 0 ), Format::currency( $e['currency'] ?? $cur ) ) ) . '</td>';
|
||||
echo '<td><strong>' . esc_html( (string) $e['title'] ) . '</strong> × ' . (int) $e['times'] . '</td>';
|
||||
echo '<td>' . esc_html( self::when( (string) $e['created_at'] ) ) . '</td>';
|
||||
echo '<td>' . esc_html( (string) ( $e['message'] ?? '' ) ) . '</td><td>';
|
||||
Admin::form( 'sg_event_done', array( 'event_id' => (int) $e['id'] ), 'sg-inline' );
|
||||
echo '<button class="button button-primary">Mark done</button></form></td></tr>';
|
||||
}
|
||||
echo '</tbody></table>';
|
||||
Admin::form( 'sg_event_done_all' );
|
||||
echo '<p><button class="button">Mark all done</button></p></form>';
|
||||
}
|
||||
$done = $repo->recentDone( 15 );
|
||||
if ( $done ) {
|
||||
echo '<h3>Recently done</h3><ul class="sg-preview-list">';
|
||||
foreach ( $done as $e ) {
|
||||
echo '<li>' . esc_html( Format::donorName( $e ) . ': ' . $e['title'] . ' x ' . (int) $e['times'] . ' (' . self::when( (string) ( $e['done_at'] ?? '' ) ) . ')' ) . '</li>';
|
||||
}
|
||||
echo '</ul>';
|
||||
}
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
private static function when( string $utc ): string {
|
||||
return '' === $utc ? '' : get_date_from_gmt( $utc, 'Y-m-d H:i' );
|
||||
}
|
||||
|
||||
/** @return array<int,string> goal id => title */
|
||||
private static function goalTitles(): array {
|
||||
$out = array();
|
||||
foreach ( Store::goals()->all() as $g ) {
|
||||
$out[ (int) $g['id'] ] = (string) $g['title'];
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function renderMenu(): void {
|
||||
$cur = Admin::currency();
|
||||
$actions = self::repo()->all();
|
||||
$goals = self::goalTitles();
|
||||
echo '<div class="sg-card"><h2>Your reward menu</h2>';
|
||||
echo '<p class="description">Donors pick a reward on the donation form (or just donate the amount). Rewards must be at least ' . esc_html( Format::money( self::minMinor(), $cur ) ) . ', the minimum donation.</p>';
|
||||
echo '<p><a class="button button-primary" href="' . esc_url( self::url( array( 'view' => 'new' ) ) ) . '">Add a reward</a></p>';
|
||||
if ( ! $actions ) {
|
||||
echo '<p>No rewards yet.</p></div>';
|
||||
return;
|
||||
}
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Reward</th><th>Amount</th><th>Triggers</th><th>Applies to</th><th>Order</th><th>Actions</th></tr></thead><tbody>';
|
||||
foreach ( $actions as $a ) {
|
||||
$id = (int) $a['id'];
|
||||
echo '<tr' . ( $a['enabled'] ? '' : ' class="sg-off"' ) . '><td><strong>' . esc_html( $a['title'] ) . '</strong>';
|
||||
if ( '' !== $a['description'] ) {
|
||||
echo '<br><span class="description">' . esc_html( $a['description'] ) . '</span>';
|
||||
}
|
||||
echo '</td><td>' . esc_html( Format::money( $a['amount_minor'], $cur ) ) . '</td>';
|
||||
echo '<td>' . esc_html( Matcher::EVERY === $a['mode'] ? 'Every time it adds up' : 'Exactly this amount' ) . '</td>';
|
||||
echo '<td>' . esc_html( 0 === $a['goal_id'] ? 'All goals' : ( $goals[ $a['goal_id'] ] ?? 'Goal #' . $a['goal_id'] ) ) . '</td>';
|
||||
echo '<td>' . (int) $a['sort'] . '</td><td class="sg-actions">';
|
||||
echo '<a class="button" href="' . esc_url( self::url( array( 'edit' => $id ) ) ) . '">Edit</a> ';
|
||||
Admin::form( 'sg_action_toggle', array( 'action_id' => $id, 'enabled' => $a['enabled'] ? 0 : 1 ), 'sg-inline' );
|
||||
echo '<button class="button">' . ( $a['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
|
||||
Admin::form( 'sg_action_delete', array( 'action_id' => $id ), 'sg-inline sg-confirm' );
|
||||
echo '<button class="button button-link-delete" data-confirm="Delete this reward? Rewards already waiting in the queue stay there.">Delete</button></form>';
|
||||
echo '</td></tr>';
|
||||
}
|
||||
echo '</tbody></table></div>';
|
||||
}
|
||||
|
||||
private static function renderForm( int $id ): void {
|
||||
$a = $id ? self::repo()->find( $id ) : null;
|
||||
if ( $id && ! $a ) {
|
||||
echo '<p>That reward no longer exists. <a href="' . esc_url( self::url() ) . '">Back to rewards</a></p>';
|
||||
return;
|
||||
}
|
||||
$cur = Admin::currency();
|
||||
$goals = self::goalTitles();
|
||||
$val = static fn( string $k, $d = '' ) => $a[ $k ] ?? $d;
|
||||
$mode = (string) $val( 'mode', Matcher::EXACT );
|
||||
$data = array(
|
||||
'currency' => $cur,
|
||||
'exp' => Money::exponent( $cur ),
|
||||
'editId' => $id,
|
||||
'actions' => array_values( array_map(
|
||||
static fn( array $r ): array => array( 'id' => $r['id'], 'goal_id' => $r['goal_id'], 'title' => $r['title'], 'amount_minor' => $r['amount_minor'], 'mode' => $r['mode'] ),
|
||||
array_filter( self::repo()->all(), static fn( array $r ): bool => (bool) $r['enabled'] && $r['id'] !== $id )
|
||||
) ),
|
||||
);
|
||||
|
||||
echo '<h2>' . ( $a ? 'Edit reward' : 'Add a reward' ) . '</h2>';
|
||||
Admin::form( 'sg_action_save', array( 'action_id' => $id ), 'sg-action-form' );
|
||||
echo '<table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sg_a_title">Title</label></th><td><input type="text" required maxlength="120" id="sg_a_title" name="title" class="regular-text" value="' . esc_attr( (string) $val( 'title' ) ) . '"><p class="description">What you do on stream, for example "Eat a bean". Up to 120 characters.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_a_desc">Description</label></th><td><input type="text" maxlength="255" id="sg_a_desc" name="description" class="large-text" value="' . esc_attr( (string) $val( 'description' ) ) . '"><p class="description">Optional. A short note shown to donors.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_a_amount">Amount (' . esc_html( $cur ) . ')</label></th><td><input type="text" required inputmode="decimal" id="sg_a_amount" name="amount" class="small-text" value="' . esc_attr( $a ? Format::decimal( (int) $a['amount_minor'], $cur ) : '' ) . '"><p class="description">At least ' . esc_html( Format::money( self::minMinor(), $cur ) ) . ' (your minimum donation). The amount before any fee the donor chooses to cover.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_a_goal">Applies to</label></th><td><select id="sg_a_goal" name="goal_id"><option value="0"' . selected( (int) $val( 'goal_id', 0 ), 0, false ) . '>All goals</option>';
|
||||
foreach ( $goals as $gid => $title ) {
|
||||
echo '<option value="' . (int) $gid . '"' . selected( (int) $val( 'goal_id', 0 ), $gid, false ) . '>' . esc_html( $title ) . '</option>';
|
||||
}
|
||||
echo '</select></td></tr>';
|
||||
echo '<tr><th scope="row">Triggers</th><td>';
|
||||
echo '<label><input type="radio" name="mode" value="exact"' . checked( $mode, Matcher::EXACT, false ) . '> Exactly this amount</label><br>';
|
||||
echo '<label><input type="radio" name="mode" value="every"' . checked( $mode, Matcher::EVERY, false ) . '> Every time the donation adds up to this amount (a $10 donation triggers a $5 reward twice)</label></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_a_sort">Order</label></th><td><input type="number" min="0" max="99999" id="sg_a_sort" name="sort" class="small-text" value="' . ( $a ? (int) $a['sort'] : '' ) . '"><p class="description">Lower numbers are listed first. Leave empty to put it last.</p></td></tr>';
|
||||
echo '</table>';
|
||||
echo '<div class="sg-card"><h3>What would a donation do?</h3><label>Donation amount (' . esc_html( $cur ) . ') <input type="text" id="sg-action-try" class="small-text" inputmode="decimal"></label>';
|
||||
echo '<p id="sg-action-preview" class="sg-form-preview" aria-live="polite"></p>';
|
||||
echo '<script type="application/json" id="sg-actions-data">' . wp_json_encode( $data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . '</script></div>';
|
||||
echo '<p><button class="button button-primary">' . ( $a ? 'Save reward' : 'Add reward' ) . '</button> <a class="button" href="' . esc_url( self::url() ) . '">Cancel</a></p></form>';
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- handlers */
|
||||
|
||||
public static function handleSave(): void {
|
||||
Admin::guard( 'sg_action_save' );
|
||||
$post = Admin::post_raw();
|
||||
$id = isset( $post['action_id'] ) ? absint( $post['action_id'] ) : 0;
|
||||
$back = self::url( $id ? array( 'edit' => $id ) : array( 'view' => 'new' ) );
|
||||
$repo = self::repo();
|
||||
if ( $id && ! $repo->find( $id ) ) {
|
||||
Admin::redirect( self::url(), 'error', 'That reward no longer exists.' );
|
||||
}
|
||||
$res = ActionInput::validate( $post, self::minMinor(), Admin::currency(), array_keys( self::goalTitles() ), $repo->nextSort() );
|
||||
if ( null === $res['data'] ) {
|
||||
Admin::redirect( $back, 'error', (string) $res['error'] );
|
||||
}
|
||||
if ( $id ) {
|
||||
$repo->update( $id, $res['data'] );
|
||||
} else {
|
||||
$repo->create( $res['data'] );
|
||||
}
|
||||
Admin::redirect( self::url(), 'success', 'Reward saved.' );
|
||||
}
|
||||
|
||||
public static function handleToggle(): void {
|
||||
Admin::guard( 'sg_action_toggle' );
|
||||
$post = Admin::post_raw();
|
||||
self::repo()->setEnabled( isset( $post['action_id'] ) ? absint( $post['action_id'] ) : 0, ! empty( $post['enabled'] ) );
|
||||
Admin::redirect( self::url(), 'success', 'Reward updated.' );
|
||||
}
|
||||
|
||||
public static function handleDelete(): void {
|
||||
Admin::guard( 'sg_action_delete' );
|
||||
$post = Admin::post_raw();
|
||||
self::repo()->delete( isset( $post['action_id'] ) ? absint( $post['action_id'] ) : 0 );
|
||||
Admin::redirect( self::url(), 'success', 'Reward deleted.' );
|
||||
}
|
||||
|
||||
public static function handleDone(): void {
|
||||
Admin::guard( 'sg_event_done' );
|
||||
$post = Admin::post_raw();
|
||||
self::repo()->markDone( isset( $post['event_id'] ) ? absint( $post['event_id'] ) : 0 );
|
||||
Admin::redirect( self::url(), 'success', 'Marked as done.' );
|
||||
}
|
||||
|
||||
public static function handleDoneAll(): void {
|
||||
Admin::guard( 'sg_event_done_all' );
|
||||
$n = self::repo()->markAllDone();
|
||||
Admin::redirect( self::url(), 'success', $n . ( 1 === $n ? ' reward' : ' rewards' ) . ' marked as done.' );
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,11 @@ final class Admin {
|
||||
'sg_rule_save' => array( GoalsPage::class, 'handleRuleSave' ),
|
||||
'sg_rule_toggle' => array( GoalsPage::class, 'handleRuleToggle' ),
|
||||
'sg_rule_delete' => array( GoalsPage::class, 'handleRuleDelete' ),
|
||||
'sg_action_save' => array( ActionsPage::class, 'handleSave' ),
|
||||
'sg_action_toggle' => array( ActionsPage::class, 'handleToggle' ),
|
||||
'sg_action_delete' => array( ActionsPage::class, 'handleDelete' ),
|
||||
'sg_event_done' => array( ActionsPage::class, 'handleDone' ),
|
||||
'sg_event_done_all' => array( ActionsPage::class, 'handleDoneAll' ),
|
||||
'sg_export_csv' => array( DonationsPage::class, 'handleExport' ),
|
||||
'sg_moderate' => array( DonationsPage::class, 'handleModerate' ),
|
||||
'sg_test_donation' => array( OverlaysPage::class, 'handleTestDonation' ),
|
||||
@@ -57,6 +62,9 @@ final class Admin {
|
||||
$badge = $pending > 0 ? ' <span class="awaiting-mod">' . (int) $pending . '</span>' : '';
|
||||
add_submenu_page( self::HOME, 'Moderation', 'Moderation' . $badge, self::CAP, 'streamgoals-moderation', array( DonationsPage::class, 'renderModeration' ) );
|
||||
}
|
||||
$queued = ActionsPage::queuedCount();
|
||||
$qbadge = $queued > 0 ? ' <span class="awaiting-mod">' . (int) $queued . '</span>' : '';
|
||||
add_submenu_page( self::HOME, 'Rewards', 'Rewards' . $qbadge, self::CAP, ActionsPage::PAGE, array( ActionsPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Overlays', 'Overlays', self::CAP, 'streamgoals-overlays', array( OverlaysPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Settings', 'Settings', self::CAP, 'streamgoals-settings', array( SettingsPage::class, 'render' ) );
|
||||
}
|
||||
@@ -90,6 +98,9 @@ final class Admin {
|
||||
if ( self::HOME === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-rules', STREAMGOALS_URL . 'assets/admin/rules.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
if ( ActionsPage::PAGE === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-actions', STREAMGOALS_URL . 'assets/admin/actions.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
if ( 'streamgoals-overlays' === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-overlays', STREAMGOALS_URL . 'assets/admin/overlays.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ final class GoalsPage {
|
||||
$pct = $target > 0 ? min( 100, intdiv( $raised * 100, $target ) ) : 0;
|
||||
echo '<tr><td><strong>' . esc_html( (string) $g['title'] ) . '</strong><br><span class="description">ID ' . $gid . ' · <code>[streamgoals_donate goal="' . $gid . '"]</code></span></td>';
|
||||
echo '<td><span class="sg-badge sg-' . esc_attr( (string) $g['status'] ) . '">' . esc_html( self::STATUSES[ $g['status'] ] ?? (string) $g['status'] ) . '</span></td>';
|
||||
echo '<td>' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div></td>';
|
||||
echo '<td>' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div>' . ( ! empty( $g['close_at_target'] ) ? '<span class="description">Closes at target</span>' : '' ) . '</td>';
|
||||
echo '<td>' . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '<br>' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '</td><td class="sg-actions">';
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'edit', 'goal' => $gid ) ) ) . '">Edit</a> ';
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ) ) . '">Rules</a> ';
|
||||
@@ -90,6 +90,7 @@ final class GoalsPage {
|
||||
echo '<tr><th scope="row"><label for="sg_start">Starts</label></th><td><input type="datetime-local" id="sg_start" name="starts_at" value="' . esc_attr( $fmt( $g['starts_at'] ?? null ) ) . '"> <span class="description">Optional. Your site time zone. Empty = starts immediately.</span></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_end">Ends</label></th><td><input type="datetime-local" id="sg_end" name="ends_at" value="' . esc_attr( $fmt( $g['ends_at'] ?? null ) ) . '"> <span class="description">Optional. Donations stop after this time.</span></td></tr>';
|
||||
echo '<tr><th scope="row">Fees</th><td><label><input type="checkbox" name="counts_fees" value="1"' . checked( ! empty( $g['counts_fees'] ), true, false ) . '> Count fees covered by donors towards the goal</label><p class="description">Off (recommended): only the amount the donor chose counts, so a $10 donation always adds $10 even if they also covered the fee.</p></td></tr>';
|
||||
echo '<tr><th scope="row">End at target</th><td><label><input type="checkbox" name="close_at_target" value="1"' . checked( ! empty( $g['close_at_target'] ), true, false ) . '> Close this goal to donations when the target is reached</label><p class="description">When the raised total reaches or goes over the target, the goal is marked complete and the donation page stops taking donations to it. Donations already in checkout still complete. You can reopen it with "Reopen" (raise the target first if you want more donations: a reopened goal that is still at or over its target closes again after the next donation).</p></td></tr>';
|
||||
echo '</table><p><button class="button button-primary">' . ( $g ? 'Save goal' : 'Create goal' ) . '</button> <a class="button" href="' . esc_url( Admin::url() ) . '">Cancel</a></p></form>';
|
||||
Admin::close();
|
||||
}
|
||||
@@ -131,7 +132,7 @@ final class GoalsPage {
|
||||
if ( $start && $end && strtotime( $end . ' UTC' ) <= strtotime( $start . ' UTC' ) ) {
|
||||
Admin::redirect( $back, 'error', 'The end must be after the start.' );
|
||||
}
|
||||
$data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1 );
|
||||
$data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1, 'close_at_target' => \StreamGoals\Core\GoalTargetPolicy::flagFromPost( $post['close_at_target'] ?? null ) );
|
||||
if ( $id ) {
|
||||
Store::goals()->update( $id, $data );
|
||||
} else {
|
||||
|
||||
@@ -15,6 +15,7 @@ final class OverlaysPage {
|
||||
'timer' => array( 'Subathon timer', 400, 120, 'Countdown that grows with donations (needs an "Add time" rule).' ),
|
||||
'counter' => array( 'Counter', 400, 120, 'A running count (needs a "Counter" rule).' ),
|
||||
'alerts' => array( 'Donation alerts', 600, 300, 'Pop-up alert for each new donation.' ),
|
||||
'actions' => array( 'Rewards menu', 500, 400, 'Lists your donation actions (e.g. "$5: Eat a bean") for the active goal. Shows nothing if you have none.' ),
|
||||
);
|
||||
|
||||
/** @return array{url:string,base:string,sep:string} */
|
||||
|
||||
@@ -56,7 +56,7 @@ final class SettingsPage {
|
||||
foreach ( \StreamGoals\Core\ClientIp::MODES as $k => $l ) {
|
||||
echo '<option value="' . esc_attr( $k ) . '"' . selected( (string) $s['visitor_ip_header'], $k, false ) . '>' . esc_html( $l ) . '</option>';
|
||||
}
|
||||
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). If your site is behind Cloudflare or another proxy, choose it here so each visitor is counted separately; otherwise everyone looks like the same visitor and a busy moment, like a raid, could block donations. Only choose a proxy option if <em>all</em> traffic to your site really goes through it.</p>';
|
||||
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). Behind a proxy, every visitor can look like the same address, and a busy moment, like a raid, could block donations. <strong>Automatic</strong> recognises Cloudflare by its published addresses and counts each visitor separately; it ignores forged headers from anywhere else. For another kind of proxy, choose its option here, but only if <em>all</em> traffic to your site really goes through it.</p>';
|
||||
self::ipDiagnostics( (string) $s['visitor_ip_header'] );
|
||||
echo '</td></tr></table></div>';
|
||||
|
||||
@@ -80,7 +80,7 @@ final class SettingsPage {
|
||||
|
||||
/** Shows the owner what their server passes to the plugin right now, to help pick the right option. */
|
||||
private static function ipDiagnostics( string $mode ): void {
|
||||
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
|
||||
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_CF_RAY' => 'CF-Ray', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
|
||||
$server = array();
|
||||
foreach ( $keys as $k => $_ ) {
|
||||
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
|
||||
@@ -91,8 +91,10 @@ final class SettingsPage {
|
||||
foreach ( $keys as $k => $label ) {
|
||||
echo '<tr><td>' . esc_html( $label ) . '</td><td><code>' . ( isset( $server[ $k ] ) ? esc_html( $server[ $k ] ) : '(not sent)' ) . '</code></td></tr>';
|
||||
}
|
||||
$viaCf = isset( $server['REMOTE_ADDR'] ) && \StreamGoals\Core\CloudflareRanges::isCloudflare( $server['REMOTE_ADDR'], (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
|
||||
echo '<tr><td>Is this connection from Cloudflare?</td><td>' . ( $viaCf ? '<strong>Yes</strong> - the connection comes from a Cloudflare address' : 'No' ) . '</td></tr>';
|
||||
echo '<tr><td><strong>Visitor address used with the saved option</strong></td><td><code>' . esc_html( \StreamGoals\Core\ClientIp::resolve( $server, $mode ) ) . '</code></td></tr>';
|
||||
echo '</tbody></table><p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
|
||||
echo '</tbody></table>' . ( ! $viaCf && ( isset( $server['HTTP_CF_RAY'] ) || isset( $server['HTTP_CF_CONNECTING_IP'] ) ) ? '<p class="sg-warn">Cloudflare headers were sent, but the connection is not from a known Cloudflare address, so "Automatic" ignores them. If your site really is behind Cloudflare, choose "Cloudflare" above (or update the plugin, as Cloudflare may have added new addresses).</p>' : '' ) . '<p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
|
||||
}
|
||||
|
||||
public static function handleSave(): void {
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/** Pure IPv4/IPv6 CIDR membership test (no WordPress, no network). Malformed input never matches. */
|
||||
final class CidrMatcher {
|
||||
|
||||
/** @param string[] $cidrs e.g. ['173.245.48.0/20', '2606:4700::/32'] */
|
||||
public static function contains( string $ip, array $cidrs ): bool {
|
||||
$ipBin = @inet_pton( trim( $ip ) );
|
||||
if ( false === $ipBin ) {
|
||||
return false;
|
||||
}
|
||||
foreach ( $cidrs as $cidr ) {
|
||||
if ( self::inRange( $ipBin, (string) $cidr ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function inRange( string $ipBin, string $cidr ): bool {
|
||||
$parts = explode( '/', trim( $cidr ), 2 );
|
||||
if ( 2 !== count( $parts ) || ! ctype_digit( $parts[1] ) ) {
|
||||
return false;
|
||||
}
|
||||
$netBin = @inet_pton( $parts[0] );
|
||||
if ( false === $netBin || strlen( $netBin ) !== strlen( $ipBin ) ) { // different address families never match
|
||||
return false;
|
||||
}
|
||||
$bits = (int) $parts[1];
|
||||
if ( $bits < 0 || $bits > strlen( $netBin ) * 8 ) {
|
||||
return false;
|
||||
}
|
||||
$fullBytes = intdiv( $bits, 8 );
|
||||
if ( $fullBytes > 0 && substr( $ipBin, 0, $fullBytes ) !== substr( $netBin, 0, $fullBytes ) ) {
|
||||
return false;
|
||||
}
|
||||
$rest = $bits % 8;
|
||||
if ( 0 === $rest ) {
|
||||
return true;
|
||||
}
|
||||
$mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF;
|
||||
return ( ord( $ipBin[ $fullBytes ] ) & $mask ) === ( ord( $netBin[ $fullBytes ] ) & $mask );
|
||||
}
|
||||
}
|
||||
@@ -12,12 +12,14 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class ClientIp {
|
||||
|
||||
public const MODE_AUTO = 'auto'; // detect Cloudflare automatically (recommended)
|
||||
public const MODE_DIRECT = ''; // no proxy: use REMOTE_ADDR
|
||||
public const MODE_CLOUDFLARE = 'cloudflare'; // CF-Connecting-IP
|
||||
public const MODE_REAL_IP = 'real_ip'; // X-Real-IP (nginx and many hosts)
|
||||
public const MODE_FORWARDED = 'forwarded'; // last address in X-Forwarded-For (exactly one proxy in front)
|
||||
|
||||
public const MODES = array(
|
||||
self::MODE_AUTO => 'Automatic (recommended): detects Cloudflare',
|
||||
self::MODE_DIRECT => 'Not behind a proxy or CDN (most sites)',
|
||||
self::MODE_CLOUDFLARE => 'Cloudflare (CF-Connecting-IP)',
|
||||
self::MODE_REAL_IP => 'X-Real-IP header',
|
||||
@@ -25,10 +27,16 @@ final class ClientIp {
|
||||
);
|
||||
|
||||
/** @param array<string,mixed> $server $_SERVER-style values (already unslashed). */
|
||||
public static function resolve( array $server, string $mode = self::MODE_DIRECT ): string {
|
||||
public static function resolve( array $server, string $mode = self::MODE_DIRECT, ?array $extraCloudflareRanges = null ): string {
|
||||
$remote = self::valid( $server['REMOTE_ADDR'] ?? null );
|
||||
$fromHeader = null;
|
||||
switch ( $mode ) {
|
||||
case self::MODE_AUTO:
|
||||
// Trust CF-Connecting-IP only when the connection itself comes from a Cloudflare address.
|
||||
if ( null !== $remote && CloudflareRanges::isCloudflare( $remote, $extraCloudflareRanges ) ) {
|
||||
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
|
||||
}
|
||||
break;
|
||||
case self::MODE_CLOUDFLARE:
|
||||
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
|
||||
break;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/**
|
||||
* Cloudflare's published proxy address ranges (https://www.cloudflare.com/ips-v4 and /ips-v6), fetched 2026-11-15.
|
||||
* They change very rarely. Sites can extend them with the `streamgoals_cloudflare_ranges` filter.
|
||||
* Used ONLY to decide whether a connection really comes from Cloudflare, so a forged CF-Connecting-IP header
|
||||
* from anywhere else is ignored.
|
||||
*/
|
||||
final class CloudflareRanges {
|
||||
|
||||
public const RANGES = array(
|
||||
'173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18',
|
||||
'190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
|
||||
'104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22',
|
||||
'2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32',
|
||||
);
|
||||
|
||||
/** @param string[]|null $extra additional ranges (from the filter) */
|
||||
public static function isCloudflare( string $ip, ?array $extra = null ): bool {
|
||||
return CidrMatcher::contains( $ip, array_merge( self::RANGES, $extra ?? array() ) );
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ namespace StreamGoals\Core;
|
||||
/** $wpdb-backed CRUD for sg_goals. Requires live WordPress. */
|
||||
final class GoalRepository {
|
||||
|
||||
private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d' );
|
||||
private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d', 'close_at_target' => '%d' );
|
||||
|
||||
private \wpdb $db;
|
||||
|
||||
@@ -21,7 +21,7 @@ final class GoalRepository {
|
||||
/** @return int new goal id */
|
||||
public function create( array $data ): int {
|
||||
$row = array_intersect_key( $data, self::FIELDS );
|
||||
$row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0 );
|
||||
$row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0, 'close_at_target' => 0 );
|
||||
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
|
||||
$this->db->insert( $this->table(), $row );
|
||||
return (int) $this->db->insert_id;
|
||||
@@ -62,9 +62,26 @@ final class GoalRepository {
|
||||
if ( ! $goal ) {
|
||||
return 0;
|
||||
}
|
||||
$col = ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor'; // whitelisted, not user input
|
||||
$col = GoalTargetPolicy::amountColumn( $goal ); // whitelisted, not user input
|
||||
$d = $this->db->prefix . 'sg_donations';
|
||||
$sum = $this->db->get_var( $this->db->prepare( "SELECT COALESCE(SUM({$col}), 0) FROM {$d} WHERE goal_id = %d AND status = 'completed'", $goalId ) );
|
||||
return (int) $sum;
|
||||
}
|
||||
|
||||
/**
|
||||
* "End at target": if the goal is active, flagged close_at_target and its raised total has reached the
|
||||
* target, set it to 'complete'. The UPDATE is conditional on status = 'active', so concurrent callers
|
||||
* change it once. Idempotent and cheap (one SELECT for non-flagged goals). Returns true if THIS call closed it.
|
||||
*/
|
||||
public function closeIfTargetReached( int $goalId ): bool {
|
||||
$goal = $this->find( $goalId );
|
||||
if ( ! $goal || empty( $goal['close_at_target'] ) || 'active' !== $goal['status'] ) {
|
||||
return false;
|
||||
}
|
||||
if ( ! GoalTargetPolicy::shouldClose( $goal, $this->raised_minor( $goalId ) ) ) {
|
||||
return false;
|
||||
}
|
||||
$n = $this->db->query( $this->db->prepare( "UPDATE {$this->table()} SET status = 'complete' WHERE id = %d AND status = 'active' AND close_at_target = 1", $goalId ) );
|
||||
return 1 === $n;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/** Pure rules for "end at target" goals (no WordPress / database access). */
|
||||
final class GoalTargetPolicy {
|
||||
|
||||
/** Donation column summed towards the goal: total (fees included) or base. Whitelisted values only. */
|
||||
public static function amountColumn( array $goal ): string {
|
||||
return ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor';
|
||||
}
|
||||
|
||||
/** True when the goal should now be auto-closed: flag on, currently active, target set and reached or exceeded. */
|
||||
public static function shouldClose( array $goal, int $raisedMinor ): bool {
|
||||
return ! empty( $goal['close_at_target'] )
|
||||
&& 'active' === ( $goal['status'] ?? '' )
|
||||
&& (int) ( $goal['target_minor'] ?? 0 ) > 0
|
||||
&& $raisedMinor >= (int) $goal['target_minor'];
|
||||
}
|
||||
|
||||
/** True for a goal that is closed to donors because it reached its target (flag on + complete). */
|
||||
public static function isClosedAtTarget( array $goal ): bool {
|
||||
return ! empty( $goal['close_at_target'] ) && 'complete' === ( $goal['status'] ?? '' );
|
||||
}
|
||||
|
||||
/** Checkbox value from a raw form field: 1 when ticked, else 0. */
|
||||
public static function flagFromPost( mixed $raw ): int {
|
||||
if ( is_array( $raw ) || null === $raw ) {
|
||||
return 0;
|
||||
}
|
||||
return in_array( strtolower( trim( (string) $raw ) ), array( '1', 'on', 'true', 'yes' ), true ) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class Installer {
|
||||
|
||||
public const DB_VERSION = '1';
|
||||
public const DB_VERSION = '3';
|
||||
|
||||
public static function activate(): void {
|
||||
self::install_schema();
|
||||
@@ -39,6 +39,7 @@ final class Installer {
|
||||
starts_at DATETIME NULL,
|
||||
ends_at DATETIME NULL,
|
||||
counts_fees TINYINT(1) NOT NULL DEFAULT 0,
|
||||
close_at_target TINYINT(1) NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
) $c;" );
|
||||
@@ -94,6 +95,54 @@ final class Installer {
|
||||
PRIMARY KEY (goal_id,skey)
|
||||
) $c;" );
|
||||
|
||||
dbDelta( "CREATE TABLE {$p}actions (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
goal_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
title VARCHAR(120) NOT NULL,
|
||||
description VARCHAR(255) NOT NULL DEFAULT '',
|
||||
amount_minor BIGINT UNSIGNED NOT NULL,
|
||||
mode VARCHAR(8) NOT NULL DEFAULT 'exact',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||
sort INT NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY goal_enabled (goal_id,enabled)
|
||||
) $c;" );
|
||||
|
||||
dbDelta( "CREATE TABLE {$p}action_events (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
donation_id BIGINT UNSIGNED NOT NULL,
|
||||
action_id BIGINT UNSIGNED NOT NULL,
|
||||
times INT NOT NULL DEFAULT 1,
|
||||
title VARCHAR(120) NOT NULL,
|
||||
status VARCHAR(8) NOT NULL DEFAULT 'queued',
|
||||
created_at DATETIME NOT NULL,
|
||||
done_at DATETIME NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY donation_action (donation_id,action_id),
|
||||
KEY status_id (status,id)
|
||||
) $c;" );
|
||||
|
||||
dbDelta( "CREATE TABLE {$p}alert_defs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
goal_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
trigger_type VARCHAR(8) NOT NULL DEFAULT 'amount',
|
||||
min_minor BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
action_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
title VARCHAR(120) NOT NULL DEFAULT '',
|
||||
visual_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
visual_type VARCHAR(6) NOT NULL DEFAULT '',
|
||||
sound_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
volume TINYINT UNSIGNED NOT NULL DEFAULT 80,
|
||||
duration_ms INT UNSIGNED NOT NULL DEFAULT 6000,
|
||||
message VARCHAR(255) NOT NULL DEFAULT '',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||
sort INT NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY goal_enabled (goal_id,enabled)
|
||||
) $c;" );
|
||||
|
||||
update_option( 'sg_db_version', self::DB_VERSION );
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ final class Settings {
|
||||
'message_max_length' => 200,
|
||||
'min_donation_minor' => 100,
|
||||
'overlay_token' => '',
|
||||
'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp)
|
||||
'visitor_ip_header' => 'auto', // auto | '' (direct) | cloudflare | real_ip | forwarded (see Core\ClientIp)
|
||||
'funding_paylater' => false, // show PayPal "Pay Later" button
|
||||
'update_token' => '', // optional Gitea read token (only while the update repo is private)
|
||||
'funding_card' => true, // show the Debit/Credit Card button
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** Optional capability: donation actions (rewards). Sources without it simply show no actions. */
|
||||
interface ActionsSource {
|
||||
|
||||
/**
|
||||
* Enabled actions for the goal (goal_id = $goalId or 0), already filtered to the effective minimum and ordered.
|
||||
* Raw rows with keys title, description, amount_minor, mode.
|
||||
*
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function menuActions( int $goalId ): array;
|
||||
|
||||
/**
|
||||
* Triggered actions per donation (sg_action_events), in trigger order. One lookup for the whole page.
|
||||
* Raw rows with keys title, times; Payloads sanitizes them.
|
||||
*
|
||||
* @param int[] $donationIds
|
||||
* @return array<int,array<int,array<string,mixed>>> donation id => events
|
||||
*/
|
||||
public function actionsFor( array $donationIds ): array;
|
||||
}
|
||||
@@ -6,11 +6,11 @@ namespace StreamGoals\Overlay;
|
||||
/** Maps a widget name to its payload using a data source. */
|
||||
final class OverlayService {
|
||||
|
||||
public const WIDGETS = array( 'goal', 'timer', 'counter', 'alerts' );
|
||||
public const WIDGETS = array( 'goal', 'timer', 'counter', 'alerts', 'actions' );
|
||||
|
||||
public function __construct( private OverlayDataSource $source ) {}
|
||||
|
||||
public function payload( string $widget, int $now, ?int $since = null ): ?array {
|
||||
public function payload( string $widget, int $now, ?int $since = null, bool $recent = false ): ?array {
|
||||
$goal = $this->source->activeGoal();
|
||||
$gid = $goal ? (int) $goal['id'] : 0;
|
||||
switch ( $widget ) {
|
||||
@@ -26,13 +26,27 @@ final class OverlayService {
|
||||
$c = $gid ? $this->source->counter( $gid ) : array( 'label' => '', 'value' => 0 );
|
||||
return Payloads::counter( $c['label'], $c['value'] );
|
||||
case 'alerts':
|
||||
$rows = $this->source->donations( $since, 20 );
|
||||
if ( $recent ) {
|
||||
// Newest 20 approved rows regardless of cursor. Sources that predate RecentDonationsSource
|
||||
// fall back to the oldest 20 (still correct for small installs, just not "newest").
|
||||
$rows = $this->source instanceof RecentDonationsSource
|
||||
? $this->source->recentDonations( 20 )
|
||||
: $this->source->donations( 0, 20 );
|
||||
$since = null;
|
||||
} else {
|
||||
$rows = $this->source->donations( $since, 20 );
|
||||
}
|
||||
$ids = array_values( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), $rows ) ) );
|
||||
$bonuses = ( null !== $since && $ids ) ? $this->source->bonusesFor( $ids ) : array();
|
||||
$bonuses = ( ( $recent || null !== $since ) && $ids ) ? $this->source->bonusesFor( $ids ) : array();
|
||||
$actions = ( ( $recent || null !== $since ) && $ids && $this->source instanceof ActionsSource ) ? $this->source->actionsFor( $ids ) : array();
|
||||
foreach ( $rows as $i => $r ) {
|
||||
$rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
$rows[ $i ]['actions'] = $actions[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
}
|
||||
return Payloads::alerts( $rows, $since );
|
||||
return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent );
|
||||
case 'actions':
|
||||
$rows = ( $gid && $this->source instanceof ActionsSource ) ? $this->source->menuActions( $gid ) : array();
|
||||
return Payloads::actionsMenu( $goal, $rows );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -74,9 +74,11 @@ final class Payloads {
|
||||
|
||||
/**
|
||||
* @param array<int,array<string,mixed>> $rows
|
||||
* @param int|null $since Null means "first poll": no alerts, just a baseline last_id.
|
||||
* @param int|null $since Null means "first poll": no alerts, just a baseline last_id.
|
||||
* @param bool $recent Recent mode: ignore $since and return the newest $limit approved alerts (ascending id),
|
||||
* so a message approved after newer donations still shows up. The client dedupes by id.
|
||||
*/
|
||||
public static function alerts( array $rows, ?int $since, int $limit = 10 ): array {
|
||||
public static function alerts( array $rows, ?int $since, int $limit = 10, bool $recent = false ): array {
|
||||
$safe = array();
|
||||
foreach ( $rows as $r ) {
|
||||
if ( 'completed' !== ( $r['status'] ?? '' ) || 'approved' !== ( $r['moderation'] ?? '' ) ) {
|
||||
@@ -85,6 +87,11 @@ final class Payloads {
|
||||
$safe[] = $r;
|
||||
}
|
||||
usort( $safe, static fn( $a, $b ) => (int) $a['id'] <=> (int) $b['id'] );
|
||||
if ( $recent ) {
|
||||
$safe = array_slice( $safe, -max( 1, $limit ) );
|
||||
$alerts = array_map( array( self::class, 'alert' ), $safe );
|
||||
return array( 'alerts' => $alerts, 'last_id' => $alerts ? (int) end( $alerts )['id'] : 0 );
|
||||
}
|
||||
$lastId = $since ?? 0;
|
||||
foreach ( $safe as $r ) {
|
||||
$lastId = max( $lastId, (int) $r['id'] );
|
||||
@@ -97,18 +104,7 @@ final class Payloads {
|
||||
if ( (int) $r['id'] <= $since ) {
|
||||
continue;
|
||||
}
|
||||
$cur = strtoupper( (string) ( $r['currency'] ?? 'USD' ) );
|
||||
$anon = ! empty( $r['is_anonymous'] );
|
||||
$name = trim( (string) ( $r['donor_name'] ?? '' ) );
|
||||
$alerts[] = array(
|
||||
'id' => (int) $r['id'],
|
||||
'name' => ( $anon || '' === $name ) ? self::ANON_NAME : $name,
|
||||
'amount_minor' => (int) $r['base_minor'],
|
||||
'amount_display' => self::money( (int) $r['base_minor'], $cur ),
|
||||
'currency' => $cur,
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
|
||||
);
|
||||
$alerts[] = self::alert( $r );
|
||||
}
|
||||
$alerts = array_slice( $alerts, 0, max( 1, $limit ) );
|
||||
if ( $alerts ) {
|
||||
@@ -117,6 +113,23 @@ final class Payloads {
|
||||
return array( 'alerts' => $alerts, 'last_id' => $lastId );
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $r */
|
||||
private static function alert( array $r ): array {
|
||||
$cur = strtoupper( (string) ( $r['currency'] ?? 'USD' ) );
|
||||
$anon = ! empty( $r['is_anonymous'] );
|
||||
$name = trim( (string) ( $r['donor_name'] ?? '' ) );
|
||||
return array(
|
||||
'id' => (int) $r['id'],
|
||||
'name' => ( $anon || '' === $name ) ? self::ANON_NAME : $name,
|
||||
'amount_minor' => (int) $r['base_minor'],
|
||||
'amount_display' => self::money( (int) $r['base_minor'], $cur ),
|
||||
'currency' => $cur,
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
|
||||
'actions' => self::actionEvents( $r['actions'] ?? array() ),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Display-safe bonus labels. Stored events should be [A-Za-z0-9_-] only; anything else is stripped
|
||||
* anyway, then humanized ("big_donation" -> "Big donation"). Empty/duplicate results are dropped.
|
||||
@@ -146,6 +159,70 @@ final class Payloads {
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Display-safe single line: no tags, control chars or runs of whitespace; capped at $max characters. */
|
||||
public static function text( mixed $v, int $max ): string {
|
||||
if ( ! is_scalar( $v ) ) {
|
||||
return '';
|
||||
}
|
||||
$s = strip_tags( (string) $v );
|
||||
$s = (string) preg_replace( '/[\x00-\x1F\x7F\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}\x{FEFF}]+/u', ' ', $s );
|
||||
$s = trim( (string) preg_replace( '/\s+/u', ' ', $s ) );
|
||||
return mb_substr( $s, 0, $max );
|
||||
}
|
||||
|
||||
/**
|
||||
* Triggered actions for one alert: [ {title, times} ]. At most 5, titles capped at 80 chars, times clamped to 1..999.
|
||||
*
|
||||
* @param mixed $events
|
||||
* @return array<int,array{title:string,times:int}>
|
||||
*/
|
||||
public static function actionEvents( mixed $events ): array {
|
||||
$out = array();
|
||||
foreach ( is_array( $events ) ? $events : array() as $e ) {
|
||||
if ( ! is_array( $e ) ) {
|
||||
continue;
|
||||
}
|
||||
$title = self::text( $e['title'] ?? '', 80 );
|
||||
if ( '' === $title ) {
|
||||
continue;
|
||||
}
|
||||
$out[] = array( 'title' => $title, 'times' => max( 1, min( 999, (int) ( $e['times'] ?? 1 ) ) ) );
|
||||
if ( count( $out ) >= 5 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The on-stream reward menu for the active goal. Empty list means "render nothing".
|
||||
*
|
||||
* @param array<string,mixed>|null $goal
|
||||
* @param array<int,array<string,mixed>> $rows Raw sg_actions rows, already ordered.
|
||||
*/
|
||||
public static function actionsMenu( ?array $goal, array $rows ): array {
|
||||
$cur = strtoupper( (string) ( $goal['currency'] ?? 'USD' ) );
|
||||
$list = array();
|
||||
foreach ( $goal ? $rows : array() as $r ) {
|
||||
$amount = (int) ( $r['amount_minor'] ?? 0 );
|
||||
$title = self::text( $r['title'] ?? '', 120 );
|
||||
if ( $amount <= 0 || '' === $title ) {
|
||||
continue;
|
||||
}
|
||||
$list[] = array(
|
||||
'title' => $title,
|
||||
'description' => self::text( $r['description'] ?? '', 255 ),
|
||||
'amount_minor' => $amount,
|
||||
'amount_display' => self::money( $amount, $cur ),
|
||||
'mode' => 'every' === ( $r['mode'] ?? '' ) ? 'every' : 'exact',
|
||||
);
|
||||
if ( count( $list ) >= 50 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return array( 'active' => (bool) $list, 'currency' => $cur, 'actions' => $list );
|
||||
}
|
||||
|
||||
/** Strong ETag over the payload, ignoring the volatile server_now so unchanged data yields 304s. */
|
||||
public static function etag( array $payload ): string {
|
||||
unset( $payload['server_now'] );
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** Optional capability: the newest approved donations, independent of any client cursor. */
|
||||
interface RecentDonationsSource {
|
||||
|
||||
/**
|
||||
* The $limit newest completed + approved donations, ascending id.
|
||||
*
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function recentDonations( int $limit ): array;
|
||||
}
|
||||
@@ -8,7 +8,7 @@ use StreamGoals\Rest\OverlayController;
|
||||
/** Serves the transparent OBS browser-source page at /streamgoals-overlay/{token}/{widget}/. */
|
||||
final class Router {
|
||||
|
||||
public const RULES_VERSION = '1';
|
||||
public const RULES_VERSION = '2';
|
||||
private const OPTION = 'sg_overlay_rules_version';
|
||||
|
||||
public static function register(): void {
|
||||
@@ -19,7 +19,7 @@ final class Router {
|
||||
|
||||
public static function add_rules(): void {
|
||||
add_rewrite_rule(
|
||||
'^streamgoals-overlay/([A-Za-z0-9]{16,128})/(goal|timer|counter|alerts)/?$',
|
||||
'^streamgoals-overlay/([A-Za-z0-9]{16,128})/(goal|timer|counter|alerts|actions)/?$',
|
||||
'index.php?sg_overlay_token=$matches[1]&sg_overlay_widget=$matches[2]',
|
||||
'top'
|
||||
);
|
||||
|
||||
@@ -4,7 +4,7 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */
|
||||
final class WpdbDataSource implements OverlayDataSource {
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource {
|
||||
|
||||
private function t( string $name ): string {
|
||||
global $wpdb;
|
||||
@@ -87,6 +87,36 @@ final class WpdbDataSource implements OverlayDataSource {
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function menuActions( int $goalId ): array {
|
||||
global $wpdb;
|
||||
$min = \StreamGoals\Core\Settings::effectiveMin( (int) \StreamGoals\Core\Settings::get( 'min_donation_minor', 0 ) );
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT title, description, amount_minor, mode FROM {$this->t('actions')}
|
||||
WHERE enabled = 1 AND goal_id IN (0, %d) AND amount_minor >= %d ORDER BY sort, amount_minor, id LIMIT 50",
|
||||
$goalId,
|
||||
$min
|
||||
), ARRAY_A );
|
||||
return (array) $rows;
|
||||
}
|
||||
|
||||
public function actionsFor( array $donationIds ): array {
|
||||
global $wpdb;
|
||||
$ids = array_values( array_unique( array_filter( array_map( 'intval', $donationIds ), static fn( $i ) => $i > 0 ) ) );
|
||||
if ( ! $ids ) {
|
||||
return array();
|
||||
}
|
||||
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT donation_id, title, times FROM {$this->t('action_events')} WHERE donation_id IN ($in) ORDER BY id ASC",
|
||||
$ids
|
||||
), ARRAY_A );
|
||||
$out = array();
|
||||
foreach ( (array) $rows as $row ) {
|
||||
$out[ (int) $row['donation_id'] ][] = array( 'title' => (string) $row['title'], 'times' => (int) $row['times'] );
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function donations( ?int $sinceId, int $limit ): array {
|
||||
global $wpdb;
|
||||
$cols = 'id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
|
||||
@@ -102,4 +132,14 @@ final class WpdbDataSource implements OverlayDataSource {
|
||||
}
|
||||
return (array) $rows;
|
||||
}
|
||||
|
||||
public function recentDonations( int $limit ): array {
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT id, base_minor, currency, donor_name, is_anonymous, message, status, moderation FROM {$this->t('donations')}
|
||||
WHERE status = 'completed' AND moderation = 'approved' ORDER BY id DESC LIMIT %d",
|
||||
max( 1, $limit )
|
||||
), ARRAY_A );
|
||||
return array_reverse( (array) $rows );
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,34 @@ final class DonationStore {
|
||||
/** 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 );
|
||||
// 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
|
||||
}
|
||||
self::close_goal_if_target_reached( $id );
|
||||
}
|
||||
|
||||
/**
|
||||
* "End at target": runs after the donation is already completed and counted, so it can never refuse or
|
||||
* undo a capture. Failures are logged and swallowed. Idempotent (atomic UPDATE ... WHERE status='active').
|
||||
*/
|
||||
public static function close_goal_if_target_reached( int $donationId ): void {
|
||||
try {
|
||||
$row = self::find( $donationId );
|
||||
if ( $row && (int) $row->goal_id > 0 ) {
|
||||
( new \StreamGoals\Core\GoalRepository() )->closeIfTargetReached( (int) $row->goal_id );
|
||||
}
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: end-at-target check failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
}
|
||||
}
|
||||
|
||||
/** Goals closed because they reached their target (newest first), for the donor-facing "goal reached" message. @return array[] */
|
||||
public static function reached_goals(): array {
|
||||
global $wpdb;
|
||||
return (array) $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'complete' AND close_at_target = 1 ORDER BY id DESC LIMIT 20", ARRAY_A );
|
||||
}
|
||||
|
||||
private static function call_engine( string $method, int $id ): void {
|
||||
|
||||
@@ -84,6 +84,9 @@ final class OrderValidator {
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public static function quote( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array {
|
||||
if ( 'complete' === ( $goal['status'] ?? '' ) ) {
|
||||
throw new ValidationException( 'goal_inactive', 'This goal is closed and no longer accepting donations. Thank you for your support!', 409 );
|
||||
}
|
||||
if ( ! self::goalIsOpen( $goal, $nowTs ) ) {
|
||||
throw new ValidationException( 'goal_inactive', 'This goal is not accepting donations.', 409 );
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Rest;
|
||||
|
||||
use StreamGoals\Core\GoalTargetPolicy;
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\PayPal\CaptureFinalizer;
|
||||
@@ -155,7 +156,8 @@ final class DonateController {
|
||||
return '<p class="sg-donate-unavailable">' . esc_html__( 'Donations are not available right now.', 'streamgoals-donate' ) . '</p>';
|
||||
}
|
||||
|
||||
$goals = array();
|
||||
$goals = array();
|
||||
$actions = self::actions_by_goal( array_map( static fn( $g ) => (int) $g['id'], DonationStore::active_goals() ), \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ) );
|
||||
foreach ( DonationStore::active_goals() as $g ) {
|
||||
if ( $pinned && (int) $g['id'] !== $pinned ) {
|
||||
continue;
|
||||
@@ -165,9 +167,15 @@ final class DonateController {
|
||||
'title' => (string) $g['title'],
|
||||
'currency' => strtoupper( (string) $g['currency'] ),
|
||||
'exp' => Money::exponent( (string) $g['currency'] ),
|
||||
'actions' => $actions[ (int) $g['id'] ] ?? 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>';
|
||||
}
|
||||
return '<p class="sg-donate-unavailable">' . esc_html__( 'There is no active goal to donate to right now.', 'streamgoals-donate' ) . '</p>';
|
||||
}
|
||||
|
||||
@@ -196,6 +204,9 @@ final class DonateController {
|
||||
'fixForm' => __( 'Please fix the form before paying.', 'streamgoals-donate' ),
|
||||
'customAmount' => __( 'Or enter your own amount', 'streamgoals-donate' ),
|
||||
'customPlaceholder' => __( 'Other amount', 'streamgoals-donate' ),
|
||||
/* translators: %s: formatted amount, e.g. $5.00 */
|
||||
'everyLabel' => __( 'Every %s', 'streamgoals-donate' ),
|
||||
'actionsHint' => __( 'Pick a reward, or enter your own amount below.', 'streamgoals-donate' ),
|
||||
/* translators: %s: formatted minimum amount, e.g. $1.00 */
|
||||
'minHint' => __( 'Minimum donation: %s', 'streamgoals-donate' ),
|
||||
/* translators: %s: formatted minimum amount, e.g. $1.00 */
|
||||
@@ -211,6 +222,41 @@ final class DonateController {
|
||||
|
||||
/* ------------------------------------------------------------- Helpers */
|
||||
|
||||
/**
|
||||
* Enabled actions per goal id (rows with goal_id 0 apply to every goal), at or above the effective minimum.
|
||||
* Public-safe fields only. One query; reads sg_actions directly.
|
||||
*
|
||||
* @param int[] $goalIds
|
||||
* @return array<int,array<int,array<string,mixed>>>
|
||||
*/
|
||||
private static function actions_by_goal( array $goalIds, int $min ): array {
|
||||
global $wpdb;
|
||||
$out = array();
|
||||
if ( ! $goalIds ) {
|
||||
return $out;
|
||||
}
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT id, goal_id, title, description, amount_minor, mode FROM {$wpdb->prefix}sg_actions
|
||||
WHERE enabled = 1 AND amount_minor >= %d ORDER BY sort, amount_minor, id LIMIT 500",
|
||||
max( 1, $min )
|
||||
), ARRAY_A );
|
||||
foreach ( (array) $rows as $r ) {
|
||||
$item = array(
|
||||
'id' => (int) $r['id'],
|
||||
'title' => (string) $r['title'],
|
||||
'description' => (string) $r['description'],
|
||||
'amount_minor' => (int) $r['amount_minor'],
|
||||
'mode' => 'every' === $r['mode'] ? 'every' : 'exact',
|
||||
);
|
||||
foreach ( $goalIds as $gid ) {
|
||||
if ( 0 === (int) $r['goal_id'] || (int) $r['goal_id'] === $gid ) {
|
||||
$out[ $gid ][] = $item;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Only whitelisted client fields are read; totals/fees from the client are ignored. */
|
||||
private static function input( \WP_REST_Request $req ): array {
|
||||
$out = array();
|
||||
@@ -238,7 +284,7 @@ final class DonateController {
|
||||
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
|
||||
}
|
||||
}
|
||||
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', '' ) );
|
||||
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', 'auto' ), (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
|
||||
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -18,12 +18,13 @@ final class OverlayController {
|
||||
}
|
||||
|
||||
public static function routes(): void {
|
||||
register_rest_route( 'streamgoals/v1', '/overlay/(?P<token>[A-Za-z0-9]{16,128})/(?P<widget>goal|timer|counter|alerts)', array(
|
||||
register_rest_route( 'streamgoals/v1', '/overlay/(?P<token>[A-Za-z0-9]{16,128})/(?P<widget>goal|timer|counter|alerts|actions)', array(
|
||||
'methods' => 'GET',
|
||||
'callback' => array( self::class, 'handle' ),
|
||||
'permission_callback' => '__return_true', // capability is the unguessable token, checked in handle()
|
||||
'args' => array(
|
||||
'since' => array( 'type' => 'integer', 'minimum' => 0, 'sanitize_callback' => 'absint' ),
|
||||
'recent' => array( 'type' => 'integer', 'minimum' => 0, 'maximum' => 1, 'sanitize_callback' => 'absint' ),
|
||||
),
|
||||
) );
|
||||
}
|
||||
@@ -47,7 +48,8 @@ final class OverlayController {
|
||||
return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) );
|
||||
}
|
||||
$since = $req->has_param( 'since' ) && '' !== (string) $req->get_param( 'since' ) ? absint( $req->get_param( 'since' ) ) : null;
|
||||
$payload = ( new OverlayService( new WpdbDataSource() ) )->payload( (string) $req['widget'], time(), $since );
|
||||
$recent = $req->has_param( 'recent' ) && 1 === absint( $req->get_param( 'recent' ) );
|
||||
$payload = ( new OverlayService( new WpdbDataSource() ) )->payload( (string) $req['widget'], time(), $since, $recent );
|
||||
if ( null === $payload ) {
|
||||
return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) );
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\ActionInput;
|
||||
|
||||
final class ActionInputTest extends TestCase {
|
||||
|
||||
private function post( array $o = array() ): array {
|
||||
return $o + array( 'title' => 'Eat a bean', 'description' => '', 'amount' => '5.00', 'mode' => 'every', 'goal_id' => '0', 'sort' => '' );
|
||||
}
|
||||
|
||||
private function v( array $o = array(), int $min = 100 ): array {
|
||||
return ActionInput::validate( $this->post( $o ), $min, 'USD', array( 3, 4 ), 40 );
|
||||
}
|
||||
|
||||
public function test_valid_input(): void {
|
||||
$r = $this->v( array( 'title' => ' <b>Eat</b> a bean ', 'description' => 'Yum', 'goal_id' => '3' ) );
|
||||
$this->assertNull( $r['error'] );
|
||||
$this->assertSame( array( 'goal_id' => 3, 'title' => 'Eat a bean', 'description' => 'Yum', 'amount_minor' => 500, 'mode' => 'every', 'sort' => 40 ), $r['data'] );
|
||||
}
|
||||
|
||||
public function test_title_required_and_max_120(): void {
|
||||
$this->assertNull( $this->v( array( 'title' => ' ' ) )['data'] );
|
||||
$this->assertNull( $this->v( array( 'title' => str_repeat( 'a', 121 ) ) )['data'] );
|
||||
$this->assertNotNull( $this->v( array( 'title' => str_repeat( 'a', 120 ) ) )['data'] );
|
||||
}
|
||||
|
||||
public function test_description_max_255(): void {
|
||||
$this->assertNull( $this->v( array( 'description' => str_repeat( 'a', 256 ) ) )['data'] );
|
||||
$this->assertNotNull( $this->v( array( 'description' => str_repeat( 'a', 255 ) ) )['data'] );
|
||||
}
|
||||
|
||||
public function test_amount_must_reach_the_minimum(): void {
|
||||
$low = $this->v( array( 'amount' => '0.99' ) );
|
||||
$this->assertNull( $low['data'] );
|
||||
$this->assertStringContainsString( 'minimum', (string) $low['error'] );
|
||||
$this->assertNotNull( $this->v( array( 'amount' => '1.00' ) )['data'] );
|
||||
$this->assertNull( $this->v( array( 'amount' => '4.99' ), 500 )['data'] );
|
||||
$this->assertNotNull( $this->v( array( 'amount' => '5' ), 500 )['data'] );
|
||||
}
|
||||
|
||||
public function test_bad_amounts(): void {
|
||||
foreach ( array( '', '0', '-5', 'abc', '5.123' ) as $bad ) {
|
||||
$this->assertNull( $this->v( array( 'amount' => $bad ) )['data'], "amount '$bad'" );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_mode_whitelist(): void {
|
||||
$this->assertNotNull( $this->v( array( 'mode' => 'exact' ) )['data'] );
|
||||
$this->assertNull( $this->v( array( 'mode' => 'always' ) )['data'] );
|
||||
$this->assertNull( $this->v( array( 'mode' => null ) )['data'] );
|
||||
}
|
||||
|
||||
public function test_goal_must_exist_or_be_zero(): void {
|
||||
$this->assertNotNull( $this->v( array( 'goal_id' => '4' ) )['data'] );
|
||||
$this->assertNull( $this->v( array( 'goal_id' => '99' ) )['data'] );
|
||||
$this->assertNull( $this->v( array( 'goal_id' => '-1' ) )['data'] );
|
||||
}
|
||||
|
||||
public function test_sort(): void {
|
||||
$this->assertSame( 7, $this->v( array( 'sort' => '7' ) )['data']['sort'] );
|
||||
$this->assertNull( $this->v( array( 'sort' => 'x' ) )['data'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Actions\Matcher;
|
||||
|
||||
final class ActionMatcherTest extends TestCase {
|
||||
|
||||
private function a( int $id, int $amount, string $mode, string $title = '' ): array {
|
||||
return array( 'id' => $id, 'title' => '' === $title ? "A$id" : $title, 'amount_minor' => $amount, 'mode' => $mode );
|
||||
}
|
||||
|
||||
public function test_exact_matches_only_the_same_amount(): void {
|
||||
$acts = array( $this->a( 1, 2500, 'exact' ) );
|
||||
$this->assertSame( array( array( 'action_id' => 1, 'title' => 'A1', 'times' => 1 ) ), Matcher::match( 2500, $acts ) );
|
||||
$this->assertSame( array(), Matcher::match( 2501, $acts ) );
|
||||
$this->assertSame( array(), Matcher::match( 5000, $acts ) );
|
||||
}
|
||||
|
||||
public function test_every_uses_floor_of_multiples(): void {
|
||||
$acts = array( $this->a( 1, 500, 'every' ) );
|
||||
$this->assertSame( 5, Matcher::match( 2500, $acts )[0]['times'] );
|
||||
$this->assertSame( 2, Matcher::match( 1099, $acts )[0]['times'], 'floor, not round' );
|
||||
$this->assertSame( 1, Matcher::match( 500, $acts )[0]['times'] );
|
||||
}
|
||||
|
||||
public function test_below_amount_never_matches(): void {
|
||||
$this->assertSame( array(), Matcher::match( 499, array( $this->a( 1, 500, 'every' ), $this->a( 2, 500, 'exact' ) ) ) );
|
||||
}
|
||||
|
||||
public function test_zero_and_negative_donations_match_nothing(): void {
|
||||
$acts = array( $this->a( 1, 100, 'every' ) );
|
||||
$this->assertSame( array(), Matcher::match( 0, $acts ) );
|
||||
$this->assertSame( array(), Matcher::match( -500, $acts ) );
|
||||
}
|
||||
|
||||
public function test_zero_and_negative_action_amounts_never_match(): void {
|
||||
$this->assertSame( array(), Matcher::match( 500, array( $this->a( 1, 0, 'every' ), $this->a( 2, -5, 'exact' ), $this->a( 3, -500, 'every' ) ) ) );
|
||||
}
|
||||
|
||||
public function test_several_actions_at_once_in_input_order(): void {
|
||||
$acts = array( $this->a( 7, 2500, 'exact', '25 pushups' ), $this->a( 3, 500, 'every', 'Eat a bean' ), $this->a( 9, 1000, 'exact' ) );
|
||||
$this->assertSame(
|
||||
array(
|
||||
array( 'action_id' => 7, 'title' => '25 pushups', 'times' => 1 ),
|
||||
array( 'action_id' => 3, 'title' => 'Eat a bean', 'times' => 5 ),
|
||||
),
|
||||
Matcher::match( 2500, $acts )
|
||||
);
|
||||
}
|
||||
|
||||
public function test_ordering_is_stable_not_resorted(): void {
|
||||
$acts = array( $this->a( 5, 100, 'every' ), $this->a( 2, 100, 'every' ), $this->a( 9, 100, 'every' ) );
|
||||
$this->assertSame( array( 5, 2, 9 ), array_column( Matcher::match( 300, $acts ), 'action_id' ) );
|
||||
}
|
||||
|
||||
public function test_bad_rows_are_ignored(): void {
|
||||
$acts = array(
|
||||
'junk',
|
||||
null,
|
||||
array(),
|
||||
array( 'id' => 1, 'title' => 'x', 'amount_minor' => 100 ),
|
||||
array( 'id' => 2, 'title' => 'x', 'amount_minor' => 100, 'mode' => 'weird' ),
|
||||
array( 'id' => 0, 'title' => 'x', 'amount_minor' => 100, 'mode' => 'every' ),
|
||||
array( 'id' => 'abc', 'title' => 'x', 'amount_minor' => 100, 'mode' => 'every' ),
|
||||
array( 'id' => 3, 'title' => 'x', 'amount_minor' => 'lots', 'mode' => 'every' ),
|
||||
array( 'id' => 4, 'title' => array(), 'amount_minor' => 100, 'mode' => 'every' ),
|
||||
array( 'id' => '5', 'title' => 'Good', 'amount_minor' => '100', 'mode' => 'every' ),
|
||||
);
|
||||
$this->assertSame( array( array( 'action_id' => 5, 'title' => 'Good', 'times' => 2 ) ), Matcher::match( 200, $acts ) );
|
||||
}
|
||||
|
||||
public function test_empty_menu(): void {
|
||||
$this->assertSame( array(), Matcher::match( 1000, array() ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Actions\ActionRepository;
|
||||
|
||||
final class ActionRepositoryTest extends TestCase {
|
||||
|
||||
private function fake(): object {
|
||||
if ( ! defined( 'ARRAY_A' ) ) {
|
||||
define( 'ARRAY_A', 'ARRAY_A' );
|
||||
}
|
||||
return new class() {
|
||||
public string $prefix = 'wp_';
|
||||
public array $sql = array();
|
||||
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 ) { $this->sql[] = $q; return 1; }
|
||||
public function get_results( string $q, $o = null ): array { $this->sql[] = $q; return $this->rows; }
|
||||
};
|
||||
}
|
||||
|
||||
public function test_record_events_is_insert_ignore(): void {
|
||||
$db = $this->fake();
|
||||
( new ActionRepository( $db ) )->recordEvents( 10, array( array( 'action_id' => 2, 'title' => 'Eat', 'times' => 5 ), array( 'action_id' => 3, 'title' => 'Push', 'times' => 1 ) ) );
|
||||
$this->assertCount( 2, $db->sql );
|
||||
foreach ( $db->sql as $q ) {
|
||||
$this->assertStringStartsWith( 'INSERT IGNORE INTO wp_sg_action_events', $q );
|
||||
}
|
||||
$this->assertStringContainsString( "VALUES (10, 2, 5, 'Eat', 'queued'", $db->sql[0] );
|
||||
}
|
||||
|
||||
public function test_record_events_skips_invalid_matches(): void {
|
||||
$db = $this->fake();
|
||||
$repo = new ActionRepository( $db );
|
||||
$repo->recordEvents( 10, array( array( 'action_id' => 0, 'title' => 'x', 'times' => 1 ), array( 'action_id' => 2, 'title' => 'x', 'times' => 0 ) ) );
|
||||
$repo->recordEvents( 0, array( array( 'action_id' => 2, 'title' => 'x', 'times' => 1 ) ) );
|
||||
$this->assertSame( array(), $db->sql );
|
||||
}
|
||||
|
||||
public function test_enabled_for_goal_filter_and_row_shape(): void {
|
||||
$db = $this->fake();
|
||||
$db->rows = array( array( 'id' => '4', 'goal_id' => '0', 'title' => 'T', 'description' => 'D', 'amount_minor' => '500', 'mode' => 'every', 'enabled' => '1', 'sort' => '10', 'created_at' => '2026-01-01 00:00:00' ) );
|
||||
$rows = ( new ActionRepository( $db ) )->enabledForGoal( 7 );
|
||||
$q = $db->sql[0];
|
||||
$this->assertStringContainsString( 'enabled = 1', $q );
|
||||
$this->assertStringContainsString( 'goal_id IN (0, 7)', $q );
|
||||
$this->assertStringContainsString( 'ORDER BY sort ASC, amount_minor ASC', $q );
|
||||
$this->assertSame( 4, $rows[0]['id'] );
|
||||
$this->assertSame( 500, $rows[0]['amount_minor'] );
|
||||
$this->assertSame( array( 'id', 'goal_id', 'title', 'description', 'amount_minor', 'mode', 'enabled', 'sort', 'created_at' ), array_keys( $rows[0] ) );
|
||||
}
|
||||
|
||||
public function test_mark_done_only_touches_queued_rows(): void {
|
||||
$db = $this->fake();
|
||||
$this->assertTrue( ( new ActionRepository( $db ) )->markDone( 5 ) );
|
||||
$this->assertStringContainsString( "AND status = 'queued'", $db->sql[0] );
|
||||
}
|
||||
|
||||
public function test_installer_schema_defines_both_tables_and_unique_key(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
|
||||
$this->assertSame( 1, preg_match( "/DB_VERSION = '(\\d+)'/", $src, $m ), 'DB_VERSION constant not found' );
|
||||
$this->assertGreaterThanOrEqual( 2, (int) $m[1], 'the actions tables arrived in schema version 2; later versions must keep them' );
|
||||
$this->assertStringContainsString( 'CREATE TABLE {$p}actions (', $src );
|
||||
$this->assertStringContainsString( 'CREATE TABLE {$p}action_events (', $src );
|
||||
$this->assertStringContainsString( 'UNIQUE KEY donation_action (donation_id,action_id)', $src );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Core\CidrMatcher;
|
||||
use StreamGoals\Core\CloudflareRanges;
|
||||
|
||||
final class CidrMatcherTest extends TestCase {
|
||||
|
||||
public function test_ipv4_boundaries(): void {
|
||||
$r = array( '173.245.48.0/20' ); // 173.245.48.0 - 173.245.63.255
|
||||
$this->assertTrue( CidrMatcher::contains( '173.245.48.0', $r ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '173.245.63.255', $r ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '173.245.47.255', $r ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '173.245.64.0', $r ) );
|
||||
}
|
||||
|
||||
public function test_non_byte_aligned_and_wide_masks(): void {
|
||||
$this->assertTrue( CidrMatcher::contains( '104.27.255.255', array( '104.24.0.0/14' ) ) ); // /14 spans 104.24 - 104.27
|
||||
$this->assertFalse( CidrMatcher::contains( '104.28.0.0', array( '104.24.0.0/14' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '104.23.255.255', array( '104.24.0.0/14' ) ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '8.8.8.8', array( '0.0.0.0/0' ) ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '1.2.3.4', array( '1.2.3.4/32' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '1.2.3.5', array( '1.2.3.4/32' ) ) );
|
||||
}
|
||||
|
||||
public function test_ipv6(): void {
|
||||
$this->assertTrue( CidrMatcher::contains( '2606:4700::1', array( '2606:4700::/32' ) ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '2a06:98c7:ffff::1', array( '2a06:98c0::/29' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '2a06:98c8::1', array( '2a06:98c0::/29' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '2606:4701::1', array( '2606:4700::/32' ) ) );
|
||||
}
|
||||
|
||||
public function test_families_never_cross_match_and_bad_input_is_false(): void {
|
||||
$this->assertFalse( CidrMatcher::contains( '1.2.3.4', array( '2606:4700::/32' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '2606:4700::1', array( '173.245.48.0/20' ) ) );
|
||||
foreach ( array( 'garbage', '', '999.1.1.1', "1.2.3.4\nX: y", '1.2.3.4, 5.6.7.8' ) as $bad ) {
|
||||
$this->assertFalse( CidrMatcher::contains( $bad, array( '0.0.0.0/0' ) ), "matched bad ip: $bad" );
|
||||
}
|
||||
foreach ( array( '1.2.3.4', '1.2.3.4/x', '1.2.3.4/33', '1.2.3.4/-1', 'nope/8', '' ) as $badCidr ) {
|
||||
$this->assertFalse( CidrMatcher::contains( '1.2.3.4', array( $badCidr ) ), "matched bad cidr: $badCidr" );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_surrounding_whitespace_is_tolerated(): void {
|
||||
$this->assertTrue( CidrMatcher::contains( ' 173.245.48.1 ', array( '173.245.48.0/20' ) ) );
|
||||
}
|
||||
|
||||
public function test_cloudflare_ranges(): void {
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '172.70.1.1' ) );
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '104.16.0.1' ) );
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '2606:4700:3030::1' ) );
|
||||
$this->assertFalse( CloudflareRanges::isCloudflare( '203.0.113.9' ) );
|
||||
$this->assertFalse( CloudflareRanges::isCloudflare( '47.151.185.180' ) );
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '203.0.113.9', array( '203.0.113.0/24' ) ), 'filter-supplied ranges extend the list' );
|
||||
}
|
||||
}
|
||||
@@ -56,4 +56,28 @@ final class ClientIpTest extends TestCase {
|
||||
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4' );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, 'something_else' ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_trusts_cf_header_only_from_a_cloudflare_connection(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => '172.70.1.1', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
|
||||
$v6 = array( 'REMOTE_ADDR' => '2606:4700:3030::1', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $v6, ClientIp::MODE_AUTO ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_ignores_a_forged_header_from_a_non_cloudflare_connection(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => '47.151.185.180', 'HTTP_CF_CONNECTING_IP' => '6.6.6.6', 'HTTP_X_FORWARDED_FOR' => '7.7.7.7' );
|
||||
$this->assertSame( '47.151.185.180', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_falls_back_when_header_missing_or_invalid(): void {
|
||||
$this->assertSame( '172.70.1.1', ClientIp::resolve( array( 'REMOTE_ADDR' => '172.70.1.1' ), ClientIp::MODE_AUTO ) );
|
||||
$this->assertSame( '172.70.1.1', ClientIp::resolve( array( 'REMOTE_ADDR' => '172.70.1.1', 'HTTP_CF_CONNECTING_IP' => 'nope' ), ClientIp::MODE_AUTO ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_extra_ranges_from_the_filter(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => '198.18.0.5', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( '198.18.0.5', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO, array( '198.18.0.0/15' ) ) );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Core\FeeCalculator;
|
||||
use StreamGoals\Core\GoalTargetPolicy;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\PayPal\OrderValidator;
|
||||
use StreamGoals\PayPal\ValidationException;
|
||||
|
||||
final class GoalTargetPolicyTest extends TestCase {
|
||||
|
||||
private function goal( array $o = array() ): array {
|
||||
return array_merge( array( 'id' => 3, 'currency' => 'USD', 'status' => 'active', 'target_minor' => 10000, 'close_at_target' => 1, 'counts_fees' => 0, 'starts_at' => null, 'ends_at' => null ), $o );
|
||||
}
|
||||
|
||||
public function test_below_equal_and_over_target(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal(), 9999 ) );
|
||||
$this->assertTrue( GoalTargetPolicy::shouldClose( $this->goal(), 10000 ) );
|
||||
$this->assertTrue( GoalTargetPolicy::shouldClose( $this->goal(), 25000 ) );
|
||||
}
|
||||
|
||||
public function test_flag_off_or_missing_never_closes(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'close_at_target' => 0 ) ), 99999 ) );
|
||||
$g = $this->goal();
|
||||
unset( $g['close_at_target'] );
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $g, 99999 ) );
|
||||
}
|
||||
|
||||
public function test_only_active_goals_are_closed(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'status' => 'complete' ) ), 20000 ) );
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'status' => 'paused' ) ), 20000 ) );
|
||||
}
|
||||
|
||||
public function test_target_zero_never_closes(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'target_minor' => 0 ) ), 0 ) );
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'target_minor' => 0 ) ), 500 ) );
|
||||
}
|
||||
|
||||
public function test_base_vs_total_basis(): void {
|
||||
$this->assertSame( 'base_minor', GoalTargetPolicy::amountColumn( $this->goal() ) );
|
||||
$this->assertSame( 'total_minor', GoalTargetPolicy::amountColumn( $this->goal( array( 'counts_fees' => 1 ) ) ) );
|
||||
}
|
||||
|
||||
public function test_closed_at_target_detection_and_pause_is_not_closed(): void {
|
||||
$this->assertTrue( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'complete' ) ) ) );
|
||||
$this->assertFalse( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'paused' ) ) ) );
|
||||
$this->assertFalse( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'complete', 'close_at_target' => 0 ) ) ) );
|
||||
}
|
||||
|
||||
public function test_checkbox_parsing(): void {
|
||||
$this->assertSame( 1, GoalTargetPolicy::flagFromPost( '1' ) );
|
||||
$this->assertSame( 1, GoalTargetPolicy::flagFromPost( 'on' ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( null ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( '' ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( '0' ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( array( '1' ) ) );
|
||||
}
|
||||
|
||||
public function test_new_orders_for_a_closed_goal_get_a_friendly_409(): void {
|
||||
try {
|
||||
OrderValidator::validate( array( 'amount' => '5.00' ), $this->goal( array( 'status' => 'complete' ) ), Settings::defaults(), new FeeCalculator( 349, 49 ), 1800000000 );
|
||||
$this->fail( 'expected refusal' );
|
||||
} catch ( ValidationException $e ) {
|
||||
$this->assertSame( 'goal_inactive', $e->errorCode );
|
||||
$this->assertSame( 409, $e->status );
|
||||
$this->assertStringContainsString( 'Thank you', $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_paused_goal_keeps_generic_message(): void {
|
||||
try {
|
||||
OrderValidator::quote( array( 'amount' => '5.00' ), $this->goal( array( 'status' => 'paused' ) ), Settings::defaults(), new FeeCalculator( 349, 49 ), 1800000000 );
|
||||
$this->fail( 'expected refusal' );
|
||||
} catch ( ValidationException $e ) {
|
||||
$this->assertSame( 'This goal is not accepting donations.', $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_goal_open_for_active_flagged_goal(): void {
|
||||
$this->assertTrue( OrderValidator::goalIsOpen( $this->goal(), 1800000000 ) );
|
||||
$this->assertFalse( OrderValidator::goalIsOpen( $this->goal( array( 'status' => 'complete' ) ), 1800000000 ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Core\Maintenance;
|
||||
|
||||
/**
|
||||
* The purge deletes rows, so pin down exactly what it may touch: only never-paid pending checkouts,
|
||||
* only older than a week, never test donations, never anything with a PayPal capture id.
|
||||
*/
|
||||
final class MaintenancePurgeTest extends TestCase {
|
||||
|
||||
private $previous;
|
||||
|
||||
protected function setUp(): void {
|
||||
foreach ( array( 'HOUR_IN_SECONDS' => 3600, 'DAY_IN_SECONDS' => 86400 ) as $k => $v ) {
|
||||
if ( ! defined( $k ) ) {
|
||||
define( $k, $v );
|
||||
}
|
||||
}
|
||||
$this->previous = $GLOBALS['wpdb'] ?? null;
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
$GLOBALS['wpdb'] = $this->previous;
|
||||
}
|
||||
|
||||
public function test_purge_sql_only_targets_abandoned_pending_rows_older_than_a_week(): void {
|
||||
$GLOBALS['wpdb'] = new class() {
|
||||
public string $prefix = 'wp_';
|
||||
public array $queries = array();
|
||||
public function prepare( string $q, ...$args ): string { return vsprintf( str_replace( '%s', "'%s'", $q ), $args ); }
|
||||
public function query( string $q ): int { $this->queries[] = $q; return 3; }
|
||||
};
|
||||
$before = time();
|
||||
$n = Maintenance::purge_abandoned();
|
||||
$sql = $GLOBALS['wpdb']->queries[0] ?? '';
|
||||
|
||||
$this->assertSame( 3, $n );
|
||||
$this->assertStringStartsWith( 'DELETE FROM wp_sg_donations', $sql );
|
||||
$this->assertStringContainsString( "status = 'pending'", $sql, 'completed donations must never be deleted' );
|
||||
$this->assertStringContainsString( "paypal_capture_id IS NULL OR paypal_capture_id = ''", $sql, 'anything with a PayPal capture must be kept' );
|
||||
$this->assertStringContainsString( 'goal_id > 0', $sql, 'test donations (goal_id 0) are handled separately and kept' );
|
||||
$this->assertMatchesRegularExpression( "/created_at < '(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})'/", $sql );
|
||||
preg_match( "/created_at < '([^']+)'/", $sql, $m );
|
||||
$cutoff = strtotime( $m[1] . ' UTC' );
|
||||
$this->assertEqualsWithDelta( $before - 7 * 86400, $cutoff, 5, 'cutoff must be 7 days ago' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Overlay\ActionsSource;
|
||||
use StreamGoals\Overlay\OverlayDataSource;
|
||||
use StreamGoals\Overlay\OverlayService;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\Overlay\RecentDonationsSource;
|
||||
|
||||
final class OverlayActionsTest extends TestCase {
|
||||
|
||||
/** @param array<int,array> $menu @param array<int,array> $events @param array<int,array> $db */
|
||||
private function svc( array $menu, array $events, array $db, bool $goal = true ): OverlayService {
|
||||
return new OverlayService( new class( $menu, $events, $db, $goal ) implements OverlayDataSource, RecentDonationsSource, ActionsSource {
|
||||
public int $actionQueries = 0;
|
||||
public function __construct( private array $menu, private array $events, private array $db, private bool $goal ) {}
|
||||
public function activeGoal(): ?array { return $this->goal ? array( 'id' => 7, 'currency' => 'USD' ) : null; }
|
||||
public function raisedMinor( array $goal ): int { return 0; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); }
|
||||
public function bonusesFor( array $ids ): array { return array(); }
|
||||
public function donations( ?int $sinceId, int $limit ): array {
|
||||
return array_values( array_filter( $this->db, static fn( $d ) => $d['id'] > (int) $sinceId ) );
|
||||
}
|
||||
public function recentDonations( int $limit ): array { return $this->db; }
|
||||
public function menuActions( int $goalId ): array { return $this->menu; }
|
||||
public function actionsFor( array $ids ): array { ++$this->actionQueries; return $this->events; }
|
||||
} );
|
||||
}
|
||||
|
||||
private function row( int $id, array $o = array() ): array {
|
||||
return $o + array( 'id' => $id, 'base_minor' => 2500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0,
|
||||
'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
|
||||
}
|
||||
|
||||
public function test_menu_lists_actions_with_display_and_mode(): void {
|
||||
$menu = array(
|
||||
array( 'title' => 'Eat a bean', 'description' => 'every flavor', 'amount_minor' => 500, 'mode' => 'every' ),
|
||||
array( 'title' => '25 pushups', 'description' => '', 'amount_minor' => 2500, 'mode' => 'exact' ),
|
||||
);
|
||||
$out = $this->svc( $menu, array(), array() )->payload( 'actions', 1 );
|
||||
$this->assertTrue( $out['active'] );
|
||||
$this->assertSame( '$5.00', $out['actions'][0]['amount_display'] );
|
||||
$this->assertSame( 'every', $out['actions'][0]['mode'] );
|
||||
$this->assertSame( 'exact', $out['actions'][1]['mode'] );
|
||||
$this->assertSame( '25 pushups', $out['actions'][1]['title'] );
|
||||
}
|
||||
|
||||
public function test_menu_empty_without_goal_or_actions_and_drops_bad_rows(): void {
|
||||
$this->assertFalse( $this->svc( array(), array(), array() )->payload( 'actions', 1 )['active'] );
|
||||
$menu = array( array( 'title' => 'x', 'amount_minor' => 500, 'mode' => 'exact' ) );
|
||||
$this->assertSame( array(), $this->svc( $menu, array(), array(), false )->payload( 'actions', 1 )['actions'] );
|
||||
$bad = array( array( 'title' => 'Zero', 'amount_minor' => 0 ), array( 'title' => ' ', 'amount_minor' => 500 ) );
|
||||
$this->assertSame( array(), Payloads::actionsMenu( array( 'currency' => 'USD' ), $bad )['actions'] );
|
||||
}
|
||||
|
||||
public function test_menu_sanitizes_hostile_strings(): void {
|
||||
$menu = array( array( 'title' => "<script>alert(1)</script>Do\x00 it\n now", 'description' => '<img src=x onerror=1>' . str_repeat( 'd', 400 ), 'amount_minor' => 500, 'mode' => 'weird' ) );
|
||||
$a = Payloads::actionsMenu( array( 'currency' => 'USD' ), $menu )['actions'][0];
|
||||
$this->assertStringNotContainsString( '<', $a['title'] . $a['description'] );
|
||||
$this->assertStringNotContainsString( "\n", $a['title'] );
|
||||
$this->assertLessThanOrEqual( 255, mb_strlen( $a['description'] ) );
|
||||
$this->assertSame( 'exact', $a['mode'] );
|
||||
}
|
||||
|
||||
public function test_alert_actions_shown_with_times_in_since_and_recent(): void {
|
||||
$events = array( 3 => array( array( 'title' => 'Eat a bean', 'times' => 3 ), array( 'title' => '25 pushups', 'times' => 1 ) ) );
|
||||
$db = array( $this->row( 3, array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ), $this->row( 4 ) );
|
||||
$svc = $this->svc( array(), $events, $db );
|
||||
$since = $svc->payload( 'alerts', 1, 0 );
|
||||
$recent = $svc->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( $since['alerts'], $recent['alerts'] );
|
||||
$a = $recent['alerts'][0];
|
||||
$this->assertSame( array( array( 'title' => 'Eat a bean', 'times' => 3 ), array( 'title' => '25 pushups', 'times' => 1 ) ), $a['actions'] );
|
||||
$this->assertSame( 'Anonymous', $a['name'] );
|
||||
$this->assertStringNotContainsString( 'Secret', json_encode( $recent ) );
|
||||
$this->assertSame( array(), $recent['alerts'][1]['actions'] );
|
||||
}
|
||||
|
||||
public function test_alert_actions_use_one_query_and_baseline_none(): void {
|
||||
$db = array( $this->row( 3 ), $this->row( 4 ) );
|
||||
$svc = $this->svc( array(), array(), $db );
|
||||
$svc->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( array(), $svc->payload( 'alerts', 1, null )['alerts'] );
|
||||
}
|
||||
|
||||
public function test_alert_actions_sanitized_capped_and_clamped(): void {
|
||||
$ev = array( array( 'title' => '<b>Hi</b>', 'times' => 0 ), array( 'title' => '', 'times' => 2 ), 'junk', array( 'title' => str_repeat( 'é', 200 ), 'times' => 99999 ) );
|
||||
for ( $i = 0; $i < 10; $i++ ) {
|
||||
$ev[] = array( 'title' => "T$i", 'times' => 1 );
|
||||
}
|
||||
$out = Payloads::actionEvents( $ev );
|
||||
$this->assertCount( 5, $out );
|
||||
$this->assertSame( array( 'title' => 'Hi', 'times' => 1 ), $out[0] );
|
||||
$this->assertSame( 80, mb_strlen( $out[1]['title'] ) );
|
||||
$this->assertSame( 999, $out[1]['times'] );
|
||||
$this->assertSame( array(), Payloads::actionEvents( 'nope' ) );
|
||||
}
|
||||
|
||||
public function test_etag_changes_when_actions_appear(): void {
|
||||
$db = array( $this->row( 3 ) );
|
||||
$none = $this->svc( array(), array(), $db )->payload( 'alerts', 1, null, true );
|
||||
$with = $this->svc( array(), array( 3 => array( array( 'title' => 'Bean', 'times' => 1 ) ) ), $db )->payload( 'alerts', 1, null, true );
|
||||
$this->assertNotSame( Payloads::etag( $none ), Payloads::etag( $with ) );
|
||||
$m1 = $this->svc( array(), array(), array() )->payload( 'actions', 1 );
|
||||
$m2 = $this->svc( array( array( 'title' => 'Bean', 'amount_minor' => 500, 'mode' => 'exact' ) ), array(), array() )->payload( 'actions', 1 );
|
||||
$this->assertNotSame( Payloads::etag( $m1 ), Payloads::etag( $m2 ) );
|
||||
}
|
||||
|
||||
public function test_source_without_actions_capability_still_works(): void {
|
||||
$svc = new OverlayService( new class implements OverlayDataSource {
|
||||
public function activeGoal(): ?array { return array( 'id' => 1, 'currency' => 'USD' ); }
|
||||
public function raisedMinor( array $goal ): int { return 0; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return array(); }
|
||||
public function bonusesFor( array $ids ): array { return array(); }
|
||||
} );
|
||||
$this->assertFalse( $svc->payload( 'actions', 1 )['active'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Overlay\OverlayDataSource;
|
||||
use StreamGoals\Overlay\OverlayService;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\Overlay\RecentDonationsSource;
|
||||
|
||||
final class OverlayRecentModeTest extends TestCase {
|
||||
|
||||
/** @param array<int,array<string,mixed>> $db */
|
||||
private function svc( array &$db ): OverlayService {
|
||||
return new OverlayService( new class( $db ) implements OverlayDataSource, RecentDonationsSource {
|
||||
public function __construct( private array &$db ) {}
|
||||
public function activeGoal(): ?array { return null; }
|
||||
public function raisedMinor( array $goal ): int { return 0; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); }
|
||||
public function bonusesFor( array $ids ): array { return array_fill_keys( $ids, array( 'big_donation' ) ); }
|
||||
private function ok(): array {
|
||||
$r = array_filter( $this->db, static fn( $d ) => 'completed' === $d['status'] && 'approved' === $d['moderation'] );
|
||||
usort( $r, static fn( $a, $b ) => $a['id'] <=> $b['id'] );
|
||||
return $r;
|
||||
}
|
||||
public function donations( ?int $sinceId, int $limit ): array {
|
||||
return array_slice( array_values( array_filter( $this->ok(), static fn( $d ) => $d['id'] > (int) $sinceId ) ), 0, $limit );
|
||||
}
|
||||
public function recentDonations( int $limit ): array { return array_slice( $this->ok(), -$limit ); }
|
||||
} );
|
||||
}
|
||||
|
||||
private function row( int $id, array $o = array() ): array {
|
||||
return $o + array( 'id' => $id, 'base_minor' => 500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0,
|
||||
'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
|
||||
}
|
||||
|
||||
public function test_recent_returns_approved_ascending_masked_with_bonuses(): void {
|
||||
$db = array( $this->row( 3 ), $this->row( 1, array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ),
|
||||
$this->row( 2, array( 'moderation' => 'pending' ) ), $this->row( 4, array( 'moderation' => 'rejected' ) ) );
|
||||
$out = $this->svc( $db )->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( array( 1, 3 ), array_column( $out['alerts'], 'id' ) );
|
||||
$this->assertSame( 3, $out['last_id'] );
|
||||
$this->assertSame( 'Anonymous', $out['alerts'][0]['name'] );
|
||||
$this->assertStringNotContainsString( 'Secret', json_encode( $out ) );
|
||||
$this->assertSame( array( 'Big donation' ), $out['alerts'][1]['bonuses'] );
|
||||
}
|
||||
|
||||
public function test_recent_caps_at_newest_20(): void {
|
||||
$db = array();
|
||||
for ( $i = 1; $i <= 25; $i++ ) {
|
||||
$db[] = $this->row( $i );
|
||||
}
|
||||
$out = $this->svc( $db )->payload( 'alerts', 1, null, true );
|
||||
$this->assertCount( 20, $out['alerts'] );
|
||||
$this->assertSame( 6, $out['alerts'][0]['id'] );
|
||||
$this->assertSame( 25, $out['alerts'][19]['id'] );
|
||||
$this->assertCount( 20, Payloads::alerts( $db, null, 20, true )['alerts'] );
|
||||
}
|
||||
|
||||
public function test_late_approval_appears_in_recent_but_not_since(): void {
|
||||
$db = array( $this->row( 1 ), $this->row( 2, array( 'moderation' => 'pending' ) ), $this->row( 3 ) );
|
||||
$svc = $this->svc( $db );
|
||||
$first = $svc->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( array( 1, 3 ), array_column( $first['alerts'], 'id' ) );
|
||||
$db[1]['moderation'] = 'approved';
|
||||
$this->assertSame( array(), $svc->payload( 'alerts', 1, $first['last_id'] )['alerts'] ); // old cursor misses it
|
||||
$next = $svc->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( array( 1, 2, 3 ), array_column( $next['alerts'], 'id' ) );
|
||||
}
|
||||
|
||||
public function test_recent_etag_stable_then_changes(): void {
|
||||
$db = array( $this->row( 1 ), $this->row( 2, array( 'moderation' => 'pending' ) ) );
|
||||
$s = $this->svc( $db );
|
||||
$a = Payloads::etag( $s->payload( 'alerts', 1, null, true ) );
|
||||
$this->assertSame( $a, Payloads::etag( $s->payload( 'alerts', 99, null, true ) ) );
|
||||
$db[1]['moderation'] = 'approved';
|
||||
$this->assertNotSame( $a, Payloads::etag( $s->payload( 'alerts', 1, null, true ) ) );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user