Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b0b5012698 | ||
|
|
c62ac06b27 | ||
|
|
11ac72b23b | ||
|
|
f7ff1dc717 | ||
|
|
875ca42054 | ||
|
|
c7f2dcffeb | ||
|
|
1e2ca96eed | ||
|
|
4cec93067c | ||
|
|
27646c1001 | ||
|
|
3bbd77b661 | ||
|
|
e4d9042aba | ||
|
|
4f92cfdade | ||
|
|
fa4feddd35 |
No files matched your search
@@ -55,6 +55,13 @@ with the Live credentials and switch the mode to Live in Settings.
|
||||
- **Refunds and chargebacks are not tracked.** If you refund someone in PayPal, goal totals, timers and
|
||||
counters are not adjusted.
|
||||
|
||||
## Updates
|
||||
New versions appear in WordPress automatically (Dashboard > Updates and the Plugins screen), checked against
|
||||
this repository's releases. The repository is public, so no token is needed. (If you run a private fork, paste an
|
||||
access token with read access to releases in StreamGoals > Settings > Advanced > Plugin updates.) You can switch
|
||||
automatic updates on or off for this plugin on the Plugins screen, and use "Check for updates now" in
|
||||
StreamGoals > Settings > Advanced to look straight away.
|
||||
|
||||
## Development
|
||||
```
|
||||
composer install
|
||||
|
||||
@@ -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();
|
||||
}() );
|
||||
@@ -42,7 +42,8 @@
|
||||
if ( ! c.unit_minor ) { return null; }
|
||||
var d = Math.floor( amount * c.seconds_per_unit / c.unit_minor );
|
||||
if ( c.cap_seconds_per_donation != null ) { d = Math.min( d, c.cap_seconds_per_donation ); }
|
||||
return d > 0 ? 'Timer: +' + duration( d ) : 'Timer: no time added';
|
||||
var note = c.max_timer_seconds != null ? ' (the timer never goes above ' + duration( c.max_timer_seconds ) + ')' : '';
|
||||
return ( d > 0 ? 'Timer: +' + duration( d ) : 'Timer: no time added' ) + note;
|
||||
}
|
||||
if ( rule.type === 'counter' ) {
|
||||
if ( ! c.per_minor ) { return null; }
|
||||
@@ -74,6 +75,7 @@
|
||||
|
||||
/* Type switch + preview of the rule being edited. */
|
||||
if ( ! form ) { return; }
|
||||
|
||||
var typeSel = document.getElementById( 'sg-rule-type' );
|
||||
var typeHidden = form.querySelector( 'input[name="type"]' );
|
||||
var formPrev = document.getElementById( 'sg-form-preview' );
|
||||
@@ -93,7 +95,8 @@
|
||||
var n = parseInt( val( g, 'time_amount' ), 10 );
|
||||
if ( ! unit || ! n ) { return null; }
|
||||
var cap = parseInt( val( g, 'cap_minutes' ), 10 );
|
||||
return { type: type, config: { seconds_per_unit: n * mult, unit_minor: unit, cap_seconds_per_donation: cap > 0 ? cap * 60 : null } };
|
||||
var clock = parseInt( val( g, 'max_timer_minutes' ), 10 );
|
||||
return { type: type, config: { seconds_per_unit: n * mult, unit_minor: unit, cap_seconds_per_donation: cap > 0 ? cap * 60 : null, max_timer_seconds: clock > 0 ? clock * 60 : null } };
|
||||
}
|
||||
if ( type === 'counter' ) {
|
||||
var step = parseInt( val( g, 'step' ), 10 );
|
||||
|
||||
@@ -17,3 +17,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}
|
||||
+38
-3
@@ -41,7 +41,8 @@
|
||||
var s = document.createElement('script');
|
||||
s.id = 'sg-paypal-sdk';
|
||||
s.src = 'https://www.paypal.com/sdk/js?client-id=' + encodeURIComponent(C.clientId) +
|
||||
'¤cy=' + encodeURIComponent(currency) + '&intent=capture&components=buttons';
|
||||
'¤cy=' + encodeURIComponent(currency) + '&intent=capture&components=buttons' +
|
||||
((C.disableFunding && C.disableFunding.length) ? '&disable-funding=' + encodeURIComponent(C.disableFunding.join(',')) : '');
|
||||
s.onload = function () { window.paypal ? resolve(window.paypal) : reject(new Error(T.sdkError)); };
|
||||
s.onerror = function () { reject(new Error(T.sdkError)); };
|
||||
document.head.appendChild(s);
|
||||
@@ -95,7 +96,8 @@
|
||||
var info = el('button', { type: 'button', 'class': 'sg-info', 'aria-label': T.coverInfoLabel || 'What does this mean?', 'aria-expanded': 'false', 'aria-controls': uid + '-tip', text: 'i' });
|
||||
var pinnedOpen = false;
|
||||
function showTip(open) { tip.hidden = !open; info.setAttribute('aria-expanded', String(open)); }
|
||||
info.addEventListener('click', function () { pinnedOpen = tip.hidden; showTip(pinnedOpen); });
|
||||
// Click toggles a "pinned" state independent of hover (a tap fires hover first, so reading tip.hidden would undo itself).
|
||||
info.addEventListener('click', function () { pinnedOpen = !pinnedOpen; showTip(pinnedOpen); });
|
||||
info.addEventListener('mouseenter', function () { showTip(true); });
|
||||
info.addEventListener('mouseleave', function () { if (!pinnedOpen) { showTip(false); } });
|
||||
info.addEventListener('blur', function () { pinnedOpen = false; showTip(false); });
|
||||
@@ -105,17 +107,42 @@
|
||||
tip
|
||||
]));
|
||||
root.appendChild(row([total]));
|
||||
root.appendChild(status); // messages sit above the PayPal buttons, next to the form fields
|
||||
root.appendChild(buttons);
|
||||
root.appendChild(status);
|
||||
|
||||
function say(text, cls) { status.textContent = text || ''; status.className = 'sg-msg' + (cls ? ' ' + cls : ''); }
|
||||
function amountStr() { return amount.value.trim().replace(',', '.'); }
|
||||
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(); });
|
||||
@@ -123,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));
|
||||
|
||||
@@ -27,7 +27,23 @@ body.sg-offline #sg-root{opacity:.6}
|
||||
.sg-alert-head{font-weight:800;font-size:1.2em}
|
||||
.sg-alert-head b{color:var(--sg-accent2)}
|
||||
.sg-alert-msg{margin-top:.3em;font-size:.85em;overflow-wrap:anywhere;max-height:5.2em;overflow:hidden}
|
||||
.sg-alert.sg-bonus{border-width:.14em;animation:sg-in .6s cubic-bezier(.22,1,.36,1) both,sg-glow 1.4s ease-in-out .6s infinite}
|
||||
.sg-alert.sg-bonus.sg-out{animation:sg-out .5s ease-in both}
|
||||
.sg-bonus-line{margin-top:.3em;display:inline-block;padding:.1em .6em;border-radius:999px;font-weight:900;font-size:.95em;letter-spacing:.06em;text-transform:uppercase;color:#fff;background:linear-gradient(90deg,var(--sg-accent),var(--sg-accent2));text-shadow:0 1px 3px rgba(0,0,0,.6);box-shadow:0 0 0 .08em rgba(0,0,0,.45)}
|
||||
.sg-bonus-line+.sg-bonus-line{margin-left:.4em}
|
||||
@keyframes sg-glow{0%,100%{box-shadow:0 0 .4em var(--sg-accent),0 0 .9em var(--sg-accent2)}50%{box-shadow:0 0 .9em var(--sg-accent),0 0 1.9em var(--sg-accent2)}}
|
||||
@keyframes sg-in{from{opacity:0;transform:translateY(40%) scale(.9)}to{opacity:1;transform:none}}
|
||||
@keyframes sg-out{to{opacity:0;transform:translateY(-30%) scale(.95)}}
|
||||
@keyframes sg-blink{50%{opacity:.4}}
|
||||
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out{animation:none}}
|
||||
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out,.sg-alert.sg-bonus,.sg-alert.sg-bonus.sg-out{animation:none}.sg-alert.sg-bonus{box-shadow:0 0 .8em var(--sg-accent2)}}
|
||||
.sg-w-actions #sg-root{align-items:flex-start}
|
||||
.sg-w-actions #sg-root:empty{display:none}
|
||||
.sg-menu{height:100%;display:flex;flex-direction:column;overflow:hidden}
|
||||
.sg-menu-view{flex:1;min-height:0;overflow:hidden}
|
||||
.sg-menu-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() {
|
||||
@@ -108,6 +124,19 @@
|
||||
head.appendChild(document.createTextNode(' donated '));
|
||||
head.appendChild(el('b', null, a.amount_display));
|
||||
card.appendChild(head);
|
||||
var bonuses = Array.isArray(a.bonuses) ? a.bonuses : [];
|
||||
if (bonuses.length) {
|
||||
card.classList.add('sg-bonus');
|
||||
for (var j = 0; j < bonuses.length; j++) {
|
||||
card.appendChild(el('div', 'sg-bonus-line', 'BONUS: ' + String(bonuses[j]) + '!'));
|
||||
}
|
||||
}
|
||||
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 () {
|
||||
@@ -116,10 +145,48 @@
|
||||
}, 6500);
|
||||
}
|
||||
|
||||
// ---- actions (reward menu) ----
|
||||
// Renders nothing visible when there are no actions. Long lists scroll gently via CSS (--sg-rows sets the duration).
|
||||
var actionsSig = null;
|
||||
function renderActions(d) {
|
||||
var list = Array.isArray(d.actions) ? d.actions : [];
|
||||
var sig = JSON.stringify(list);
|
||||
if (sig === actionsSig) return;
|
||||
actionsSig = sig;
|
||||
root.textContent = '';
|
||||
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);
|
||||
// Overflow check after layout: duplicate the list for a seamless loop and start the CSS scroll.
|
||||
requestAnimationFrame(function () {
|
||||
if (ul.scrollHeight > view.clientHeight + 2) {
|
||||
var dup = ul.cloneNode(true);
|
||||
dup.setAttribute('aria-hidden', 'true');
|
||||
track.appendChild(dup);
|
||||
track.style.setProperty('--sg-scroll-s', Math.max(8, list.length * 3) + 's');
|
||||
track.classList.add('sg-scrolling');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- 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() {
|
||||
@@ -156,6 +223,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();
|
||||
|
||||
+21
-2
@@ -37,9 +37,9 @@ Rules engine entry point (Agent 2 implements, Agent 1 calls after a capture is r
|
||||
Rules\Engine::applyDonation(Donation $d): void; // idempotent via sg_rule_events UNIQUE
|
||||
Rules\Engine::reverseDonation(Donation $d): void; // honors per-rule "reverse on refund"
|
||||
```
|
||||
Rule `config` examples:
|
||||
Rule `config` examples (`max_total_seconds` caps what one rule has added over time; `max_timer_seconds` caps how long the timer can ever get, null = uncapped):
|
||||
```json
|
||||
{"type":"add_time","seconds_per_unit":60,"unit_minor":100,"cap_seconds_per_donation":null,"max_total_seconds":null,"basis":"base"}
|
||||
{"type":"add_time","seconds_per_unit":60,"unit_minor":100,"cap_seconds_per_donation":null,"max_total_seconds":null,"max_timer_seconds":null,"basis":"base"}
|
||||
{"type":"counter","step":1,"per_minor":1000,"carry_over":true,"basis":"base","label":"Pies"}
|
||||
{"type":"bonus","min_minor":5000,"event":"big_donation"}
|
||||
```
|
||||
@@ -54,3 +54,22 @@ 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().
|
||||
@@ -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 );
|
||||
}
|
||||
|
||||
@@ -197,7 +197,13 @@ final class GoalsPage {
|
||||
foreach ( $rules as $r ) {
|
||||
$rid = (int) $r['id'];
|
||||
echo '<tr class="' . ( $r['enabled'] ? '' : 'sg-off' ) . '"><td>' . esc_html( RuleConfig::TYPES[ $r['type'] ] ?? (string) $r['type'] ) . ( $r['enabled'] ? '' : ' <em>(off)</em>' ) . '</td>';
|
||||
echo '<td>' . esc_html( RuleConfig::summary( (string) $r['type'], $r['config'], $cur ) ) . '</td><td class="sg-actions">';
|
||||
try {
|
||||
$summary = RuleConfig::summary( (string) $r['type'], $r['config'], $cur );
|
||||
} catch ( \Throwable $e ) {
|
||||
// One unreadable rule must not take down the whole screen; say what is wrong so it can be fixed or deleted.
|
||||
$summary = 'Could not read this rule (' . $e->getMessage() . '). You can delete it and add it again.';
|
||||
}
|
||||
echo '<td>' . esc_html( $summary ) . '</td><td class="sg-actions">';
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId, 'rule' => $rid ) ) ) . '#sg-rule-form">Edit</a> ';
|
||||
Admin::form( 'sg_rule_toggle', array( 'goal_id' => $goalId, 'rule_id' => $rid, 'enabled' => $r['enabled'] ? 0 : 1 ), 'sg-inline' );
|
||||
echo '<button class="button">' . ( $r['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
|
||||
@@ -249,9 +255,10 @@ final class GoalsPage {
|
||||
echo '<option value="' . esc_attr( $u ) . '"' . selected( 'add_time' === $type ? ( $vals['time_unit'] ?? 'minutes' ) : 'minutes', $u, false ) . '>' . esc_html( $u ) . '</option>';
|
||||
}
|
||||
echo '</select> to the timer for every ' . esc_html( $cur ) . ' <input type="text" inputmode="decimal" name="rule[add_time][unit_amount]" class="small-text" data-f="unit_amount" value="' . $v( 'add_time', 'unit_amount', 0 === Money::exponent( $cur ) ? '100' : '1.00' ) . '"> donated.</p>';
|
||||
echo '<details' . ( ( 'add_time' === $type && ( ( $vals['cap_minutes'] ?? '' ) !== '' || ( $vals['max_total_minutes'] ?? '' ) !== '' ) ) ? ' open' : '' ) . '><summary>Limits (optional)</summary>';
|
||||
echo '<details' . ( ( 'add_time' === $type && ( ( $vals['cap_minutes'] ?? '' ) !== '' || ( $vals['max_total_minutes'] ?? '' ) !== '' || ( $vals['max_timer_minutes'] ?? '' ) !== '' ) ) ? ' open' : '' ) . '><summary>Limits (optional)</summary>';
|
||||
echo '<p><label>Most minutes one donation can add <input type="number" min="1" class="small-text" name="rule[add_time][cap_minutes]" data-f="cap_minutes" value="' . $v( 'add_time', 'cap_minutes' ) . '"></label></p>';
|
||||
echo '<p><label>Most minutes this rule can add in total <input type="number" min="1" class="small-text" name="rule[add_time][max_total_minutes]" data-f="max_total_minutes" value="' . $v( 'add_time', 'max_total_minutes' ) . '"></label></p>';
|
||||
echo '<p><label>Longest the timer can ever get (minutes) <input type="number" min="1" class="small-text" name="rule[add_time][max_timer_minutes]" data-f="max_timer_minutes" value="' . $v( 'add_time', 'max_timer_minutes' ) . '"></label> <span class="description">Leave empty for no limit. For example, 1440 means the clock never shows more than 24 hours.</span></p>';
|
||||
echo '<p><label>Count ' . $basisOpts( 'add_time' ) . '</label></p></details></div>'; // phpcs:ignore WordPress.Security.EscapeOutput -- built from escaped parts
|
||||
// counter
|
||||
echo '<div class="sg-rule-group" data-type="counter"' . ( 'counter' === $type ? '' : ' hidden' ) . '><p>Add <input type="number" min="1" class="small-text" name="rule[counter][step]" data-f="step" value="' . $v( 'counter', 'step', '1' ) . '"> to the counter for every ' . esc_html( $cur ) . ' <input type="text" inputmode="decimal" class="small-text" name="rule[counter][unit_amount]" data-f="unit_amount" value="' . $v( 'counter', 'unit_amount', 0 === Money::exponent( $cur ) ? '1000' : '10.00' ) . '"> donated.</p>';
|
||||
|
||||
@@ -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} */
|
||||
|
||||
@@ -46,6 +46,7 @@ final class RuleConfig {
|
||||
}
|
||||
$cap = self::optionalMinutes( $in['cap_minutes'] ?? '', 'The per-donation limit', $errors );
|
||||
$max = self::optionalMinutes( $in['max_total_minutes'] ?? '', 'The total limit', $errors );
|
||||
$clk = self::optionalMinutes( $in['max_timer_minutes'] ?? '', 'The longest the timer can get', $errors );
|
||||
if ( $errors ) {
|
||||
return array( 'config' => null, 'errors' => $errors );
|
||||
}
|
||||
@@ -59,6 +60,7 @@ final class RuleConfig {
|
||||
'unit_minor' => $unit,
|
||||
'cap_seconds_per_donation' => $cap,
|
||||
'max_total_seconds' => $max,
|
||||
'max_timer_seconds' => $clk,
|
||||
'basis' => $basis,
|
||||
),
|
||||
'errors' => array(),
|
||||
@@ -128,6 +130,9 @@ final class RuleConfig {
|
||||
if ( isset( $c['max_total_seconds'] ) ) {
|
||||
$s .= ', ' . Format::duration( (int) $c['max_total_seconds'] ) . ' in total';
|
||||
}
|
||||
if ( isset( $c['max_timer_seconds'] ) ) {
|
||||
$s .= ', up to ' . Format::duration( (int) $c['max_timer_seconds'] ) . ' on the clock';
|
||||
}
|
||||
return $s;
|
||||
case 'counter':
|
||||
$label = (string) ( $c['label'] ?? '' );
|
||||
@@ -158,6 +163,9 @@ final class RuleConfig {
|
||||
if ( 'add_time' === $type ) {
|
||||
$res = AddTimeRule::fromConfig( $cfg )->apply( $d, 0, 0, 0 );
|
||||
$lines[] = $res['delta'] > 0 ? 'Timer: +' . Format::duration( $res['delta'] ) : 'Timer: no time added';
|
||||
if ( isset( $cfg['max_timer_seconds'] ) ) {
|
||||
$lines[ count( $lines ) - 1 ] .= ' (the timer never goes above ' . Format::duration( (int) $cfg['max_timer_seconds'] ) . ')';
|
||||
}
|
||||
} elseif ( 'counter' === $type ) {
|
||||
$res = CounterRule::fromConfig( $cfg )->apply( $d, 0, 0 );
|
||||
$lbl = (string) ( $cfg['label'] ?? '' );
|
||||
@@ -182,6 +190,7 @@ final class RuleConfig {
|
||||
$f['unit_amount'] = Format::decimal( (int) ( $c['unit_minor'] ?? 100 ), $currency );
|
||||
$f['cap_minutes'] = isset( $c['cap_seconds_per_donation'] ) ? (string) intdiv( (int) $c['cap_seconds_per_donation'], 60 ) : '';
|
||||
$f['max_total_minutes'] = isset( $c['max_total_seconds'] ) ? (string) intdiv( (int) $c['max_total_seconds'], 60 ) : '';
|
||||
$f['max_timer_minutes'] = isset( $c['max_timer_seconds'] ) ? (string) intdiv( (int) $c['max_timer_seconds'], 60 ) : '';
|
||||
} elseif ( 'counter' === $type ) {
|
||||
$f['step'] = (int) ( $c['step'] ?? 1 );
|
||||
$f['unit_amount'] = Format::decimal( (int) ( $c['per_minor'] ?? 1000 ), $currency );
|
||||
|
||||
@@ -47,14 +47,54 @@ final class SettingsPage {
|
||||
echo '<label><input type="checkbox" name="profanity_use_builtin" value="1"' . checked( ! empty( $s['profanity_use_builtin'] ), true, false ) . '> Use the built-in word list</label>';
|
||||
echo '<p><label for="sg_words">Your own words to block (one per line)</label><br><textarea id="sg_words" name="profanity_words" rows="6" class="large-text code">' . esc_textarea( (string) $s['profanity_words'] ) . '</textarea></p></td></tr></table></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Checkout buttons</h2><table class="form-table" role="presentation"><tr><th scope="row">Payment options</th><td>';
|
||||
echo '<label><input type="checkbox" name="funding_card" value="1"' . checked( ! empty( $s['funding_card'] ), true, false ) . '> Show "Debit or Credit Card" (donors without a PayPal account)</label><br>';
|
||||
echo '<label><input type="checkbox" name="funding_paylater" value="1"' . checked( ! empty( $s['funding_paylater'] ), true, false ) . '> Show "Pay Later" (donors pay in instalments; you are still paid in full)</label>';
|
||||
echo '<p class="description">The PayPal button is always shown. Which extra buttons appear can also depend on the donor\'s country.</p></td></tr></table></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Advanced</h2><table class="form-table" role="presentation"><tr><th scope="row"><label for="sg_ip">Visitor IP address</label></th><td><select id="sg_ip" name="visitor_ip_header">';
|
||||
foreach ( \StreamGoals\Core\ClientIp::MODES as $k => $l ) {
|
||||
echo '<option value="' . esc_attr( $k ) . '"' . selected( (string) $s['visitor_ip_header'], $k, false ) . '>' . esc_html( $l ) . '</option>';
|
||||
}
|
||||
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). If your site is behind Cloudflare or another proxy, choose it here so each visitor is counted separately; otherwise everyone looks like the same visitor and a busy moment, like a raid, could block donations. Only choose a proxy option if <em>all</em> traffic to your site really goes through it.</p>';
|
||||
self::ipDiagnostics( (string) $s['visitor_ip_header'] );
|
||||
echo '</td></tr></table></div>';
|
||||
|
||||
$rel = \StreamGoals\Update\Updater::latest();
|
||||
echo '<div class="sg-card"><h2>Plugin updates</h2><table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row">Installed version</th><td><code>' . esc_html( STREAMGOALS_VERSION ) . '</code></td></tr>';
|
||||
echo '<tr><th scope="row">Latest release</th><td>' . ( $rel ? '<code>' . esc_html( $rel['version'] ) . '</code>' . ( \StreamGoals\Update\ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ? ' (update available)' : ' (up to date)' ) : 'Not found yet (or the check failed).' ) . ' <button type="submit" form="sg_update_check_form" class="button">Check for updates now</button></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_utoken">Access token (only needed while the update repository is private)</label></th><td><input type="password" id="sg_utoken" name="update_token" class="regular-text code" autocomplete="new-password" spellcheck="false" value="" placeholder="' . esc_attr( '' !== (string) $s['update_token'] ? Input::maskSecret( (string) $s['update_token'] ) : 'Paste a read-only token' ) . '">';
|
||||
echo '<p class="description">' . ( '' !== (string) $s['update_token'] ? 'A token is saved. Leave this empty to keep it, or paste a new one to replace it.' : 'Not needed once the repository is public.' ) . '</p></td></tr></table></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>PayPal fee estimate</h2>';
|
||||
echo '<p>When a donor chooses "cover the fees", the form adds the estimated PayPal fee so you receive the amount they intended. The defaults (<strong>3.49% + $0.49</strong>) are <strong>US domestic estimates</strong>. Fees for international (cross-border) payments and currency conversion are higher and are <strong>not</strong> included, so you may receive slightly less than expected in those cases. Check PayPal\'s current fee page for your country and adjust.</p>';
|
||||
echo '<table class="form-table" role="presentation"><tr><th scope="row"><label for="sg_pct">Percentage fee</label></th><td><input type="text" id="sg_pct" name="fee_percent" class="small-text" inputmode="decimal" value="' . esc_attr( number_format( (int) $s['fee_percent_bps'] / 100, 2, '.', '' ) ) . '"> %</td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_fix">Fixed fee (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_fix" name="fee_fixed" class="small-text" inputmode="decimal" value="' . esc_attr( Format::decimal( (int) $s['fee_fixed_minor'], $cur ) ) . '"></td></tr></table></div>';
|
||||
echo '<p><button class="button button-primary button-hero">Save settings</button></p></form>';
|
||||
echo '<form id="sg_update_check_form" method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '"><input type="hidden" name="action" value="' . esc_attr( \StreamGoals\Update\Updater::ACTION_CHECK ) . '">';
|
||||
wp_nonce_field( \StreamGoals\Update\Updater::ACTION_CHECK );
|
||||
echo '</form>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
/** Shows the owner what their server passes to the plugin right now, to help pick the right option. */
|
||||
private static function ipDiagnostics( string $mode ): void {
|
||||
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
|
||||
$server = array();
|
||||
foreach ( $keys as $k => $_ ) {
|
||||
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
|
||||
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
|
||||
}
|
||||
}
|
||||
echo '<details class="sg-ipdiag"><summary>What does my server see right now?</summary><table class="widefat striped" style="max-width:36rem"><tbody>';
|
||||
foreach ( $keys as $k => $label ) {
|
||||
echo '<tr><td>' . esc_html( $label ) . '</td><td><code>' . ( isset( $server[ $k ] ) ? esc_html( $server[ $k ] ) : '(not sent)' ) . '</code></td></tr>';
|
||||
}
|
||||
echo '<tr><td><strong>Visitor address used with the saved option</strong></td><td><code>' . esc_html( \StreamGoals\Core\ClientIp::resolve( $server, $mode ) ) . '</code></td></tr>';
|
||||
echo '</tbody></table><p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
|
||||
}
|
||||
|
||||
public static function handleSave(): void {
|
||||
Admin::guard( 'sg_settings_save' );
|
||||
$post = Admin::post_raw();
|
||||
@@ -93,6 +133,18 @@ final class SettingsPage {
|
||||
} else {
|
||||
$upd['anonymity_policy'] = $pol;
|
||||
}
|
||||
$ipMode = isset( $post['visitor_ip_header'] ) && is_string( $post['visitor_ip_header'] ) ? $post['visitor_ip_header'] : '';
|
||||
if ( ! array_key_exists( $ipMode, \StreamGoals\Core\ClientIp::MODES ) ) {
|
||||
$errors[] = 'Please choose a visitor IP option.';
|
||||
} else {
|
||||
$upd['visitor_ip_header'] = $ipMode;
|
||||
}
|
||||
$tok = $post['update_token'] ?? '';
|
||||
if ( ! Input::secretUnchanged( is_string( $tok ) ? $tok : '' ) ) {
|
||||
$upd['update_token'] = Input::text( $tok, 300 );
|
||||
}
|
||||
$upd['funding_card'] = ! empty( $post['funding_card'] );
|
||||
$upd['funding_paylater'] = ! empty( $post['funding_paylater'] );
|
||||
$upd['moderate_messages'] = ! empty( $post['moderate_messages'] );
|
||||
$upd['profanity_filter'] = ! empty( $post['profanity_filter'] );
|
||||
$upd['profanity_use_builtin'] = ! empty( $post['profanity_use_builtin'] );
|
||||
|
||||
@@ -26,11 +26,14 @@ final class Store {
|
||||
public static function rules( int $goalId ): array {
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'rules' ) . ' WHERE goal_id = %d ORDER BY sort ASC, id ASC', $goalId ), ARRAY_A );
|
||||
foreach ( (array) $rows as &$r ) {
|
||||
$rows = (array) $rows;
|
||||
// Iterate $rows itself by reference: `foreach ( (array) $rows as &$r )` would modify a temporary copy and discard the decoding.
|
||||
foreach ( $rows as &$r ) {
|
||||
$cfg = json_decode( (string) $r['config'], true );
|
||||
$r['config'] = is_array( $cfg ) ? $cfg : array();
|
||||
}
|
||||
return (array) $rows;
|
||||
unset( $r );
|
||||
return $rows;
|
||||
}
|
||||
|
||||
public static function rule( int $ruleId, int $goalId ): ?array {
|
||||
@@ -134,7 +137,7 @@ final class Store {
|
||||
global $wpdb;
|
||||
return (array) $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id > %d AND paypal_order_id NOT LIKE %s AND goal_id > 0 ORDER BY id ASC LIMIT %d',
|
||||
'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id > %d AND status = \'completed\' AND paypal_order_id NOT LIKE %s AND goal_id > 0 ORDER BY id ASC LIMIT %d',
|
||||
$afterId,
|
||||
$wpdb->esc_like( Format::TEST_PREFIX ) . '%',
|
||||
$limit
|
||||
|
||||
@@ -28,7 +28,7 @@ final class Templates {
|
||||
$rules = array();
|
||||
if ( 'subathon' === $key ) {
|
||||
$rules[] = array( 'type' => 'add_time', 'config' => array(
|
||||
'seconds_per_unit' => 60, 'unit_minor' => $one, 'cap_seconds_per_donation' => null, 'max_total_seconds' => null, 'basis' => 'base',
|
||||
'seconds_per_unit' => 60, 'unit_minor' => $one, 'cap_seconds_per_donation' => null, 'max_total_seconds' => null, 'max_timer_seconds' => null, 'basis' => 'base',
|
||||
) );
|
||||
} elseif ( 'counter' === $key ) {
|
||||
$rules[] = array( 'type' => 'counter', 'config' => array(
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/**
|
||||
* Works out the visitor's IP for rate limiting. Pure (takes the $_SERVER values as an array) so it is unit-testable.
|
||||
*
|
||||
* Behind a CDN or reverse proxy, PHP's REMOTE_ADDR is the proxy's address, so every visitor would share one rate
|
||||
* limit. The owner can name the header their proxy sets. A header is ONLY trusted when the owner selected it, and
|
||||
* only if it holds a valid IP address; otherwise we fall back to REMOTE_ADDR.
|
||||
*/
|
||||
final class ClientIp {
|
||||
|
||||
public const MODE_DIRECT = ''; // no proxy: use REMOTE_ADDR
|
||||
public const MODE_CLOUDFLARE = 'cloudflare'; // CF-Connecting-IP
|
||||
public const MODE_REAL_IP = 'real_ip'; // X-Real-IP (nginx and many hosts)
|
||||
public const MODE_FORWARDED = 'forwarded'; // last address in X-Forwarded-For (exactly one proxy in front)
|
||||
|
||||
public const MODES = array(
|
||||
self::MODE_DIRECT => 'Not behind a proxy or CDN (most sites)',
|
||||
self::MODE_CLOUDFLARE => 'Cloudflare (CF-Connecting-IP)',
|
||||
self::MODE_REAL_IP => 'X-Real-IP header',
|
||||
self::MODE_FORWARDED => 'X-Forwarded-For header (one proxy in front)',
|
||||
);
|
||||
|
||||
/** @param array<string,mixed> $server $_SERVER-style values (already unslashed). */
|
||||
public static function resolve( array $server, string $mode = self::MODE_DIRECT ): string {
|
||||
$remote = self::valid( $server['REMOTE_ADDR'] ?? null );
|
||||
$fromHeader = null;
|
||||
switch ( $mode ) {
|
||||
case self::MODE_CLOUDFLARE:
|
||||
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
|
||||
break;
|
||||
case self::MODE_REAL_IP:
|
||||
$fromHeader = self::valid( $server['HTTP_X_REAL_IP'] ?? null );
|
||||
break;
|
||||
case self::MODE_FORWARDED:
|
||||
$raw = $server['HTTP_X_FORWARDED_FOR'] ?? null;
|
||||
if ( is_string( $raw ) && '' !== trim( $raw ) ) {
|
||||
$parts = array_map( 'trim', explode( ',', $raw ) );
|
||||
$fromHeader = self::valid( end( $parts ) ); // the entry our proxy appended; earlier ones are client-supplied
|
||||
}
|
||||
break;
|
||||
}
|
||||
return $fromHeader ?? $remote ?? 'unknown';
|
||||
}
|
||||
|
||||
private static function valid( mixed $v ): ?string {
|
||||
if ( ! is_string( $v ) ) {
|
||||
return null;
|
||||
}
|
||||
$v = trim( $v );
|
||||
return false !== filter_var( $v, FILTER_VALIDATE_IP ) ? $v : null;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class Installer {
|
||||
|
||||
public const DB_VERSION = '1';
|
||||
public const DB_VERSION = '2';
|
||||
|
||||
public static function activate(): void {
|
||||
self::install_schema();
|
||||
@@ -94,6 +94,34 @@ 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;" );
|
||||
|
||||
update_option( 'sg_db_version', self::DB_VERSION );
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,7 @@ final class Plugin {
|
||||
\StreamGoals\Rest\WebhookController::class,
|
||||
\StreamGoals\Rest\OverlayController::class,
|
||||
\StreamGoals\Admin\Admin::class,
|
||||
\StreamGoals\Update\Updater::class,
|
||||
);
|
||||
|
||||
public static function boot(): void {
|
||||
|
||||
@@ -35,6 +35,10 @@ final class Settings {
|
||||
'message_max_length' => 200,
|
||||
'min_donation_minor' => 100,
|
||||
'overlay_token' => '',
|
||||
'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp)
|
||||
'funding_paylater' => false, // show PayPal "Pay Later" button
|
||||
'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;
|
||||
}
|
||||
@@ -28,4 +28,13 @@ interface OverlayDataSource {
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function donations( ?int $sinceId, int $limit ): array;
|
||||
|
||||
/**
|
||||
* Bonus event names that fired (and were not reversed) per donation, in firing order. One lookup
|
||||
* for the whole page. Raw stored strings; Payloads sanitizes them. Donations without bonuses may be omitted.
|
||||
*
|
||||
* @param int[] $donationIds
|
||||
* @return array<int,string[]> donation id => event names
|
||||
*/
|
||||
public function bonusesFor( array $donationIds ): array;
|
||||
}
|
||||
@@ -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,7 +26,27 @@ final class OverlayService {
|
||||
$c = $gid ? $this->source->counter( $gid ) : array( 'label' => '', 'value' => 0 );
|
||||
return Payloads::counter( $c['label'], $c['value'] );
|
||||
case 'alerts':
|
||||
return Payloads::alerts( $this->source->donations( $since, 20 ), $since );
|
||||
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 = ( ( $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, $recent ? 20 : 10, $recent );
|
||||
case 'actions':
|
||||
$rows = ( $gid && $this->source instanceof ActionsSource ) ? $this->source->menuActions( $gid ) : array();
|
||||
return Payloads::actionsMenu( $goal, $rows );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
+120
-13
@@ -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,17 +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'] ?? '' ),
|
||||
);
|
||||
$alerts[] = self::alert( $r );
|
||||
}
|
||||
$alerts = array_slice( $alerts, 0, max( 1, $limit ) );
|
||||
if ( $alerts ) {
|
||||
@@ -116,6 +113,116 @@ 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.
|
||||
*
|
||||
* @param mixed $events
|
||||
* @return string[]
|
||||
*/
|
||||
public static function bonuses( mixed $events ): array {
|
||||
$out = array();
|
||||
foreach ( is_array( $events ) ? $events : array() as $e ) {
|
||||
if ( ! is_string( $e ) ) {
|
||||
continue;
|
||||
}
|
||||
$clean = substr( (string) preg_replace( '/[^A-Za-z0-9_-]/', '', $e ), 0, 40 );
|
||||
$label = trim( (string) preg_replace( '/[_-]+/', ' ', $clean ) );
|
||||
if ( '' === $label ) {
|
||||
continue;
|
||||
}
|
||||
$label = ucfirst( strtolower( $label ) );
|
||||
if ( ! in_array( $label, $out, true ) ) {
|
||||
$out[] = $label;
|
||||
}
|
||||
if ( count( $out ) >= 5 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** 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;
|
||||
@@ -62,6 +62,61 @@ final class WpdbDataSource implements OverlayDataSource {
|
||||
return array( 'label' => $label, 'value' => $total );
|
||||
}
|
||||
|
||||
public function bonusesFor( array $donationIds ): array {
|
||||
global $wpdb;
|
||||
$ids = array_values( array_unique( array_filter( array_map( 'intval', $donationIds ), static fn( $i ) => $i > 0 ) ) );
|
||||
if ( ! $ids ) {
|
||||
return array();
|
||||
}
|
||||
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT e.donation_id, r.config FROM {$this->t('rule_events')} e
|
||||
INNER JOIN {$this->t('rules')} r ON r.id = e.rule_id
|
||||
WHERE r.type = 'bonus' AND e.reversed = 0 AND e.delta > 0 AND e.donation_id IN ($in)
|
||||
ORDER BY e.id ASC",
|
||||
$ids
|
||||
), ARRAY_A );
|
||||
$out = array();
|
||||
foreach ( (array) $rows as $row ) {
|
||||
$cfg = json_decode( (string) $row['config'], true );
|
||||
$ev = is_array( $cfg ) && isset( $cfg['event'] ) && is_string( $cfg['event'] ) ? $cfg['event'] : '';
|
||||
if ( '' !== $ev ) {
|
||||
$out[ (int) $row['donation_id'] ][] = $ev;
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function 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';
|
||||
@@ -77,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,12 @@ 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
|
||||
}
|
||||
}
|
||||
|
||||
private static function call_engine( string $method, int $id ): void {
|
||||
|
||||
@@ -155,7 +155,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,6 +166,7 @@ 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 ) {
|
||||
@@ -179,6 +181,7 @@ final class DonateController {
|
||||
'policy' => (string) $s['anonymity_policy'],
|
||||
'minMinor' => \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ),
|
||||
'messageMax' => min( 500, (int) $s['message_max_length'] ),
|
||||
'disableFunding' => array_values( array_filter( array( empty( $s['funding_paylater'] ) ? 'paylater' : '', empty( $s['funding_card'] ) ? 'card' : '' ) ) ),
|
||||
'goals' => $goals,
|
||||
'i18n' => array(
|
||||
'goal' => __( 'Goal', 'streamgoals-donate' ),
|
||||
@@ -195,6 +198,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 */
|
||||
@@ -210,6 +216,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();
|
||||
@@ -231,7 +272,13 @@ final class DonateController {
|
||||
}
|
||||
|
||||
private static function limit( string $bucket, int $max, int $window ): ?\WP_Error {
|
||||
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown';
|
||||
$server = array();
|
||||
foreach ( array( 'REMOTE_ADDR', 'HTTP_CF_CONNECTING_IP', 'HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR' ) as $k ) {
|
||||
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
|
||||
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
|
||||
}
|
||||
}
|
||||
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', '' ) );
|
||||
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -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 ) );
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@ namespace StreamGoals\Rules;
|
||||
/**
|
||||
* Adds seconds to a goal timer. Proportional: seconds = floor(amount * seconds_per_unit / unit_minor).
|
||||
* cap_seconds_per_donation limits one donation; max_total_seconds limits the cumulative seconds
|
||||
* this rule may ever add (net of reversals). The timer is an absolute ends_at timestamp.
|
||||
* this rule may ever add (net of reversals). maxTimer caps the remaining time on the clock (ends_at - now);
|
||||
* null = uncapped. A timer already above the cap is never shortened, it just gets 0 added. The timer is an absolute ends_at timestamp.
|
||||
*/
|
||||
final class AddTimeRule {
|
||||
|
||||
@@ -15,9 +16,10 @@ final class AddTimeRule {
|
||||
public readonly int $unitMinor,
|
||||
public readonly ?int $capPerDonation = null,
|
||||
public readonly ?int $maxTotal = null,
|
||||
public readonly string $basis = 'base'
|
||||
public readonly string $basis = 'base',
|
||||
public readonly ?int $maxTimer = null
|
||||
) {
|
||||
if ( $unitMinor <= 0 || $secondsPerUnit < 0 ) {
|
||||
if ( $unitMinor <= 0 || $secondsPerUnit < 0 || ( null !== $maxTimer && $maxTimer < 1 ) ) {
|
||||
throw new \InvalidArgumentException( 'Invalid add_time config.' );
|
||||
}
|
||||
}
|
||||
@@ -28,7 +30,8 @@ final class AddTimeRule {
|
||||
(int) ( $c['unit_minor'] ?? 0 ),
|
||||
isset( $c['cap_seconds_per_donation'] ) ? (int) $c['cap_seconds_per_donation'] : null,
|
||||
isset( $c['max_total_seconds'] ) ? (int) $c['max_total_seconds'] : null,
|
||||
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base'
|
||||
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base',
|
||||
isset( $c['max_timer_seconds'] ) ? (int) $c['max_timer_seconds'] : null
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,14 +44,18 @@ final class AddTimeRule {
|
||||
if ( null !== $this->maxTotal ) {
|
||||
$delta = min( $delta, max( 0, $this->maxTotal - $addedTotal ) );
|
||||
}
|
||||
// Expired (or never started) timers restart from now.
|
||||
$start = max( $endsAt, $now );
|
||||
if ( null !== $this->maxTimer ) {
|
||||
$delta = min( $delta, max( 0, $this->maxTimer - ( $start - $now ) ) );
|
||||
}
|
||||
$delta = max( 0, $delta );
|
||||
if ( 0 === $delta ) {
|
||||
return array( 'delta' => 0, 'ends_at' => $endsAt, 'added_total' => $addedTotal );
|
||||
}
|
||||
// Expired (or never started) timers restart from now.
|
||||
return array(
|
||||
'delta' => $delta,
|
||||
'ends_at' => max( $endsAt, $now ) + $delta,
|
||||
'ends_at' => $start + $delta,
|
||||
'added_total' => $addedTotal + $delta,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,20 @@ final class Engine {
|
||||
|
||||
/** Production wiring: $wpdb-backed stores. */
|
||||
public static function default(): self {
|
||||
return new self( new WpRuleStore(), new WpEventStore(), new \StreamGoals\Core\StateStore() );
|
||||
$onBonus = static function ( string $event, RuleDef $rule, Donation $d, bool $reversed ): void {
|
||||
if ( function_exists( 'do_action' ) ) {
|
||||
/**
|
||||
* Fires when a big-donation bonus rule triggers (or is reversed by a refund).
|
||||
*
|
||||
* @param string $event Rule's event name.
|
||||
* @param int $donationId Donation id.
|
||||
* @param int $ruleId Rule id.
|
||||
* @param bool $reversed True when the bonus was undone.
|
||||
*/
|
||||
do_action( 'streamgoals_bonus', $event, $d->id, $rule->id, $reversed );
|
||||
}
|
||||
};
|
||||
return new self( new WpRuleStore(), new WpEventStore(), new \StreamGoals\Core\StateStore(), null, $onBonus );
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Update;
|
||||
|
||||
/**
|
||||
* Pure (WordPress-free) parsing of a Gitea release payload.
|
||||
*/
|
||||
final class ReleaseParser {
|
||||
|
||||
public const ASSET_NAME = 'streamgoals-donate.zip';
|
||||
|
||||
private const DATE_TAG = '/^\d{4}\.\d{2}\.\d{2}-\d{4}$/';
|
||||
private const SEMVER = '/^\d+\.\d+\.\d+$/';
|
||||
|
||||
/**
|
||||
* @param array $release Decoded Gitea release JSON.
|
||||
* @param string $host The only host a package URL may point to (e.g. repo.anhonesthost.net).
|
||||
* @return array{version:string,package:string,url:string,notes:string,published:string}|null
|
||||
*/
|
||||
public static function parse( array $release, string $host ): ?array {
|
||||
if ( ! empty( $release['draft'] ) || ! empty( $release['prerelease'] ) ) {
|
||||
return null;
|
||||
}
|
||||
$version = self::normalizeVersion( $release['tag_name'] ?? null );
|
||||
if ( null === $version ) {
|
||||
return null;
|
||||
}
|
||||
$assets = isset( $release['assets'] ) && is_array( $release['assets'] ) ? $release['assets'] : array();
|
||||
$package = self::pickPackage( $assets, $host );
|
||||
if ( null === $package ) {
|
||||
return null;
|
||||
}
|
||||
$url = $release['html_url'] ?? '';
|
||||
return array(
|
||||
'version' => $version,
|
||||
'package' => $package,
|
||||
'url' => is_string( $url ) && self::isAllowedUrl( $url, $host ) ? $url : '',
|
||||
'notes' => is_string( $release['body'] ?? null ) ? $release['body'] : '',
|
||||
'published' => is_string( $release['published_at'] ?? null ) ? $release['published_at'] : '',
|
||||
);
|
||||
}
|
||||
|
||||
public static function normalizeVersion( mixed $tag ): ?string {
|
||||
if ( ! is_string( $tag ) ) {
|
||||
return null;
|
||||
}
|
||||
$t = trim( $tag );
|
||||
if ( '' !== $t && ( 'v' === $t[0] || 'V' === $t[0] ) ) {
|
||||
$t = substr( $t, 1 );
|
||||
}
|
||||
return 1 === preg_match( self::DATE_TAG, $t ) || 1 === preg_match( self::SEMVER, $t ) ? $t : null;
|
||||
}
|
||||
|
||||
public static function isNewer( string $remote, string $current ): bool {
|
||||
$r = self::normalizeVersion( $remote );
|
||||
if ( null === $r ) {
|
||||
return false;
|
||||
}
|
||||
return version_compare( $r, ltrim( $current, 'vV' ), '>' );
|
||||
}
|
||||
|
||||
/** https URL on exactly the configured host (no userinfo tricks). */
|
||||
public static function isAllowedUrl( string $url, string $host ): bool {
|
||||
$p = parse_url( $url );
|
||||
if ( ! is_array( $p ) || ! isset( $p['scheme'], $p['host'] ) || isset( $p['user'] ) || isset( $p['pass'] ) ) {
|
||||
return false;
|
||||
}
|
||||
return 'https' === strtolower( $p['scheme'] ) && '' !== $host && strtolower( $p['host'] ) === strtolower( $host );
|
||||
}
|
||||
|
||||
private static function pickPackage( array $assets, string $host ): ?string {
|
||||
$exact = null;
|
||||
$first = null;
|
||||
foreach ( $assets as $a ) {
|
||||
if ( ! is_array( $a ) || ! is_string( $a['name'] ?? null ) || ! is_string( $a['browser_download_url'] ?? null ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( ! self::isAllowedUrl( $a['browser_download_url'], $host ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( self::ASSET_NAME === $a['name'] ) {
|
||||
$exact = $exact ?? $a['browser_download_url'];
|
||||
} elseif ( null === $first && str_ends_with( strtolower( $a['name'] ), '.zip' ) ) {
|
||||
$first = $a['browser_download_url'];
|
||||
}
|
||||
}
|
||||
return $exact ?? $first;
|
||||
}
|
||||
|
||||
/** Minimal markdown to safe HTML: everything is escaped first; only paragraphs, headings (as <h4>) and lists. */
|
||||
public static function changelogHtml( string $markdown ): string {
|
||||
$lines = preg_split( '/\r\n|\r|\n/', $markdown ) ?: array();
|
||||
$out = '';
|
||||
$list = false;
|
||||
$para = array();
|
||||
$flush = static function () use ( &$out, &$para ): void {
|
||||
if ( $para ) {
|
||||
$out .= '<p>' . implode( ' ', $para ) . '</p>';
|
||||
$para = array();
|
||||
}
|
||||
};
|
||||
foreach ( $lines as $line ) {
|
||||
$t = trim( $line );
|
||||
if ( 1 === preg_match( '/^[*\-+]\s+(.*)$/', $t, $m ) ) {
|
||||
$flush();
|
||||
if ( ! $list ) {
|
||||
$out .= '<ul>';
|
||||
$list = true;
|
||||
}
|
||||
$out .= '<li>' . self::esc( $m[1] ) . '</li>';
|
||||
continue;
|
||||
}
|
||||
if ( $list ) {
|
||||
$out .= '</ul>';
|
||||
$list = false;
|
||||
}
|
||||
if ( '' === $t ) {
|
||||
$flush();
|
||||
} elseif ( 1 === preg_match( '/^#{1,6}\s+(.*)$/', $t, $m ) ) {
|
||||
$flush();
|
||||
$out .= '<h4>' . self::esc( $m[1] ) . '</h4>';
|
||||
} else {
|
||||
$para[] = self::esc( $t );
|
||||
}
|
||||
}
|
||||
$flush();
|
||||
if ( $list ) {
|
||||
$out .= '</ul>';
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function esc( string $s ): string {
|
||||
return htmlspecialchars( $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Update;
|
||||
|
||||
use StreamGoals\Admin\Admin;
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/**
|
||||
* Self-updater: checks the Gitea repo's latest release and feeds WordPress' plugin update machinery.
|
||||
* Every network/parse failure degrades to "no update known"; nothing here throws into WP screens.
|
||||
*/
|
||||
final class Updater {
|
||||
|
||||
public const SLUG = 'streamgoals-donate';
|
||||
public const BASE_URL = 'https://repo.anhonesthost.net';
|
||||
public const OWNER = 'wp-plugins';
|
||||
public const REPO = 'wp-donations';
|
||||
public const CACHE_KEY = 'sg_update_release';
|
||||
public const CACHE_OK = HOUR_IN_SECONDS;
|
||||
public const CACHE_FAIL = 10 * MINUTE_IN_SECONDS;
|
||||
public const TIMEOUT = 8;
|
||||
public const ACTION_CHECK = 'sg_update_check';
|
||||
|
||||
public static function register(): void {
|
||||
if ( ! self::enabled() ) {
|
||||
return;
|
||||
}
|
||||
add_filter( 'pre_set_site_transient_update_plugins', array( self::class, 'inject' ) );
|
||||
add_filter( 'plugins_api', array( self::class, 'pluginInfo' ), 10, 3 );
|
||||
add_filter( 'http_request_args', array( self::class, 'authorize' ), 10, 2 );
|
||||
add_action( 'upgrader_process_complete', array( self::class, 'afterUpgrade' ), 10, 2 );
|
||||
add_action( 'admin_post_' . self::ACTION_CHECK, array( self::class, 'handleCheck' ) );
|
||||
}
|
||||
|
||||
public static function enabled(): bool {
|
||||
return (bool) apply_filters( 'streamgoals_updates_enabled', true );
|
||||
}
|
||||
|
||||
/** @return array{base:string,owner:string,repo:string,host:string} */
|
||||
public static function repo(): array {
|
||||
$r = apply_filters( 'streamgoals_update_repo', array( 'base' => self::BASE_URL, 'owner' => self::OWNER, 'repo' => self::REPO ) );
|
||||
$r = is_array( $r ) ? $r : array();
|
||||
$base = rtrim( is_string( $r['base'] ?? null ) ? $r['base'] : self::BASE_URL, '/' );
|
||||
$host = parse_url( $base, PHP_URL_HOST );
|
||||
return array(
|
||||
'base' => $base,
|
||||
'owner' => is_string( $r['owner'] ?? null ) ? $r['owner'] : self::OWNER,
|
||||
'repo' => is_string( $r['repo'] ?? null ) ? $r['repo'] : self::REPO,
|
||||
'host' => is_string( $host ) ? strtolower( $host ) : '',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached latest release (parsed) or null. Failures are cached briefly so WP never re-hits a broken endpoint.
|
||||
*
|
||||
* @return array{version:string,package:string,url:string,notes:string,published:string}|null
|
||||
*/
|
||||
public static function latest( bool $force = false ): ?array {
|
||||
try {
|
||||
if ( ! $force ) {
|
||||
$c = get_site_transient( self::CACHE_KEY );
|
||||
if ( is_array( $c ) && array_key_exists( 'release', $c ) ) {
|
||||
return is_array( $c['release'] ) ? $c['release'] : null;
|
||||
}
|
||||
}
|
||||
$release = self::fetch();
|
||||
set_site_transient( self::CACHE_KEY, array( 'release' => $release ), null === $release ? self::CACHE_FAIL : self::CACHE_OK );
|
||||
return $release;
|
||||
} catch ( \Throwable $e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static function clearCache(): void {
|
||||
delete_site_transient( self::CACHE_KEY );
|
||||
}
|
||||
|
||||
private static function fetch(): ?array {
|
||||
$repo = self::repo();
|
||||
if ( '' === $repo['host'] || 'https' !== strtolower( (string) parse_url( $repo['base'], PHP_URL_SCHEME ) ) ) {
|
||||
return null;
|
||||
}
|
||||
$url = $repo['base'] . '/api/v1/repos/' . rawurlencode( $repo['owner'] ) . '/' . rawurlencode( $repo['repo'] ) . '/releases/latest';
|
||||
$resp = wp_remote_get( $url, array( 'timeout' => self::TIMEOUT, 'redirection' => 2, 'headers' => array( 'Accept' => 'application/json' ) ) );
|
||||
if ( is_wp_error( $resp ) || 200 !== (int) wp_remote_retrieve_response_code( $resp ) ) {
|
||||
return null;
|
||||
}
|
||||
$data = json_decode( (string) wp_remote_retrieve_body( $resp ), true );
|
||||
return is_array( $data ) ? ReleaseParser::parse( $data, $repo['host'] ) : null;
|
||||
}
|
||||
|
||||
public static function pluginFile(): string {
|
||||
return plugin_basename( STREAMGOALS_FILE );
|
||||
}
|
||||
|
||||
private static function entry( array $rel ): object {
|
||||
$e = new \stdClass();
|
||||
$e->id = $rel['url'] ?: self::BASE_URL;
|
||||
$e->slug = self::SLUG;
|
||||
$e->plugin = self::pluginFile();
|
||||
$e->new_version = $rel['version'];
|
||||
$e->url = $rel['url'];
|
||||
$e->package = $rel['package'];
|
||||
$e->requires = '6.8';
|
||||
$e->requires_php = '8.1';
|
||||
return $e;
|
||||
}
|
||||
|
||||
public static function inject( mixed $transient ): mixed {
|
||||
try {
|
||||
if ( ! is_object( $transient ) ) {
|
||||
return $transient;
|
||||
}
|
||||
$rel = self::latest();
|
||||
$file = self::pluginFile();
|
||||
unset( $transient->response[ $file ], $transient->no_update[ $file ] );
|
||||
if ( null === $rel ) {
|
||||
return $transient;
|
||||
}
|
||||
$entry = self::entry( $rel );
|
||||
if ( ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ) {
|
||||
$transient->response = is_array( $transient->response ?? null ) ? $transient->response : array();
|
||||
$transient->response[ $file ] = $entry;
|
||||
} else {
|
||||
$entry->new_version = STREAMGOALS_VERSION;
|
||||
$transient->no_update = is_array( $transient->no_update ?? null ) ? $transient->no_update : array();
|
||||
$transient->no_update[ $file ] = $entry;
|
||||
}
|
||||
} catch ( \Throwable $e ) {
|
||||
// Never break the Updates screen.
|
||||
}
|
||||
return $transient;
|
||||
}
|
||||
|
||||
public static function pluginInfo( mixed $result, mixed $action = '', mixed $args = null ): mixed {
|
||||
try {
|
||||
if ( 'plugin_information' !== $action || ! is_object( $args ) || ( $args->slug ?? '' ) !== self::SLUG ) {
|
||||
return $result;
|
||||
}
|
||||
$rel = self::latest();
|
||||
if ( null === $rel ) {
|
||||
return $result;
|
||||
}
|
||||
$i = new \stdClass();
|
||||
$i->name = 'StreamGoals Donate';
|
||||
$i->slug = self::SLUG;
|
||||
$i->version = $rel['version'];
|
||||
$i->author = 'StreamGoals';
|
||||
$i->homepage = $rel['url'];
|
||||
$i->requires = '6.8';
|
||||
$i->requires_php = '8.1';
|
||||
$i->last_updated = $rel['published'];
|
||||
$i->download_link = $rel['package'];
|
||||
$i->sections = array(
|
||||
'description' => 'PayPal donations with multiple goals, fee coverage, and OBS stream overlays.',
|
||||
'changelog' => '' !== $rel['notes'] ? ReleaseParser::changelogHtml( $rel['notes'] ) : '<p>No release notes.</p>',
|
||||
);
|
||||
return $i;
|
||||
} catch ( \Throwable $e ) {
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds the token ONLY for https requests to the configured Gitea host. */
|
||||
public static function authorize( mixed $args, mixed $url ): mixed {
|
||||
try {
|
||||
if ( ! is_array( $args ) || ! is_string( $url ) ) {
|
||||
return $args;
|
||||
}
|
||||
$token = trim( (string) Settings::get( 'update_token', '' ) );
|
||||
$host = self::repo()['host'];
|
||||
if ( '' === $token || ! ReleaseParser::isAllowedUrl( $url, $host ) ) {
|
||||
return $args;
|
||||
}
|
||||
$args['headers'] = is_array( $args['headers'] ?? null ) ? $args['headers'] : array();
|
||||
$args['headers']['Authorization'] = 'token ' . $token;
|
||||
} catch ( \Throwable $e ) {
|
||||
// Fall through without credentials.
|
||||
}
|
||||
return $args;
|
||||
}
|
||||
|
||||
public static function afterUpgrade( mixed $upgrader, mixed $options ): void {
|
||||
if ( is_array( $options ) && ( $options['type'] ?? '' ) === 'plugin' ) {
|
||||
self::clearCache();
|
||||
}
|
||||
}
|
||||
|
||||
public static function handleCheck(): void {
|
||||
Admin::guard( self::ACTION_CHECK );
|
||||
self::clearCache();
|
||||
delete_site_transient( 'update_plugins' );
|
||||
$rel = self::latest( true );
|
||||
$back = Admin::url( 'streamgoals-settings' );
|
||||
if ( null === $rel ) {
|
||||
Admin::redirect( $back, 'warning', 'Could not read the latest release. Check your connection and, if the update repository is private, the access token.' );
|
||||
}
|
||||
Admin::redirect( $back, 'success', ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ? 'Version ' . $rel['version'] . ' is available. See Dashboard > Updates.' : 'You are up to date.' );
|
||||
}
|
||||
}
|
||||
@@ -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,75 @@
|
||||
<?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->assertStringContainsString( "DB_VERSION = '2'", $src );
|
||||
$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 );
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,7 @@ final class AdminLogicTest extends TestCase {
|
||||
$r = RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1.00', 'cap_minutes' => '10', 'max_total_minutes' => '' ), 'USD' );
|
||||
$this->assertSame( array(), $r['errors'] );
|
||||
$this->assertSame(
|
||||
array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'basis' => 'base' ),
|
||||
array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'max_timer_seconds' => null, 'basis' => 'base' ),
|
||||
$r['config']
|
||||
);
|
||||
}
|
||||
@@ -92,8 +92,23 @@ final class AdminLogicTest extends TestCase {
|
||||
$this->assertSame( array( 'Timer: +25 minutes', 'Pies: +2', 'Bonus "big" does not trigger' ), RuleConfig::preview( $rules, 2500, 'USD' ) );
|
||||
}
|
||||
|
||||
public function test_max_timer_validation_and_summary(): void {
|
||||
$base = array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1.00' );
|
||||
$this->assertNull( RuleConfig::sanitize( 'add_time', $base, 'USD' )['config']['max_timer_seconds'] );
|
||||
$this->assertNull( RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => ' ' ), 'USD' )['config']['max_timer_seconds'] );
|
||||
$this->assertSame( 86400, RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => '1440' ), 'USD' )['config']['max_timer_seconds'] );
|
||||
foreach ( array( '0', '-5', 'abc', '1.5' ) as $bad ) {
|
||||
$r = RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => $bad ), 'USD' );
|
||||
$this->assertNotEmpty( $r['errors'], $bad );
|
||||
$this->assertNull( $r['config'] );
|
||||
}
|
||||
$this->assertSame( 'Adds 1 minute for every $1.00, up to 1 day on the clock', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 86400 ), 'USD' ) );
|
||||
$this->assertSame( 'Adds 1 minute for every $1.00', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ), 'USD' ) );
|
||||
$this->assertSame( array( 'Timer: +25 minutes (the timer never goes above 1 hour)' ), RuleConfig::preview( array( array( 'type' => 'add_time', 'config' => array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 3600 ) ) ), 2500, 'USD' ) );
|
||||
}
|
||||
|
||||
public function test_form_roundtrip(): void {
|
||||
$cfg = array( 'seconds_per_unit' => 120, 'unit_minor' => 250, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'basis' => 'base' );
|
||||
$cfg = array( 'seconds_per_unit' => 120, 'unit_minor' => 250, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'max_timer_seconds' => 86400, 'basis' => 'base' );
|
||||
$form = RuleConfig::toForm( 'add_time', $cfg, 'USD' );
|
||||
$back = RuleConfig::sanitize( 'add_time', $form, 'USD' );
|
||||
$this->assertSame( $cfg, $back['config'] );
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\Store;
|
||||
|
||||
/**
|
||||
* Regression: Store::rules() must return rules whose `config` is a decoded array, not the raw JSON string.
|
||||
* (A by-reference foreach over a cast temporary once discarded the decoding and crashed the Rules screen.)
|
||||
*/
|
||||
final class AdminStoreRulesTest extends TestCase {
|
||||
|
||||
private $previous;
|
||||
|
||||
protected function setUp(): void {
|
||||
if ( ! defined( 'ARRAY_A' ) ) {
|
||||
define( 'ARRAY_A', 'ARRAY_A' ); // WordPress constant; not loaded in plain PHPUnit
|
||||
}
|
||||
$this->previous = $GLOBALS['wpdb'] ?? null;
|
||||
$GLOBALS['wpdb'] = new class() {
|
||||
public string $prefix = 'wp_';
|
||||
public function prepare( string $q, ...$args ): string { return $q; }
|
||||
public function get_results( string $q, $output = null ): array {
|
||||
return array(
|
||||
array( 'id' => '1', 'goal_id' => '1', 'type' => 'add_time', 'config' => '{"seconds_per_unit":60,"unit_minor":100,"max_timer_seconds":5400}', 'enabled' => '1', 'sort' => '0' ),
|
||||
array( 'id' => '2', 'goal_id' => '1', 'type' => 'counter', 'config' => 'not json', 'enabled' => '0', 'sort' => '1' ),
|
||||
array( 'id' => '3', 'goal_id' => '1', 'type' => 'bonus', 'config' => '{"min_minor":5000}', 'enabled' => '1', 'sort' => '2' ),
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
$GLOBALS['wpdb'] = $this->previous;
|
||||
}
|
||||
|
||||
public function test_every_rule_config_is_a_decoded_array(): void {
|
||||
$rules = Store::rules( 1 );
|
||||
$this->assertCount( 3, $rules );
|
||||
foreach ( $rules as $r ) {
|
||||
$this->assertIsArray( $r['config'], 'rule ' . $r['id'] . ' config was not decoded' );
|
||||
}
|
||||
$this->assertSame( 5400, $rules[0]['config']['max_timer_seconds'] );
|
||||
$this->assertSame( array(), $rules[1]['config'], 'invalid JSON becomes an empty config, not a crash' );
|
||||
$this->assertSame( 5000, $rules[2]['config']['min_minor'] );
|
||||
}
|
||||
|
||||
public function test_rule_lookup_returns_decoded_config(): void {
|
||||
$r = Store::rule( 3, 1 );
|
||||
$this->assertIsArray( $r['config'] );
|
||||
$this->assertNull( Store::rule( 99, 1 ) );
|
||||
}
|
||||
|
||||
public function test_export_only_selects_completed_non_test_donations(): void {
|
||||
$captured = array();
|
||||
$GLOBALS['wpdb'] = new class( $captured ) {
|
||||
public string $prefix = 'wp_';
|
||||
public function __construct( public array &$sql ) {}
|
||||
public function esc_like( string $s ): string { return $s; }
|
||||
public function prepare( string $q, ...$args ): string { return $q; }
|
||||
public function get_results( string $q, $output = null ): array { $this->sql[] = $q; return array(); }
|
||||
};
|
||||
Store::exportBatch( 0, 100 );
|
||||
$this->assertNotEmpty( $captured );
|
||||
$this->assertStringContainsString( "status = 'completed'", $captured[0], 'abandoned/unpaid checkouts must not be exported' );
|
||||
$this->assertStringContainsString( 'goal_id > 0', $captured[0], 'test donations must not be exported' );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Core\ClientIp;
|
||||
|
||||
final class ClientIpTest extends TestCase {
|
||||
|
||||
private const PROXY = '172.70.1.1';
|
||||
private const CLIENT = '203.0.113.9';
|
||||
|
||||
public function test_direct_mode_uses_remote_addr_and_ignores_headers(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4', 'HTTP_X_FORWARDED_FOR' => '5.6.7.8' );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_DIRECT ) );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv ) );
|
||||
}
|
||||
|
||||
public function test_cloudflare_mode_uses_cf_header(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_CLOUDFLARE ) );
|
||||
}
|
||||
|
||||
public function test_cloudflare_mode_without_header_falls_back_to_remote_addr(): void {
|
||||
$this->assertSame( self::PROXY, ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY ), ClientIp::MODE_CLOUDFLARE ) );
|
||||
}
|
||||
|
||||
public function test_invalid_header_values_are_ignored(): void {
|
||||
foreach ( array( 'not-an-ip', '999.1.1.1', '', '1.2.3.4, 5.6.7.8', '<script>', "1.2.3.4\r\nX: y" ) as $bad ) {
|
||||
$srv = array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_CF_CONNECTING_IP' => $bad );
|
||||
$this->assertSame( self::PROXY, ClientIp::resolve( $srv, ClientIp::MODE_CLOUDFLARE ), "accepted bad value: $bad" );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_x_real_ip_mode(): void {
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_X_REAL_IP' => self::CLIENT ), ClientIp::MODE_REAL_IP ) );
|
||||
}
|
||||
|
||||
public function test_forwarded_mode_takes_the_last_entry_not_the_spoofable_first(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_X_FORWARDED_FOR' => '6.6.6.6, ' . self::CLIENT );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_FORWARDED ) );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_X_FORWARDED_FOR' => self::CLIENT ), ClientIp::MODE_FORWARDED ) );
|
||||
}
|
||||
|
||||
public function test_ipv6_is_accepted(): void {
|
||||
$this->assertSame( '2001:db8::1', ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_CF_CONNECTING_IP' => '2001:db8::1' ), ClientIp::MODE_CLOUDFLARE ) );
|
||||
}
|
||||
|
||||
public function test_unknown_when_nothing_valid(): void {
|
||||
$this->assertSame( 'unknown', ClientIp::resolve( array(), ClientIp::MODE_CLOUDFLARE ) );
|
||||
$this->assertSame( 'unknown', ClientIp::resolve( array( 'REMOTE_ADDR' => 'garbage' ) ) );
|
||||
}
|
||||
|
||||
public function test_unrecognised_mode_behaves_like_direct(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4' );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, 'something_else' ) );
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ final class EngineToOverlayIntegrationTest extends TestCase {
|
||||
}
|
||||
public function counter( int $goalId ): array { return array( 'label' => 'Pies', 'value' => $this->s->getInt( $goalId, 'counter:2' ) ); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return array(); }
|
||||
public function bonusesFor( array $donationIds ): array { return array(); }
|
||||
} );
|
||||
|
||||
$d = new Donation( 7, 1, 2500, 0, 2500, 'USD' ); // $25 -> +25 min, counter +2
|
||||
@@ -53,4 +54,55 @@ final class EngineToOverlayIntegrationTest extends TestCase {
|
||||
$engine->reverseDonation( $d );
|
||||
$this->assertSame( 0, $svc->payload( 'counter', $now )['value'] );
|
||||
}
|
||||
|
||||
private function bonusOverlay( FakeEventStore $events, array $donations ): OverlayService {
|
||||
return new OverlayService( new class( $events, $donations ) implements OverlayDataSource {
|
||||
public function __construct( private FakeEventStore $ev, private array $rows ) {}
|
||||
public function activeGoal(): ?array { return array( 'id' => 1, 'title' => 'G', 'target_minor' => 5000, 'currency' => 'USD' ); }
|
||||
public function raisedMinor( array $goal ): int { return 0; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return $this->rows; }
|
||||
public function bonusesFor( array $donationIds ): array {
|
||||
$out = array();
|
||||
foreach ( $this->ev->events as $k => $e ) {
|
||||
[ , $did ] = array_map( 'intval', explode( ':', $k ) );
|
||||
if ( 1 === $e[0] && ! $e[1] && in_array( $did, $donationIds, true ) ) {
|
||||
$out[ $did ][] = 'big_donation';
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
} );
|
||||
}
|
||||
|
||||
public function test_bonus_over_threshold_visible_in_alerts_below_is_not_and_refund_removes(): void {
|
||||
$events = new FakeEventStore();
|
||||
$fired = array();
|
||||
$engine = new Engine(
|
||||
new FakeRuleStore( array( new RuleDef( 3, 1, 'bonus', array( 'min_minor' => 5000, 'event' => 'big_donation' ) ) ) ),
|
||||
$events,
|
||||
new FakeStateRepository(),
|
||||
null,
|
||||
function ( string $event, RuleDef $r, Donation $d, bool $rev ) use ( &$fired ): void {
|
||||
$fired[] = array( $event, $d->id, $rev );
|
||||
}
|
||||
);
|
||||
$big = new Donation( 10, 1, 5000, 0, 5000, 'USD' );
|
||||
$small = new Donation( 11, 1, 4999, 0, 4999, 'USD' );
|
||||
$engine->applyDonation( $big );
|
||||
$engine->applyDonation( $small );
|
||||
$this->assertSame( array( array( 'big_donation', 10, false ) ), $fired );
|
||||
|
||||
$row = static fn( int $id ): array => array( 'id' => $id, 'base_minor' => 5000, 'currency' => 'USD', 'donor_name' => 'A',
|
||||
'is_anonymous' => 0, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
|
||||
$svc = $this->bonusOverlay( $events, array( $row( 10 ), $row( 11 ) ) );
|
||||
$alerts = $svc->payload( 'alerts', 1, 0 )['alerts'];
|
||||
$this->assertSame( array( 'Big donation' ), $alerts[0]['bonuses'] );
|
||||
$this->assertSame( array(), $alerts[1]['bonuses'] );
|
||||
|
||||
$engine->reverseDonation( $big );
|
||||
$this->assertSame( array(), $svc->payload( 'alerts', 1, 0 )['alerts'][0]['bonuses'] );
|
||||
$this->assertSame( true, $fired[1][2] );
|
||||
}
|
||||
}
|
||||
@@ -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'] );
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,41 @@ final class OverlayPayloadsTest extends TestCase {
|
||||
$this->assertSame( Payloads::etag( $g ), Payloads::etag( $g ) );
|
||||
}
|
||||
|
||||
public function test_alert_bonuses_humanized_and_empty_when_none(): void {
|
||||
$out = Payloads::alerts( array( $this->don( 1, array( 'bonuses' => array( 'big_donation', 'mega-win' ) ) ), $this->don( 2 ) ), 0 );
|
||||
$this->assertSame( array( 'Big donation', 'Mega win' ), $out['alerts'][0]['bonuses'] );
|
||||
$this->assertSame( array(), $out['alerts'][1]['bonuses'] );
|
||||
}
|
||||
|
||||
public function test_alert_bonuses_sanitize_hostile_event(): void {
|
||||
$out = Payloads::alerts( array( $this->don( 1, array( 'bonuses' => array( '<img src=x onerror=alert(1)>', '"><script>', '<>', 42, 'big_donation', 'BIG_DONATION' ) ) ) ), 0 );
|
||||
$b = $out['alerts'][0]['bonuses'];
|
||||
$this->assertSame( 'Imgsrcxonerroralert1', $b[0] );
|
||||
foreach ( $b as $label ) {
|
||||
$this->assertMatchesRegularExpression( '/^[A-Za-z0-9 ]+$/', $label );
|
||||
}
|
||||
$this->assertSame( 1, count( array_keys( $b, 'Big donation', true ) ) ); // deduped
|
||||
}
|
||||
|
||||
public function test_bonuses_do_not_affect_masking_moderation_or_since(): void {
|
||||
$rows = array(
|
||||
$this->don( 1, array( 'bonuses' => array( 'big_donation' ) ) ),
|
||||
$this->don( 2, array( 'is_anonymous' => 1, 'donor_name' => 'Secret Sam', 'bonuses' => array( 'big_donation' ) ) ),
|
||||
$this->don( 3, array( 'moderation' => 'pending', 'bonuses' => array( 'big_donation' ) ) ),
|
||||
);
|
||||
$out = Payloads::alerts( $rows, 1 );
|
||||
$this->assertSame( array( 2 ), array_column( $out['alerts'], 'id' ) );
|
||||
$this->assertSame( 'Anonymous', $out['alerts'][0]['name'] );
|
||||
$this->assertStringNotContainsString( 'Secret Sam', json_encode( $out ) );
|
||||
$this->assertSame( array(), Payloads::alerts( $rows, null )['alerts'] );
|
||||
}
|
||||
|
||||
public function test_etag_changes_when_bonus_added(): void {
|
||||
$plain = Payloads::alerts( array( $this->don( 5 ) ), 0 );
|
||||
$bonus = Payloads::alerts( array( $this->don( 5, array( 'bonuses' => array( 'big_donation' ) ) ) ), 0 );
|
||||
$this->assertNotSame( Payloads::etag( $plain ), Payloads::etag( $bonus ) );
|
||||
}
|
||||
|
||||
public function test_style_sanitizes(): void {
|
||||
$s = Style::fromQuery( array( 'theme' => 'bogus', 'accent' => '#FF00AA', 'color' => 'red;}</style>', 'bg' => '11223344',
|
||||
'font' => 'x;}body{', 'scale' => '99' ) );
|
||||
@@ -114,6 +149,7 @@ final class OverlayPayloadsTest extends TestCase {
|
||||
public function raisedMinor( array $goal ): int { return 250; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return 'timer_ends_at' === $key ? '2000' : null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => 'Pies', 'value' => 4 ); }
|
||||
public function bonusesFor( array $donationIds ): array { return array( 3 => array( 'big_donation' ) ); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return array( array( 'id' => 3, 'base_minor' => 100, 'currency' => 'USD', 'donor_name' => 'Z', 'is_anonymous' => 1, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' ) ); }
|
||||
};
|
||||
$svc = new OverlayService( $src );
|
||||
@@ -121,6 +157,7 @@ final class OverlayPayloadsTest extends TestCase {
|
||||
$this->assertSame( 2000, $svc->payload( 'timer', 1500 )['ends_at'] );
|
||||
$this->assertSame( 4, $svc->payload( 'counter', 1 )['value'] );
|
||||
$this->assertSame( 'Anonymous', $svc->payload( 'alerts', 1, 0 )['alerts'][0]['name'] );
|
||||
$this->assertSame( array( 'Big donation' ), $svc->payload( 'alerts', 1, 0 )['alerts'][0]['bonuses'] );
|
||||
$this->assertNull( $svc->payload( 'nope', 1 ) );
|
||||
}
|
||||
}
|
||||
@@ -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 ) ) );
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,88 @@ final class RulesEngineTest extends TestCase {
|
||||
$this->assertSame( 1000 + 100, $this->state->getInt( 1, 'timer_ends_at' ) );
|
||||
}
|
||||
|
||||
private function ends(): int {
|
||||
return $this->state->getInt( 1, 'timer_ends_at' );
|
||||
}
|
||||
|
||||
public function test_max_timer_clamps_and_records_actual_delta(): void {
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 1200 ) ) ) ); // now=1000
|
||||
$this->state->setInt( 1, 'timer_ends_at', 2000 ); // 1000s remaining
|
||||
$e->applyDonation( $this->d( 1, 1000 ) ); // wants +600, room 200
|
||||
$this->assertSame( 2200, $this->ends() );
|
||||
$this->assertSame( 200, $this->events->events['1:1'][0] );
|
||||
$this->assertSame( 200, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
}
|
||||
|
||||
public function test_max_timer_exactly_at_cap_adds_zero(): void {
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 1000 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 2000 );
|
||||
$e->applyDonation( $this->d( 1, 100 ) );
|
||||
$this->assertSame( 2000, $this->ends() );
|
||||
$this->assertSame( 0, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
}
|
||||
|
||||
public function test_max_timer_lowered_below_existing_timer_does_not_shorten(): void {
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 100 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 9000 );
|
||||
$e->applyDonation( $this->d( 1, 100 ) );
|
||||
$this->assertSame( 9000, $this->ends() );
|
||||
$this->assertSame( 0, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
}
|
||||
|
||||
public function test_uncapped_by_default_and_null(): void {
|
||||
foreach ( array( array(), array( 'max_timer_seconds' => null ) ) as $extra ) {
|
||||
$e = $this->engine( array( $this->timer( $extra ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 10000000 );
|
||||
$e->applyDonation( $this->d( 1, 100000 ) );
|
||||
$this->assertSame( 10000000 + 60000, $this->ends() );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_max_timer_with_other_caps_most_restrictive_wins(): void {
|
||||
// per-donation 50 is the tightest
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 500, 'cap_seconds_per_donation' => 50, 'max_total_seconds' => 400 ) ) ) );
|
||||
$e->applyDonation( $this->d( 1, 1000 ) );
|
||||
$this->assertSame( 1050, $this->ends() );
|
||||
// max_total tightest: 30 left of 40 total, clock has room
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 500, 'max_total_seconds' => 40 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_added:1', 10 );
|
||||
$e->applyDonation( $this->d( 1, 1000 ) );
|
||||
$this->assertSame( 1030, $this->ends() );
|
||||
$this->assertSame( 40, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
// clock cap tightest: only 20 of room
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 120, 'cap_seconds_per_donation' => 300, 'max_total_seconds' => 900 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 1100 );
|
||||
$e->applyDonation( $this->d( 1, 1000 ) );
|
||||
$this->assertSame( 1120, $this->ends() );
|
||||
$this->assertSame( 20, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
}
|
||||
|
||||
public function test_max_timer_with_expired_timer_starts_from_now(): void {
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 100 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 10 );
|
||||
$e->applyDonation( $this->d( 1, 1000 ) ); // wants 600
|
||||
$this->assertSame( 1100, $this->ends() );
|
||||
}
|
||||
|
||||
public function test_max_timer_replay_idempotent_and_reversal_uses_clamped_delta(): void {
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 1200 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 2000 );
|
||||
$d = $this->d( 1, 1000 );
|
||||
$e->applyDonation( $d );
|
||||
$e->applyDonation( $d );
|
||||
$this->assertSame( 2200, $this->ends() );
|
||||
$e->reverseDonation( $d );
|
||||
$e->reverseDonation( $d );
|
||||
$this->assertSame( 2000, $this->ends() );
|
||||
$this->assertSame( 0, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
}
|
||||
|
||||
public function test_max_timer_invalid_value_rejected_by_rule(): void {
|
||||
$this->expectException( \InvalidArgumentException::class );
|
||||
\StreamGoals\Rules\AddTimeRule::fromConfig( array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 0 ) );
|
||||
}
|
||||
|
||||
public function test_reversal_undoes_and_is_not_double_applied(): void {
|
||||
$e = $this->engine( array( $this->timer(), $this->counter() ) );
|
||||
$d = $this->d( 10, 2500 );
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Update\ReleaseParser;
|
||||
|
||||
final class UpdateReleaseParserTest extends TestCase {
|
||||
|
||||
private const HOST = 'repo.anhonesthost.net';
|
||||
private const ZIP = 'https://repo.anhonesthost.net/wp-plugins/wp-donations/releases/download/2026.11.15-1941/streamgoals-donate.zip';
|
||||
|
||||
private function release( array $over = array() ): array {
|
||||
return array_merge(
|
||||
array(
|
||||
'tag_name' => '2026.11.15-1941',
|
||||
'draft' => false,
|
||||
'prerelease' => false,
|
||||
'body' => "## What's New\n\n* one\n* two",
|
||||
'html_url' => 'https://repo.anhonesthost.net/wp-plugins/wp-donations/releases/tag/2026.11.15-1941',
|
||||
'published_at' => '2026-11-15T19:41:00Z',
|
||||
'assets' => array( array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => self::ZIP ) ),
|
||||
),
|
||||
$over
|
||||
);
|
||||
}
|
||||
|
||||
public function test_valid_release(): void {
|
||||
$r = ReleaseParser::parse( $this->release(), self::HOST );
|
||||
$this->assertSame( '2026.11.15-1941', $r['version'] );
|
||||
$this->assertSame( self::ZIP, $r['package'] );
|
||||
$this->assertSame( '2026-11-15T19:41:00Z', $r['published'] );
|
||||
$this->assertStringContainsString( 'releases/tag', $r['url'] );
|
||||
}
|
||||
|
||||
public function test_draft_and_prerelease_ignored(): void {
|
||||
$this->assertNull( ReleaseParser::parse( $this->release( array( 'draft' => true ) ), self::HOST ) );
|
||||
$this->assertNull( ReleaseParser::parse( $this->release( array( 'prerelease' => true ) ), self::HOST ) );
|
||||
}
|
||||
|
||||
public function test_bad_tag(): void {
|
||||
foreach ( array( 'nightly', '2026.1.15-1941', '', null, array() ) as $t ) {
|
||||
$this->assertNull( ReleaseParser::parse( $this->release( array( 'tag_name' => $t ) ), self::HOST ) );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_v_prefix_and_semver(): void {
|
||||
$this->assertSame( '2026.11.15-1941', ReleaseParser::parse( $this->release( array( 'tag_name' => 'v2026.11.15-1941' ) ), self::HOST )['version'] );
|
||||
$this->assertSame( '1.2.3', ReleaseParser::parse( $this->release( array( 'tag_name' => 'v1.2.3' ) ), self::HOST )['version'] );
|
||||
}
|
||||
|
||||
public function test_wrong_host_and_non_https_rejected(): void {
|
||||
foreach ( array( 'https://evil.example/streamgoals-donate.zip', 'http://repo.anhonesthost.net/x.zip', 'https://repo.anhonesthost.net@evil.example/x.zip', 'https://repo.anhonesthost.net.evil.example/x.zip', '//repo.anhonesthost.net/x.zip' ) as $u ) {
|
||||
$rel = $this->release( array( 'assets' => array( array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => $u ) ) ) );
|
||||
$this->assertNull( ReleaseParser::parse( $rel, self::HOST ), $u );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_missing_asset(): void {
|
||||
$this->assertNull( ReleaseParser::parse( $this->release( array( 'assets' => array() ) ), self::HOST ) );
|
||||
$this->assertNull( ReleaseParser::parse( $this->release( array( 'assets' => array( array( 'name' => 'notes.txt', 'browser_download_url' => self::ZIP ) ) ) ), self::HOST ) );
|
||||
$this->assertNull( ReleaseParser::parse( array( 'tag_name' => '1.0.0' ), self::HOST ) );
|
||||
}
|
||||
|
||||
public function test_picks_right_asset(): void {
|
||||
$other = 'https://repo.anhonesthost.net/dl/other.zip';
|
||||
$a = array( array( 'name' => 'source.zip', 'browser_download_url' => $other ), array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => self::ZIP ) );
|
||||
$this->assertSame( self::ZIP, ReleaseParser::parse( $this->release( array( 'assets' => $a ) ), self::HOST )['package'] );
|
||||
$this->assertSame( $other, ReleaseParser::parse( $this->release( array( 'assets' => array( $a[0] ) ) ), self::HOST )['package'] );
|
||||
}
|
||||
|
||||
public function test_version_comparison(): void {
|
||||
$this->assertTrue( ReleaseParser::isNewer( '2026.11.15-1830', '2026.11.15-0930' ) );
|
||||
$this->assertFalse( ReleaseParser::isNewer( '2026.11.15-0930', '2026.11.15-1830' ) );
|
||||
$this->assertFalse( ReleaseParser::isNewer( '2026.11.15-0930', '2026.11.15-0930' ) );
|
||||
$this->assertTrue( ReleaseParser::isNewer( 'v2026.11.16-0001', '2026.11.15-2359' ) );
|
||||
$this->assertTrue( ReleaseParser::isNewer( '2026.11.15-1941', '0.1.0' ) );
|
||||
$this->assertFalse( ReleaseParser::isNewer( 'garbage', '0.1.0' ) );
|
||||
}
|
||||
|
||||
public function test_changelog_escapes_html(): void {
|
||||
$h = ReleaseParser::changelogHtml( "<script>alert(1)</script>\n\n* <b>bold</b> & \"q\"\n* two" );
|
||||
$this->assertStringNotContainsString( '<script', $h );
|
||||
$this->assertStringNotContainsString( '<b>', $h );
|
||||
$this->assertStringContainsString( '<script>', $h );
|
||||
$this->assertStringContainsString( '<ul><li><b>bold</b> & "q"</li><li>two</li></ul>', $h );
|
||||
}
|
||||
|
||||
public function test_changelog_paragraphs_and_headings(): void {
|
||||
$this->assertSame( '<h4>What's New</h4><p>a b</p><ul><li>x</li></ul>', ReleaseParser::changelogHtml( "## What's New\n\na\nb\n\n- x" ) );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user