Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
afa768fa42 | ||
|
|
9249b80cb6 | ||
|
|
cc5b9518e4 | ||
|
|
f6cd67ed0d | ||
|
|
4c379a0245 |
No files matched your search
@@ -30,6 +30,11 @@ You need two values from PayPal: a **Client ID** and a **Secret**.
|
||||
Start in **Sandbox**, make a test donation using a PayPal sandbox buyer account, then repeat the steps
|
||||
with the Live credentials and switch the mode to Live in Settings.
|
||||
|
||||
### Behind Cloudflare?
|
||||
Nothing to do: the plugin recognises Cloudflare automatically (by its published addresses) so each visitor is rate
|
||||
limited separately. For another proxy, choose it in StreamGoals > Settings > Advanced; the panel there shows what your
|
||||
server sees.
|
||||
|
||||
### Notes on fees and currency
|
||||
- "Cover the processing fees" adds an estimate based on the rates in Settings (default: US domestic,
|
||||
3.49% + $0.49). Your actual PayPal rate depends on your account, country and payment method.
|
||||
@@ -51,6 +56,19 @@ with the Live credentials and switch the mode to Live in Settings.
|
||||
form, as a **Rewards menu** overlay for OBS, and as a highlighted line in the donation alert. Triggered rewards land in a
|
||||
**queue** on the Rewards screen so you can tick them off as you do them. Rewards count the donation amount, not the
|
||||
optional fee cover, and must be at least your minimum donation.
|
||||
- **Alerts with pictures, GIFs, videos and sounds:** StreamGoals > Alerts. Pick files from your WordPress Media Library
|
||||
(PNG, JPEG, GIF, WebP, MP4, WebM for the picture/video; MP3, OGG, WAV for sound). Tie an alert to **a donation size**
|
||||
("any donation of at least $5": the highest matching amount wins) or to **a reward** (a reward alert beats an amount
|
||||
alert). Set the volume, how long a picture stays, and a message using `{name}`, `{amount}` and `{reward}`. In OBS media
|
||||
plays automatically; in an ordinary browser tab click the page once before sound is allowed. Keep files small (videos
|
||||
under about 25 MB). If a file is deleted the alert still shows, just without it.
|
||||
- **Tiers (milestones):** on the Goals screen use **Tiers** to turn one goal into a ladder, for example $100 "Giveaway",
|
||||
$250 "New microphone", $500 "24-hour stream". The goal bar shows the current tier and fills within it; unlocking a tier
|
||||
shows a **TIER UNLOCKED** line in the alert and the bar moves on to the next one. The goal's final target is your highest
|
||||
tier. The donation form shows "Next unlock: ... to go".
|
||||
- **End at target:** tick "Close this goal to donations when the target is reached" on a goal. When the total reaches or
|
||||
passes the target (for a tiered goal, the final tier) the goal closes and the donation page says so. Donations already
|
||||
in checkout still go through. Use **Reopen** after raising the target.
|
||||
- **Test:** "Send test donation" on the Overlays screen shows an alert without touching real totals.
|
||||
|
||||
## Privacy and moderation
|
||||
@@ -61,6 +79,19 @@ 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.
|
||||
|
||||
## Transparent alerts
|
||||
In StreamGoals > Alerts, tick **Frameless** on an alert to drop the dark box, border and glow so only your picture or
|
||||
video shows. Transparency works with PNG, GIF and WebP pictures that have an alpha channel and with WebM (VP8/VP9)
|
||||
videos made with alpha; MP4 (H.264) can never be transparent. To make a WebM with alpha:
|
||||
`ffmpeg -i input.mov -c:v libvpx-vp9 -pix_fmt yuva420p -b:v 0 -crf 30 output.webm`. The name and bonus lines still
|
||||
show under the media, outlined so they stay readable. The alert preview has a checkerboard/sample-scene backdrop.
|
||||
|
||||
## Overlays update themselves
|
||||
An open OBS Browser Source never reloads on its own. Every overlay response now carries a build id (plugin version
|
||||
plus a counter); when it differs from the one the page was loaded with, the overlay reloads itself once. Updating the
|
||||
plugin does this automatically, and StreamGoals > Overlays > "Refresh all overlays now" does it on demand. Alert media
|
||||
URLs also carry `?v=<file modified time>`, so replacing a file with the same name is picked up.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -47,7 +47,12 @@
|
||||
/* Phones: wide tables scroll inside their own box instead of pushing the page; controls never exceed the card. */
|
||||
@media (max-width: 782px) {
|
||||
.sg-admin table.sg-table { display: block; max-width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; }
|
||||
.sg-admin .sg-table th, .sg-admin .sg-table td { min-width: 4.5em; }
|
||||
.sg-admin .sg-table th, .sg-admin .sg-table td { min-width: 3em; padding: 8px 6px; font-size: 13px; }
|
||||
.sg-admin .sg-table code { overflow-wrap: anywhere; word-break: break-all; font-size: 12px; }
|
||||
.sg-admin .sg-table td:last-child .button { margin: 0 4px 4px 0; }
|
||||
.sg-admin .sg-card details > summary { min-height: 44px; display: flex; align-items: center; cursor: pointer; }
|
||||
.sg-admin .sg-card label > input[type="radio"], .sg-admin .sg-card label > input[type="checkbox"] { margin-right: 6px; }
|
||||
.sg-admin .sg-card p > label + .description, .sg-admin .sg-card p > label { display: inline-block; margin: 4px 0; }
|
||||
.sg-admin select, .sg-admin input[type="text"], .sg-admin input[type="url"], .sg-admin input[type="number"], .sg-admin textarea { max-width: 100%; box-sizing: border-box; }
|
||||
.sg-admin .sg-card { padding-left: 14px; padding-right: 14px; }
|
||||
}
|
||||
@@ -11,3 +11,23 @@
|
||||
.sga-alert-head{font-weight:800;font-size:1.2em}
|
||||
.sga-alert-head b{color:#22d3ee}
|
||||
.sga-idle{color:#bbb;font-size:14px;align-self:center}
|
||||
|
||||
/* Phones: radio rows breathe, slider fills the width, preview stage scales and never overflows. */
|
||||
@media (max-width:782px){
|
||||
.sga-form label{display:inline-block;margin:6px 0;min-height:32px}
|
||||
.sga-form input[type=range]{width:100%;min-height:32px}
|
||||
.sga-stage{min-height:120px;padding:10px;font-size:16px;overflow:hidden;box-sizing:border-box;max-width:100%}
|
||||
.sga-alert{box-sizing:border-box}
|
||||
.sga-alert-media img,.sga-alert-media video{max-height:180px}
|
||||
.sga-media .button{min-height:40px}
|
||||
}
|
||||
|
||||
/* Frameless alerts: preview backdrops and card without the box */
|
||||
.sga-bg-light{background:repeating-conic-gradient(#e8e8ee 0 25%,#fff 0 50%) 0 0/20px 20px;color:#111}
|
||||
.sga-bg-scene{background:linear-gradient(135deg,#1e6f3c 0 33%,#c2410c 33% 66%,#1d4ed8 66%)}
|
||||
.sga-alert.sga-frameless{background:none;border:0;padding:0}
|
||||
.sga-frameless .sga-alert-head{text-shadow:0 0 3px #000,0 0 6px #000,0 1px 4px #000}
|
||||
.sga-bg-light .sga-frameless .sga-alert-head{text-shadow:0 0 3px #fff,0 0 6px #fff;color:#111}
|
||||
.sga-howto{margin-top:8px}
|
||||
.sga-howto pre{overflow-x:auto;max-width:100%;padding:8px;background:#f0f0f1}
|
||||
.sga-bg-pick{margin-left:12px}
|
||||
@@ -110,7 +110,8 @@
|
||||
var vals = { name: 'Alex', amount: money( amt || 500 ), reward: reward };
|
||||
var msg = render( form.elements.message.value, vals );
|
||||
|
||||
var card = el( 'div', 'sga-alert' );
|
||||
var frameless = !! ( visUrl && form.elements.frameless && form.elements.frameless.checked );
|
||||
var card = el( 'div', 'sga-alert' + ( frameless ? ' sga-frameless' : '' ) );
|
||||
var isVideo = /^video\//.test( visMime ), video = null;
|
||||
if ( visUrl ) {
|
||||
var box = el( 'div', 'sga-alert-media' );
|
||||
@@ -145,6 +146,10 @@
|
||||
timers.push( setTimeout( end, dur ) );
|
||||
}
|
||||
}
|
||||
/* Preview backdrop: dark / light checkerboard or a busy "scene" so transparency is visible. */
|
||||
var bgSel = document.getElementById( 'sga-bg' );
|
||||
function setBg() { stage.className = 'sga-stage' + ( bgSel && bgSel.value !== 'dark' ? ' sga-bg-' + bgSel.value : '' ); }
|
||||
if ( bgSel ) { bgSel.addEventListener( 'change', setBg ); }
|
||||
playBtn.addEventListener( 'click', play );
|
||||
stage.appendChild( el( 'span', 'sga-idle', 'Press "Play preview".' ) );
|
||||
}() );
|
||||
@@ -35,3 +35,10 @@
|
||||
.sg-donate label.sg-inline input[type=checkbox]{flex:none;width:22px;height:22px;margin:0}
|
||||
.sg-donate .sg-cover{gap:.25rem}
|
||||
.sg-donate .sg-act-title,.sg-donate .sg-act-desc,.sg-donate .sg-tip,.sg-donate .sg-msg,.sg-donate .sg-total{overflow-wrap:anywhere}
|
||||
|
||||
.sg-donate .sg-next-unlock{margin:0 0 .9rem;padding:.5rem .75rem;border:1px solid rgba(128,128,128,.5);border-left-width:4px;border-radius:.4rem;font-weight:600;line-height:1.4;overflow-wrap:anywhere}
|
||||
.sg-donate .sg-next-unlock[hidden]{display:none}
|
||||
.sg-donate .sg-presets button.sg-action{padding-right:2.2em}
|
||||
.sg-donate .sg-presets.sg-actions{padding:0 5px}
|
||||
|
||||
.sg-donate .sg-notice{margin:.6rem 0 0;font-size:.9em;line-height:1.4;opacity:.85;overflow-wrap:anywhere}
|
||||
+15
-2
@@ -82,6 +82,18 @@
|
||||
var status = el('div', { 'class': 'sg-msg', role: 'status' });
|
||||
var buttons = el('div', { 'class': 'sg-buttons' });
|
||||
|
||||
// "Next unlock" line for tiered goals (server computes title + remaining minor units per goal).
|
||||
var nextLine = el('p', { 'class': 'sg-next-unlock', 'aria-live': 'polite' });
|
||||
nextLine.hidden = true;
|
||||
function showNext() {
|
||||
var n = state.goal.nextUnlock;
|
||||
if (!n || !n.title || !(n.remaining_minor > 0)) { nextLine.hidden = true; nextLine.textContent = ''; return; }
|
||||
nextLine.textContent = String(T.nextUnlock || 'Next unlock: %1$s \u2014 %2$s to go')
|
||||
.replace('%1$s', function () { return n.title; })
|
||||
.replace('%2$s', function () { return fmt(n.remaining_minor, state.goal.exp, state.goal.currency); });
|
||||
nextLine.hidden = false;
|
||||
}
|
||||
root.appendChild(nextLine);
|
||||
if (goals.length > 1) { root.appendChild(row([el('label', { 'for': uid + '-goal', text: T.goal }), goalSel])); }
|
||||
root.appendChild(row([el('label', { text: T.amount }), presetBox, el('label', { 'class': 'sg-sub', 'for': uid + '-amt', text: T.customAmount || 'Or enter your own amount' }), amount, hint]));
|
||||
var nameRow = row([el('label', { 'for': uid + '-name', text: T.name }), name]);
|
||||
@@ -109,6 +121,7 @@
|
||||
root.appendChild(row([total]));
|
||||
root.appendChild(status); // messages sit above the PayPal buttons, next to the form fields
|
||||
root.appendChild(buttons);
|
||||
if (C.notice) { root.appendChild(el('p', { 'class': 'sg-notice', text: String(C.notice) })); } // e.g. "Donations are non-refundable." right where the donor pays
|
||||
|
||||
function say(text, cls) { status.textContent = text || ''; status.className = 'sg-msg' + (cls ? ' ' + cls : ''); }
|
||||
function amountStr() { return amount.value.trim().replace(',', '.'); }
|
||||
@@ -223,9 +236,9 @@
|
||||
|
||||
goalSel.addEventListener('change', function () {
|
||||
state.goal = goals.filter(function (g) { return String(g.id) === goalSel.value; })[0] || goals[0];
|
||||
buildPresets(); refresh(); renderButtons();
|
||||
showNext(); buildPresets(); refresh(); renderButtons();
|
||||
});
|
||||
buildPresets(); refresh(); renderButtons();
|
||||
showNext(); buildPresets(); refresh(); renderButtons();
|
||||
}
|
||||
|
||||
function boot() { Array.prototype.forEach.call(document.querySelectorAll('.sg-donate'), init); }
|
||||
|
||||
@@ -49,3 +49,23 @@ body.sg-offline #sg-root{opacity:.6}
|
||||
.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}}
|
||||
|
||||
/* Tiered goals */
|
||||
.sg-tier{font-size:.85em;font-weight:600;margin-bottom:.3em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--sg-accent2)}
|
||||
.sg-tier[hidden]{display:none}
|
||||
.sg-card.sg-tiers-done .sg-tier{font-weight:800}
|
||||
.sg-card.sg-tier-up{animation:sg-tier-pop 1.1s cubic-bezier(.22,1,.36,1) 2,sg-tier-glow 1.3s ease-in-out 2}
|
||||
.sg-bonus-line.sg-tier-line{background:linear-gradient(90deg,#f59e0b,#ef4444);color:#fff;border-radius:.3em;letter-spacing:.04em}
|
||||
@keyframes sg-tier-pop{0%{transform:scale(1)}30%{transform:scale(1.06)}100%{transform:scale(1)}}
|
||||
@keyframes sg-tier-glow{0%,100%{box-shadow:0 0 0 transparent}50%{box-shadow:0 0 1em #f59e0b,0 0 2em var(--sg-accent2)}}
|
||||
@media (prefers-reduced-motion:reduce){.sg-card.sg-tier-up{animation:none;box-shadow:0 0 .8em #f59e0b}}
|
||||
|
||||
/* Frameless alerts (transparent PNG/GIF/WebP/WebM): no box, border or glow; media fits the window; text gets an outline. */
|
||||
.sg-alert.sg-frameless{background:none;border:0;box-shadow:none;padding:0;max-height:100%;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;min-height:0}
|
||||
.sg-alert.sg-frameless.sg-bonus{border:0;animation:sg-in .6s cubic-bezier(.22,1,.36,1) both}
|
||||
.sg-alert.sg-frameless.sg-bonus.sg-out,.sg-alert.sg-frameless.sg-out{animation:sg-out .5s ease-in both}
|
||||
.sg-frameless .sg-alert-media{flex:0 1 auto;min-height:0;max-width:100%;max-height:100%;margin-bottom:.2em;overflow:hidden}
|
||||
.sg-frameless .sg-alert-media img,.sg-frameless .sg-alert-media video{max-width:100%;max-height:calc(100vh - 9em);width:auto;height:auto;object-fit:contain;border-radius:0;background:transparent}
|
||||
.sg-frameless .sg-alert-head,.sg-frameless .sg-alert-msg,.sg-frameless .sg-bonus-line{text-shadow:0 0 .06em #000,0 0 .12em #000,0 0 .2em #000,0 .04em .3em #000,.04em 0 0 #000,-.04em 0 0 #000,0 .04em 0 #000,0 -.04em 0 #000}
|
||||
.sg-theme-light .sg-frameless .sg-alert-head,.sg-theme-light .sg-frameless .sg-alert-msg{text-shadow:0 0 .06em #fff,0 0 .12em #fff,0 0 .2em #fff,.04em 0 0 #fff,-.04em 0 0 #fff,0 .04em 0 #fff,0 -.04em 0 #fff}
|
||||
@media (prefers-reduced-motion:reduce){.sg-alert.sg-frameless,.sg-alert.sg-frameless.sg-out,.sg-alert.sg-frameless.sg-bonus,.sg-alert.sg-frameless.sg-bonus.sg-out{animation:none;box-shadow:none}}
|
||||
@@ -5,6 +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 build = body.getAttribute('data-build') || '';
|
||||
var etag = null, failures = 0, skew = 0, timerState = null;
|
||||
var queue = [], showing = false;
|
||||
|
||||
@@ -16,26 +17,52 @@
|
||||
}
|
||||
|
||||
// ---- goal ----
|
||||
var goal = null, shownRaised = 0, raf = 0;
|
||||
var goal = null, shownRaised = 0, raf = 0, lastTierKey = null, celebrateTimer = 0;
|
||||
function renderGoal(d) {
|
||||
if (!d.active) { root.textContent = ''; goal = null; return; }
|
||||
if (!d.active) { root.textContent = ''; goal = null; lastTierKey = null; return; }
|
||||
if (!goal) {
|
||||
root.textContent = '';
|
||||
var card = el('div', 'sg-card');
|
||||
goal = { title: el('div', 'sg-title'), fill: el('div', 'sg-fill'), pct: el('div', 'sg-pct'),
|
||||
goal = { card: card, tier: el('div', 'sg-tier'), title: el('div', 'sg-title'), fill: el('div', 'sg-fill'), pct: el('div', 'sg-pct'),
|
||||
raised: el('span'), target: el('span') };
|
||||
var track = el('div', 'sg-track');
|
||||
track.appendChild(goal.fill); track.appendChild(goal.pct);
|
||||
var nums = el('div', 'sg-nums'); nums.appendChild(goal.raised); nums.appendChild(goal.target);
|
||||
card.appendChild(goal.title); card.appendChild(track); card.appendChild(nums);
|
||||
goal.tier.hidden = true;
|
||||
card.appendChild(goal.title); card.appendChild(goal.tier); card.appendChild(track); card.appendChild(nums);
|
||||
root.appendChild(card);
|
||||
}
|
||||
goal.title.textContent = d.title;
|
||||
goal.target.textContent = d.target_display;
|
||||
goal.fill.style.width = d.percent + '%';
|
||||
goal.pct.textContent = d.percent + '%';
|
||||
renderTier(d.tiers);
|
||||
tweenRaised(d);
|
||||
}
|
||||
// Tiered goals only (d.tiers present): "Tier 2 of 4 \u00b7 title" above the bar, or "All tiers unlocked!".
|
||||
// Untiered goals keep the tier line hidden, so they look exactly as before. textContent only.
|
||||
function renderTier(t) {
|
||||
var valid = t && typeof t === 'object' && isFinite(Number(t.count)) && Number(t.count) > 0;
|
||||
goal.tier.hidden = !valid;
|
||||
goal.card.classList.toggle('sg-tiered', !!valid);
|
||||
goal.card.classList.toggle('sg-tiers-done', !!(valid && t.all_reached));
|
||||
if (!valid) { goal.tier.textContent = ''; lastTierKey = null; return; }
|
||||
var cur = t.current && typeof t.current === 'object' ? t.current : null;
|
||||
goal.tier.textContent = t.all_reached || !cur
|
||||
? 'All tiers unlocked!'
|
||||
: 'Tier ' + parseInt(t.index, 10) + ' of ' + parseInt(t.count, 10) + ' \u00b7 ' + String(cur.title || '');
|
||||
// Celebrate when the current tier changed between polls (never on the first poll / after a reload).
|
||||
var key = (t.all_reached ? 'done' : String(t.index)) + '/' + t.count;
|
||||
if (lastTierKey !== null && lastTierKey !== key) {
|
||||
goal.card.classList.remove('sg-tier-up');
|
||||
void goal.card.offsetWidth; // restart the animation
|
||||
goal.card.classList.add('sg-tier-up');
|
||||
clearTimeout(celebrateTimer);
|
||||
var card = goal.card;
|
||||
celebrateTimer = setTimeout(function () { card.classList.remove('sg-tier-up'); }, 2600);
|
||||
}
|
||||
lastTierKey = key;
|
||||
}
|
||||
function tweenRaised(d) {
|
||||
cancelAnimationFrame(raf);
|
||||
var from = shownRaised, to = d.raised_minor, t0 = performance.now(), dur = 1200;
|
||||
@@ -125,7 +152,7 @@
|
||||
if (!v && !s && !msg) return null;
|
||||
var vol = Number(m.volume); if (!isFinite(vol)) vol = 80;
|
||||
var dur = Number(m.duration_ms); if (!isFinite(dur) || dur <= 0) dur = DEFAULT_HOLD;
|
||||
return { visual: v, sound: s, volume: Math.max(0, Math.min(100, vol)) / 100, duration: Math.max(1000, Math.min(60000, dur)), message: msg };
|
||||
return { frameless: !!(v && m.frameless === true), visual: v, sound: s, volume: Math.max(0, Math.min(100, vol)) / 100, duration: Math.max(1000, Math.min(60000, dur)), message: msg };
|
||||
}
|
||||
// Loads visual + sound before the card appears (no flash of an empty frame). Anything that fails or takes
|
||||
// longer than MEDIA_TIMEOUT is dropped, so the alert falls back to text and the queue never stalls.
|
||||
@@ -186,6 +213,7 @@
|
||||
box.appendChild(vis);
|
||||
card.appendChild(box);
|
||||
card.classList.add('sg-has-media');
|
||||
if (m && m.frameless) card.classList.add('sg-frameless');
|
||||
}
|
||||
if (m && m.message) {
|
||||
head.textContent = m.message;
|
||||
@@ -203,11 +231,16 @@
|
||||
}
|
||||
}
|
||||
var acts = Array.isArray(a.actions) ? a.actions : [];
|
||||
if (acts.length) card.classList.add('sg-bonus');
|
||||
var tiersUnlocked = Array.isArray(a.tiers) ? a.tiers : [];
|
||||
if (acts.length || tiersUnlocked.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 : '')));
|
||||
}
|
||||
for (var q = 0; q < tiersUnlocked.length; q++) {
|
||||
var tt = tiersUnlocked[q] && tiersUnlocked[q].title;
|
||||
if (tt) card.appendChild(el('div', 'sg-bonus-line sg-tier-line', 'TIER UNLOCKED: ' + String(tt)));
|
||||
}
|
||||
if (a.message) card.appendChild(el('div', 'sg-alert-msg', a.message));
|
||||
root.appendChild(card);
|
||||
|
||||
@@ -333,6 +366,33 @@
|
||||
var delay = failures ? Math.min(15000, poll * Math.pow(2, Math.min(failures, 3))) : poll;
|
||||
setTimeout(tick, delay);
|
||||
}
|
||||
// Self-refresh: every overlay response carries the current build id (plugin version + admin epoch) in X-SG-Build.
|
||||
// A different value than the one this page was rendered with means the page is stale (OBS never reloads a
|
||||
// running source after an update), so reload once. Guard: at most one reload per build per 30 s, remembered in
|
||||
// sessionStorage, or in a module flag when storage is blocked. Applies to 200 and 304 responses alike.
|
||||
var RELOAD_GUARD_MS = 30000, reloadTried = {};
|
||||
// sessionStorage first; if it is blocked, window.name (which also survives a reload) carries the marker, so a
|
||||
// blocked-storage source cannot reload in a loop. The module-level reloadTried only covers one page life.
|
||||
function readGuard(key) {
|
||||
try { return JSON.parse(sessionStorage.getItem(key) || 'null'); } catch (e) { /* fall through */ }
|
||||
try { var m = /(?:^|;)sg_reload=([^;]*)/.exec(window.name || ''); return m ? JSON.parse(decodeURIComponent(m[1])) : null; } catch (e2) { return null; }
|
||||
}
|
||||
function writeGuard(key, v) {
|
||||
try { sessionStorage.setItem(key, JSON.stringify(v)); return; } catch (e) { /* fall through */ }
|
||||
try { window.name = (window.name || '').replace(/(?:^|;)sg_reload=[^;]*/, '') + ';sg_reload=' + encodeURIComponent(JSON.stringify(v)); } catch (e2) { /* module flag only */ }
|
||||
}
|
||||
function checkBuild(r) {
|
||||
var b = null;
|
||||
try { b = r.headers.get('X-SG-Build'); } catch (e) { return false; }
|
||||
if (!b || !build || b === build) return false;
|
||||
var now = Date.now(), key = 'sg_overlay_reload', last = readGuard(key);
|
||||
var seen = last && last.b === b ? Number(last.t) : 0;
|
||||
if (reloadTried[b] && reloadTried[b] > seen) seen = reloadTried[b];
|
||||
if (seen && now - seen < RELOAD_GUARD_MS && now >= seen) return false;
|
||||
reloadTried[b] = now;
|
||||
writeGuard(key, { b: b, t: now });
|
||||
try { location.reload(); return true; } catch (e3) { return false; }
|
||||
}
|
||||
function tick() {
|
||||
var ctrl = typeof AbortController === 'function' ? new AbortController() : null;
|
||||
var to = ctrl ? setTimeout(function () { ctrl.abort(); }, 8000) : 0;
|
||||
@@ -341,6 +401,7 @@
|
||||
fetch(url(), { headers: headers, cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
|
||||
.then(function (r) {
|
||||
clearTimeout(to);
|
||||
if (checkBuild(r)) return null;
|
||||
if (r.status === 304) return null;
|
||||
if (!r.ok) throw new Error('http ' + r.status);
|
||||
var et = r.headers.get('ETag');
|
||||
|
||||
@@ -25,6 +25,8 @@ 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_tier_save' => array( GoalsPage::class, 'handleTierSave' ),
|
||||
'sg_tier_delete' => array( GoalsPage::class, 'handleTierDelete' ),
|
||||
'sg_action_save' => array( ActionsPage::class, 'handleSave' ),
|
||||
'sg_action_toggle' => array( ActionsPage::class, 'handleToggle' ),
|
||||
'sg_action_delete' => array( ActionsPage::class, 'handleDelete' ),
|
||||
@@ -38,6 +40,7 @@ final class Admin {
|
||||
'sg_test_donation' => array( OverlaysPage::class, 'handleTestDonation' ),
|
||||
'sg_delete_tests' => array( OverlaysPage::class, 'handleDeleteTests' ),
|
||||
'sg_regen_token' => array( OverlaysPage::class, 'handleRegenerate' ),
|
||||
'sg_refresh_overlays' => array( OverlaysPage::class, 'handleRefreshAll' ),
|
||||
'sg_settings_save' => array( SettingsPage::class, 'handleSave' ),
|
||||
);
|
||||
|
||||
|
||||
@@ -178,6 +178,9 @@ final class AlertsPage {
|
||||
echo '</select><p class="description">A reward alert beats an amount alert. Only rewards that are turned on can be picked.</p></td></tr>';
|
||||
self::mediaField( 'visual_id', 'Picture, GIF or video', 'visual', (int) $val( 'visual_id', 0 ), 'PNG, JPEG, GIF, WebP, MP4 or WebM. Optional. Under 25 MB works best; big videos can slow OBS down.' );
|
||||
self::mediaField( 'sound_id', 'Sound', 'sound', (int) $val( 'sound_id', 0 ), 'MP3, OGG or WAV. Optional. If you also pick a video, the video is muted and this sound plays instead.' );
|
||||
echo '<tr><th scope="row">Frameless</th><td><label><input type="checkbox" name="frameless" value="1" id="sga_frameless"' . checked( ! empty( $d['frameless'] ), true, false ) . '> Show the picture/video without the alert box (for transparent PNG, GIF, WebP or WebM files)</label>';
|
||||
echo '<p class="description">Normally the alert sits in a dark rounded box. Tick this to remove the box, border and glow so only your picture or video shows, with the see-through parts showing your stream underneath. Transparency works with <strong>PNG, GIF and WebP</strong> pictures and <strong>WebM</strong> videos made with transparency. <strong>MP4 never supports transparency</strong>, so an MP4 always shows a solid picture. The name and bonus lines still appear under the media, with an outline so they stay readable on any scene. Only applies when you picked a picture or video.</p>';
|
||||
echo '<details class="sga-howto"><summary>How do I make a transparent video?</summary><p>Export your animation with an alpha channel (a "transparent background"), then convert it to WebM with <a href="https://ffmpeg.org/" target="_blank" rel="noopener noreferrer">ffmpeg</a>:</p><pre><code>ffmpeg -i input.mov -c:v libvpx-vp9 -pix_fmt yuva420p -b:v 0 -crf 30 -an output.webm</code></pre><p>Replace <code>input.mov</code> with your file (a ProRes 4444 .mov or a PNG sequence both work). Use <code>-an</code> to drop audio (pick a separate sound above instead) or remove it to keep the clip\'s own sound. Then upload <code>output.webm</code> to your Media Library. Use the preview below to check it: the checkerboard shows through the transparent parts.</p></details></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sga_volume">Volume</label></th><td><input type="range" min="0" max="100" id="sga_volume" name="volume" value="' . (int) $val( 'volume', 80 ) . '"> <output id="sga_volume_out">' . (int) $val( 'volume', 80 ) . '</output>%</td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sga_duration">How long a picture stays</label></th><td><input type="number" min="1" max="60" step="1" id="sga_duration" name="duration" class="small-text" value="' . esc_attr( (string) (int) round( (int) $val( 'duration_ms', 6000 ) / 1000 ) ) . '"> seconds<p class="description">1 to 60. Videos play to the end instead, for at most 30 seconds.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sga_message">Message</label></th><td><input type="text" maxlength="255" id="sga_message" name="message" class="large-text" value="' . esc_attr( (string) $val( 'message' ) ) . '"><p class="description">Optional. Use {name}, {amount} and {reward}, for example "{name} just sent {amount}!". Leave empty for the normal text ("Name donated $5.00").</p></td></tr>';
|
||||
@@ -186,7 +189,7 @@ final class AlertsPage {
|
||||
|
||||
echo '<div class="sg-card"><h3>Preview</h3>';
|
||||
echo '<p class="description">This is how the alert will look on stream. Press the button to play it (browsers only allow sound after you click).</p>';
|
||||
echo '<p><button type="button" class="button" id="sga-play">Play preview</button></p>';
|
||||
echo '<p><button type="button" class="button" id="sga-play">Play preview</button> <label class="sga-bg-pick">Preview background <select id="sga-bg"><option value="dark">Dark checkerboard</option><option value="light">Light checkerboard</option><option value="scene">Sample scene</option></select></label></p>';
|
||||
echo '<div id="sga-stage" class="sga-stage" aria-live="polite"></div>';
|
||||
echo '<script type="application/json" id="sga-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">' . ( $d ? 'Save alert' : 'Add alert' ) . '</button> <a class="button" href="' . esc_url( self::url() ) . '">Cancel</a></p></form>';
|
||||
|
||||
@@ -4,6 +4,9 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Tiers\TierPolicy;
|
||||
use StreamGoals\Tiers\TierRepository;
|
||||
|
||||
/** Goals list/create/edit/status/delete, plus the per-goal rules editor. */
|
||||
final class GoalsPage {
|
||||
@@ -17,6 +20,8 @@ final class GoalsPage {
|
||||
self::renderForm( 'edit' === $view ? $id : 0 );
|
||||
} elseif ( 'rules' === $view && $id ) {
|
||||
self::renderRules( $id );
|
||||
} elseif ( 'tiers' === $view && $id ) {
|
||||
self::renderTiers( $id );
|
||||
} else {
|
||||
self::renderList();
|
||||
}
|
||||
@@ -29,6 +34,7 @@ final class GoalsPage {
|
||||
echo '<p><a class="page-title-action" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'new' ) ) ) . '">Add new goal</a></p>';
|
||||
echo '<p class="description">Overlays and the donation form use your newest <strong>active</strong> goal(s). Pause a goal to stop accepting donations; mark it complete when you are done. A goal that has donations cannot be deleted (complete it instead), so your records stay intact.</p>';
|
||||
$goals = Store::goals()->all();
|
||||
$tierCounts = $goals ? ( new TierRepository() )->countsByGoal() : array();
|
||||
if ( ! $goals ) {
|
||||
echo '<div class="sg-card"><p>No goals yet. <a href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'new' ) ) ) . '">Create your first goal</a> or run the <a href="' . esc_url( SetupPage::url( 2 ) ) . '">setup guide</a>.</p></div>';
|
||||
Admin::close();
|
||||
@@ -47,6 +53,8 @@ final class GoalsPage {
|
||||
echo '<td>' . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '<br>' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '</td><td class="sg-actions">';
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'edit', 'goal' => $gid ) ) ) . '">Edit</a> ';
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ) ) . '">Rules</a> ';
|
||||
$nt = $tierCounts[ $gid ] ?? 0;
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'tiers', 'goal' => $gid ) ) ) . '">Tiers' . ( $nt > 0 ? ' (' . (int) $nt . ')' : '' ) . '</a> ';
|
||||
foreach ( array( 'active' => array( 'paused', 'Pause' ), 'paused' => array( 'active', 'Resume' ), 'complete' => array( 'active', 'Reopen' ) ) as $from => [ $to, $lbl ] ) {
|
||||
if ( $g['status'] === $from ) {
|
||||
Admin::form( 'sg_goal_status', array( 'goal_id' => $gid, 'status' => $to ), 'sg-inline' );
|
||||
@@ -80,11 +88,16 @@ final class GoalsPage {
|
||||
return;
|
||||
}
|
||||
$cur = $g ? Format::currency( $g['currency'] ) : Admin::currency();
|
||||
$tiered = $id && (bool) ( new TierRepository() )->forGoal( $id );
|
||||
Admin::open( $g ? 'Edit goal' : 'New goal' );
|
||||
Admin::form( 'sg_goal_save', array( 'goal_id' => $id ) );
|
||||
echo '<table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sg_title">Title</label></th><td><input type="text" required maxlength="190" id="sg_title" name="title" class="regular-text" value="' . esc_attr( (string) ( $g['title'] ?? '' ) ) . '"></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" required inputmode="decimal" id="sg_target" name="target" class="small-text" value="' . esc_attr( $g ? Format::decimal( (int) $g['target_minor'], $cur ) : '' ) . '"></td></tr>';
|
||||
if ( $tiered ) {
|
||||
echo '<tr><th scope="row">Target (' . esc_html( $cur ) . ')</th><td><strong>' . esc_html( Format::money( (int) $g['target_minor'], $cur ) ) . '</strong> <span class="description">Set automatically from your highest tier. To change it, <a href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'tiers', 'goal' => $id ) ) ) . '">edit the tiers</a>.</span></td></tr>';
|
||||
} else {
|
||||
echo '<tr><th scope="row"><label for="sg_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" required inputmode="decimal" id="sg_target" name="target" class="small-text" value="' . esc_attr( $g ? Format::decimal( (int) $g['target_minor'], $cur ) : '' ) . '"></td></tr>';
|
||||
}
|
||||
echo '<tr><th scope="row">Currency</th><td><strong>' . esc_html( $cur ) . '</strong> <span class="description">One currency is used across the whole site. Change it in <a href="' . esc_url( Admin::url( 'streamgoals-settings' ) ) . '">Settings</a> (applies to new goals only).</span></td></tr>';
|
||||
$fmt = static fn( ?string $utc ): string => $utc ? get_date_from_gmt( $utc, 'Y-m-d\TH:i' ) : '';
|
||||
echo '<tr><th scope="row"><label for="sg_start">Starts</label></th><td><input type="datetime-local" id="sg_start" name="starts_at" value="' . esc_attr( $fmt( $g['starts_at'] ?? null ) ) . '"> <span class="description">Optional. Your site time zone. Empty = starts immediately.</span></td></tr>';
|
||||
@@ -116,10 +129,12 @@ final class GoalsPage {
|
||||
$cur = $old ? Format::currency( $old['currency'] ) : Admin::currency();
|
||||
$title = Input::text( $post['title'] ?? '', 190 );
|
||||
$tgt = Input::amountToMinor( $post['target'] ?? '', $cur );
|
||||
// A goal with tiers has a derived target (its highest tier): never taken from the form.
|
||||
$tiered = $id && ( new TierRepository() )->forGoal( $id );
|
||||
if ( '' === $title ) {
|
||||
Admin::redirect( $back, 'error', 'Please give the goal a title.' );
|
||||
}
|
||||
if ( null === $tgt || $tgt <= 0 ) {
|
||||
if ( ! $tiered && ( null === $tgt || $tgt <= 0 ) ) {
|
||||
Admin::redirect( $back, 'error', 'Please enter a target greater than zero, for example 250.00.' );
|
||||
}
|
||||
$startRaw = Input::text( $post['starts_at'] ?? '', 20 );
|
||||
@@ -133,6 +148,9 @@ final class GoalsPage {
|
||||
Admin::redirect( $back, 'error', 'The end must be after the start.' );
|
||||
}
|
||||
$data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1, 'close_at_target' => \StreamGoals\Core\GoalTargetPolicy::flagFromPost( $post['close_at_target'] ?? null ) );
|
||||
if ( $tiered ) {
|
||||
unset( $data['target_minor'] );
|
||||
}
|
||||
if ( $id ) {
|
||||
Store::goals()->update( $id, $data );
|
||||
} else {
|
||||
@@ -171,6 +189,125 @@ final class GoalsPage {
|
||||
Admin::redirect( Admin::url(), 'success', 'Goal deleted.' );
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- tiers */
|
||||
|
||||
private static function tiersUrl( int $goalId, array $extra = array() ): string {
|
||||
return Admin::url( Admin::HOME, array_merge( array( 'view' => 'tiers', 'goal' => $goalId ), $extra ) );
|
||||
}
|
||||
|
||||
private static function renderTiers( int $goalId ): void {
|
||||
$g = Store::goals()->find( $goalId );
|
||||
if ( ! $g ) {
|
||||
Admin::open( 'Goal not found' );
|
||||
echo '<p><a href="' . esc_url( Admin::url() ) . '">Back to goals</a></p>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
$cur = Format::currency( $g['currency'] );
|
||||
$repo = new TierRepository();
|
||||
$tiers = $repo->forGoal( $goalId );
|
||||
$raised = Store::goals()->raised_minor( $goalId );
|
||||
Admin::open( 'Tiers for "' . (string) $g['title'] . '"' );
|
||||
echo '<p><a href="' . esc_url( Admin::url() ) . '">← Back to goals</a></p>';
|
||||
echo '<p class="sg-lead">Tiers turn one goal into a ladder of milestones. Each tier has a target and something you unlock or give away. When your total reaches a tier\'s target, that tier unlocks and the goal bar moves on to the next one. The goal\'s final target is your highest tier.</p>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Your tiers</h2>';
|
||||
echo '<p class="description">Raised so far: <strong>' . esc_html( Format::money( $raised, $cur ) ) . '</strong>. Targets are cumulative totals, not extra amounts: a tier at ' . esc_html( Format::money( 25000, $cur ) ) . ' unlocks when the goal total reaches ' . esc_html( Format::money( 25000, $cur ) ) . '.</p>';
|
||||
if ( ! $tiers ) {
|
||||
echo '<p>No tiers yet. This goal works as a single target until you add one.</p>';
|
||||
} else {
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>#</th><th>Unlock</th><th>Target</th><th>Status</th><th>Actions</th></tr></thead><tbody>';
|
||||
foreach ( TierPolicy::sorted( $tiers ) as $i => $t ) {
|
||||
$tid = (int) $t['id'];
|
||||
$status = TierPolicy::status( $tiers, $t );
|
||||
$label = 'reached' === $status ? 'Reached on ' . get_date_from_gmt( (string) $t['reached_at'], 'Y-m-d H:i' ) : ( 'current' === $status ? 'Current' : 'Upcoming' );
|
||||
echo '<tr><td>' . (int) ( $i + 1 ) . '</td><td><strong>' . esc_html( $t['title'] ) . '</strong>';
|
||||
if ( '' !== $t['description'] ) {
|
||||
echo '<br><span class="description">' . esc_html( $t['description'] ) . '</span>';
|
||||
}
|
||||
echo '</td><td>' . esc_html( Format::money( (int) $t['target_minor'], $cur ) ) . '</td>';
|
||||
echo '<td><span class="sg-badge sg-' . ( 'reached' === $status ? 'complete' : ( 'current' === $status ? 'active' : 'paused' ) ) . '">' . esc_html( $label ) . '</span></td><td class="sg-actions">';
|
||||
echo '<a class="button" href="' . esc_url( self::tiersUrl( $goalId, array( 'tier' => $tid ) ) ) . '#sg-tier-form">Edit</a> ';
|
||||
Admin::form( 'sg_tier_delete', array( 'goal_id' => $goalId, 'tier_id' => $tid ), 'sg-inline sg-confirm' );
|
||||
echo '<button class="button button-link-delete" data-confirm="Delete this tier?">Delete</button></form></td></tr>';
|
||||
}
|
||||
echo '</tbody></table>';
|
||||
}
|
||||
echo '</div>';
|
||||
|
||||
$editId = Admin::get_int( 'tier' );
|
||||
$edit = $editId ? $repo->find( $editId ) : null;
|
||||
if ( $edit && (int) $edit['goal_id'] !== $goalId ) {
|
||||
$edit = null;
|
||||
}
|
||||
$locked = $edit && TierPolicy::isReached( $edit );
|
||||
$min = Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
|
||||
echo '<div class="sg-card" id="sg-tier-form"><h2>' . ( $edit ? 'Edit tier' : 'Add a tier' ) . '</h2>';
|
||||
Admin::form( 'sg_tier_save', array( 'goal_id' => $goalId, 'tier_id' => $edit ? (int) $edit['id'] : 0 ) );
|
||||
echo '<table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sg_t_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" ' . ( $locked ? 'disabled' : 'required' ) . ' inputmode="decimal" id="sg_t_target" name="target" class="small-text" value="' . esc_attr( $edit ? Format::decimal( (int) $edit['target_minor'], $cur ) : '' ) . '">';
|
||||
echo '<p class="description">' . ( $locked ? 'This tier has been reached, so its target is locked. You can still change its name and description.' : 'When your total reaches this amount, this tier unlocks and the goal bar moves on to the next one. Must be above what has been raised so far (' . esc_html( Format::money( $raised, $cur ) ) . ') and at least ' . esc_html( Format::money( $min, $cur ) ) . '.' ) . '</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_t_title">Item or unlock</label></th><td><input type="text" required maxlength="120" id="sg_t_title" name="title" class="regular-text" value="' . esc_attr( $edit ? (string) $edit['title'] : '' ) . '"><p class="description">What viewers get when this tier is reached, for example "New microphone". Up to 120 characters. Shown on your overlay and the donation form.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_t_desc">Description</label></th><td><input type="text" maxlength="255" id="sg_t_desc" name="description" class="large-text" value="' . esc_attr( $edit ? (string) $edit['description'] : '' ) . '"><p class="description">Optional. A short note, up to 255 characters.</p></td></tr>';
|
||||
echo '</table><p><button class="button button-primary">' . ( $edit ? 'Save tier' : 'Add tier' ) . '</button>';
|
||||
if ( $edit ) {
|
||||
echo ' <a class="button" href="' . esc_url( self::tiersUrl( $goalId ) ) . '">Cancel</a>';
|
||||
}
|
||||
echo '</p></form></div>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
public static function handleTierSave(): void {
|
||||
Admin::guard( 'sg_tier_save' );
|
||||
$post = Admin::post_raw();
|
||||
$goalId = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
|
||||
$tierId = isset( $post['tier_id'] ) ? absint( $post['tier_id'] ) : 0;
|
||||
$g = $goalId ? Store::goals()->find( $goalId ) : null;
|
||||
if ( ! $g ) {
|
||||
Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' );
|
||||
}
|
||||
$back = self::tiersUrl( $goalId, $tierId ? array( 'tier' => $tierId ) : array() );
|
||||
$cur = Format::currency( $g['currency'] );
|
||||
$repo = new TierRepository();
|
||||
$min = Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
|
||||
$res = TierPolicy::validate(
|
||||
$repo->forGoal( $goalId ),
|
||||
$tierId ?: null,
|
||||
Input::amountToMinor( $post['target'] ?? '', $cur ),
|
||||
Input::text( $post['title'] ?? '', 200 ),
|
||||
Input::text( $post['description'] ?? '', 400 ),
|
||||
Store::goals()->raised_minor( $goalId ),
|
||||
$min,
|
||||
Format::money( $min, $cur )
|
||||
);
|
||||
if ( null === $res['data'] ) {
|
||||
Admin::redirect( $back, 'error', (string) $res['error'] );
|
||||
}
|
||||
if ( $tierId ) {
|
||||
$repo->update( $tierId, $goalId, $res['data'] );
|
||||
} elseif ( $repo->create( $goalId, $res['data'] ) <= 0 ) {
|
||||
Admin::redirect( $back, 'error', 'The tier could not be saved. Another tier may already have that target.' );
|
||||
}
|
||||
$repo->syncGoalTarget( $goalId );
|
||||
$msg = 'Tier saved. The goal target is now ' . Format::money( TierPolicy::derivedGoalTarget( $repo->forGoal( $goalId ) ), $cur ) . '.';
|
||||
if ( 'complete' === ( $g['status'] ?? '' ) ) {
|
||||
$msg .= ' This goal is marked complete; use "Reopen" on the goals list if you want donations to continue.';
|
||||
}
|
||||
Admin::redirect( self::tiersUrl( $goalId ), 'success', $msg );
|
||||
}
|
||||
|
||||
public static function handleTierDelete(): void {
|
||||
Admin::guard( 'sg_tier_delete' );
|
||||
$post = Admin::post_raw();
|
||||
$goalId = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
|
||||
if ( $goalId && Store::goals()->find( $goalId ) ) {
|
||||
$repo = new TierRepository();
|
||||
$repo->delete( isset( $post['tier_id'] ) ? absint( $post['tier_id'] ) : 0, $goalId );
|
||||
$repo->syncGoalTarget( $goalId ); // no-op when the last tier was removed: the goal keeps its current target (editable again)
|
||||
}
|
||||
Admin::redirect( self::tiersUrl( $goalId ), 'success', 'Tier deleted.' );
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- rules */
|
||||
|
||||
private static function renderRules( int $goalId ): void {
|
||||
|
||||
@@ -4,6 +4,7 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Build;
|
||||
use StreamGoals\Overlay\Style;
|
||||
use StreamGoals\Rest\OverlayController;
|
||||
|
||||
@@ -73,6 +74,11 @@ final class OverlaysPage {
|
||||
self::urlList( true );
|
||||
echo '</div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Refresh overlays</h2>';
|
||||
Admin::form( 'sg_refresh_overlays', array(), 'sg-inline' );
|
||||
echo '<button type="submit" class="button">Refresh all overlays now</button></form>';
|
||||
echo '<p class="description">Reloads every open OBS source. Done automatically after a plugin update.</p></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Send a test donation</h2>';
|
||||
echo '<p>Shows a fake donation on the <strong>Donation alerts</strong> overlay so you can check your OBS setup. Open the alerts preview above (or have OBS running) first, then press the button; the alert appears within a few seconds.</p>';
|
||||
echo '<p class="description"><strong>How tests are kept out of your numbers:</strong> test donations are not attached to any goal, so they never count towards raised totals, timers or counters. They are excluded from the CSV export, and marked <em>TEST</em> in the Donations list. Test donations are kept in the database until you delete them below.</p>';
|
||||
@@ -105,6 +111,12 @@ final class OverlaysPage {
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', $n . ' test donation(s) deleted.' );
|
||||
}
|
||||
|
||||
public static function handleRefreshAll(): void {
|
||||
Admin::guard( 'sg_refresh_overlays' );
|
||||
Build::bump();
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', 'All open overlays will reload within a few seconds.' );
|
||||
}
|
||||
|
||||
public static function handleRegenerate(): void {
|
||||
Admin::guard( 'sg_regen_token' );
|
||||
Settings::update( array( 'overlay_token' => bin2hex( random_bytes( 16 ) ) ) );
|
||||
|
||||
@@ -34,6 +34,7 @@ final class SettingsPage {
|
||||
}
|
||||
echo '</select><p class="description">One currency for the whole site. It applies to goals you create from now on; existing goals keep their currency. Check the fixed fee below after changing it.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_min">Minimum donation (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_min" name="min_donation" class="small-text" inputmode="decimal" value="' . esc_attr( Format::decimal( \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ), $cur ) ) . '"> <span class="description">At least ' . esc_html( Format::money( \StreamGoals\Core\Settings::HARD_MIN_MINOR, $cur ) ) . '. Visitors cannot donate less than this.</span></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_notice">Notice under the donation form</label></th><td><input type="text" id="sg_notice" name="donation_notice" class="large-text" maxlength="200" value="' . esc_attr( (string) $s['donation_notice'] ) . '"><p class="description">Shown right under the PayPal buttons so donors see it before paying. Plain text, up to 200 characters. The default says donations are non-refundable. Leave it empty to hide the notice.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_len">Longest message</label></th><td><input type="number" id="sg_len" name="message_max_length" min="0" max="500" class="small-text" value="' . (int) $s['message_max_length'] . '"> characters <span class="description">(0 to 500; 0 = no messages)</span></td></tr>';
|
||||
echo '<tr><th scope="row">Names</th><td><fieldset>';
|
||||
foreach ( self::POLICIES as $k => $l ) {
|
||||
@@ -147,6 +148,7 @@ final class SettingsPage {
|
||||
}
|
||||
$upd['funding_card'] = ! empty( $post['funding_card'] );
|
||||
$upd['funding_paylater'] = ! empty( $post['funding_paylater'] );
|
||||
$upd['donation_notice'] = Input::text( $post['donation_notice'] ?? '', 200 );
|
||||
$upd['moderate_messages'] = ! empty( $post['moderate_messages'] );
|
||||
$upd['profanity_filter'] = ! empty( $post['profanity_filter'] );
|
||||
$upd['profanity_use_builtin'] = ! empty( $post['profanity_use_builtin'] );
|
||||
|
||||
@@ -87,6 +87,7 @@ final class Store {
|
||||
self::deleteRule( (int) $r['id'], $goalId );
|
||||
}
|
||||
$wpdb->delete( self::t( 'state' ), array( 'goal_id' => $goalId ), array( '%d' ) );
|
||||
$wpdb->delete( self::t( 'goal_tiers' ), array( 'goal_id' => $goalId ), array( '%d' ) );
|
||||
return self::goals()->delete( $goalId );
|
||||
}
|
||||
|
||||
|
||||
@@ -13,8 +13,8 @@ final class AlertMedia {
|
||||
* @param array<string,mixed> $row Donation row (goal_id, base_minor).
|
||||
* @param array<int,array<string,mixed>> $defs Raw alert definitions.
|
||||
* @param array<int,array{action_id:int,amount_minor:int,title:string}> $triggered Rewards this donation triggered.
|
||||
* @param callable(int):?array{url:string,mime:string} $attachment
|
||||
* @return array{visual:?array{type:string,url:string},sound:?array{url:string},volume:int,duration_ms:int,message:?string}|null
|
||||
* @param callable(int):?array{url:string,mime:string,v?:int,modified?:string} $attachment
|
||||
* @return array{visual:?array{type:string,url:string},sound:?array{url:string},volume:int,duration_ms:int,message:?string,frameless:bool}|null
|
||||
*/
|
||||
public static function build( array $row, string $name, string $amountDisplay, array $defs, array $triggered, callable $attachment ): ?array {
|
||||
if ( ! $defs ) {
|
||||
@@ -36,13 +36,15 @@ final class AlertMedia {
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public static function fromDef( array $def, string $name, string $amountDisplay, array $triggered, callable $attachment ): ?array {
|
||||
$visual = null;
|
||||
$visual = null;
|
||||
$frameless = false;
|
||||
$vid = (int) ( $def['visual_id'] ?? 0 );
|
||||
if ( $vid > 0 ) {
|
||||
$a = self::lookup( $attachment, $vid );
|
||||
$type = $a ? Media::visualType( $a['mime'] ) : null;
|
||||
if ( $a && $type ) {
|
||||
$visual = array( 'type' => $type, 'url' => $a['url'] );
|
||||
$frameless = ! empty( $def['frameless'] );
|
||||
}
|
||||
}
|
||||
$sound = null;
|
||||
@@ -81,6 +83,7 @@ final class AlertMedia {
|
||||
'volume' => Media::clampVolume( $def['volume'] ?? 80 ),
|
||||
'duration_ms' => $duration,
|
||||
'message' => '' === $msg ? null : $msg,
|
||||
'frameless' => $frameless,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -95,6 +98,11 @@ final class AlertMedia {
|
||||
return null;
|
||||
}
|
||||
$url = Media::safeUrl( $a['url'] ?? null );
|
||||
return null === $url ? null : array( 'url' => $url, 'mime' => (string) $a['mime'] );
|
||||
if ( null === $url ) {
|
||||
return null;
|
||||
}
|
||||
// Cache-bust suffix from server-side data only (file mtime / post_modified_gmt supplied by the lookup).
|
||||
$versioned = Media::safeUrl( Media::withVersion( $url, (int) ( $a['v'] ?? 0 ), isset( $a['modified'] ) && is_string( $a['modified'] ) ? $a['modified'] : null ) );
|
||||
return array( 'url' => $versioned ?? $url, 'mime' => (string) $a['mime'] );
|
||||
}
|
||||
}
|
||||
@@ -99,6 +99,7 @@ final class DefInput {
|
||||
if ( null === $sort ) {
|
||||
return $fail( 'The sort order must be a whole number from 0 to 99999.' );
|
||||
}
|
||||
$frameless = self::checkbox( $post['frameless'] ?? null ) ? 1 : 0;
|
||||
return array(
|
||||
'data' => array(
|
||||
'goal_id' => $goal,
|
||||
@@ -113,12 +114,18 @@ final class DefInput {
|
||||
'duration_ms' => $dur,
|
||||
'message' => $message,
|
||||
'sort' => $sort,
|
||||
'frameless' => $frameless,
|
||||
),
|
||||
'error' => null,
|
||||
'warnings' => $warnings,
|
||||
);
|
||||
}
|
||||
|
||||
/** HTML checkbox: present with a truthy value = on; absent or anything odd = off. */
|
||||
public static function checkbox( mixed $v ): bool {
|
||||
return is_scalar( $v ) && in_array( strtolower( trim( (string) $v ) ), array( '1', 'on', 'true', 'yes' ), true );
|
||||
}
|
||||
|
||||
/** @param string[] $warnings */
|
||||
private static function sizeWarning( array $a, string $what, bool $video, array &$warnings ): void {
|
||||
if ( (int) ( $a['size'] ?? 0 ) > Media::WARN_BYTES ) {
|
||||
|
||||
@@ -31,6 +31,7 @@ final class DefRepository {
|
||||
'volume' => (int) ( $r['volume'] ?? 80 ),
|
||||
'duration_ms' => (int) ( $r['duration_ms'] ?? 6000 ),
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'frameless' => (int) ( $r['frameless'] ?? 0 ) ? 1 : 0,
|
||||
'enabled' => (int) ( $r['enabled'] ?? 0 ),
|
||||
'sort' => (int) ( $r['sort'] ?? 0 ),
|
||||
'created_at' => (string) ( $r['created_at'] ?? '' ),
|
||||
@@ -57,13 +58,13 @@ final class DefRepository {
|
||||
|
||||
private const COLS = array(
|
||||
'goal_id' => '%d', 'trigger_type' => '%s', 'min_minor' => '%d', 'action_id' => '%d', 'title' => '%s', 'visual_id' => '%d',
|
||||
'visual_type' => '%s', 'sound_id' => '%d', 'volume' => '%d', 'duration_ms' => '%d', 'message' => '%s', 'sort' => '%d',
|
||||
'visual_type' => '%s', 'sound_id' => '%d', 'volume' => '%d', 'duration_ms' => '%d', 'message' => '%s', 'sort' => '%d', 'frameless' => '%d',
|
||||
);
|
||||
|
||||
public function create( array $d ): int {
|
||||
$row = array();
|
||||
foreach ( self::COLS as $k => $f ) {
|
||||
$row[ $k ] = $d[ $k ];
|
||||
$row[ $k ] = $d[ $k ] ?? ( '%d' === $f ? 0 : '' );
|
||||
}
|
||||
$row['enabled'] = 1;
|
||||
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
|
||||
@@ -74,7 +75,7 @@ final class DefRepository {
|
||||
public function update( int $id, array $d ): void {
|
||||
$row = array();
|
||||
foreach ( self::COLS as $k => $f ) {
|
||||
$row[ $k ] = $d[ $k ];
|
||||
$row[ $k ] = $d[ $k ] ?? ( '%d' === $f ? 0 : '' );
|
||||
}
|
||||
$this->db->update( $this->t(), $row, array( 'id' => $id ), array_values( self::COLS ), array( '%d' ) );
|
||||
}
|
||||
|
||||
@@ -66,6 +66,24 @@ final class Media {
|
||||
return is_numeric( $v ) ? max( 0, min( 100, (int) $v ) ) : $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends ?v=<timestamp> so a replaced file with the same name is fetched again. The timestamp comes from the
|
||||
* server (file mtime, else the attachment's post_modified_gmt), never from input. Unknown time = URL unchanged.
|
||||
*/
|
||||
public static function withVersion( string $url, int $fileMtime, ?string $postModifiedGmt = null ): string {
|
||||
$v = $fileMtime;
|
||||
if ( $v <= 0 && null !== $postModifiedGmt && preg_match( '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $postModifiedGmt ) ) {
|
||||
$t = strtotime( $postModifiedGmt . ' UTC' );
|
||||
$v = false === $t ? 0 : $t;
|
||||
}
|
||||
if ( $v <= 0 || str_contains( $url, '#' ) ) {
|
||||
return $url;
|
||||
}
|
||||
$base = preg_replace( '/([?&])v=[^&]*(&|$)/', '$1', $url ) ?? $url;
|
||||
$base = rtrim( $base, '?&' );
|
||||
return $base . ( str_contains( $base, '?' ) ? '&' : '?' ) . 'v=' . $v;
|
||||
}
|
||||
|
||||
/** Only plain http(s) URLs are ever handed to the overlay. */
|
||||
public static function safeUrl( mixed $url ): ?string {
|
||||
if ( ! is_string( $url ) || '' === $url || strlen( $url ) > 2000 || preg_match( '/[\x00-\x20\x7F"\'<>\\\\]/', $url ) ) {
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class Installer {
|
||||
|
||||
public const DB_VERSION = '3';
|
||||
public const DB_VERSION = '5';
|
||||
|
||||
public static function activate(): void {
|
||||
self::install_schema();
|
||||
@@ -138,11 +138,26 @@ final class Installer {
|
||||
message VARCHAR(255) NOT NULL DEFAULT '',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||
sort INT NOT NULL DEFAULT 0,
|
||||
frameless TINYINT(1) NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY goal_enabled (goal_id,enabled)
|
||||
) $c;" );
|
||||
|
||||
dbDelta( "CREATE TABLE {$p}goal_tiers (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
goal_id BIGINT UNSIGNED NOT NULL,
|
||||
target_minor BIGINT UNSIGNED NOT NULL,
|
||||
title VARCHAR(120) NOT NULL,
|
||||
description VARCHAR(255) NOT NULL DEFAULT '',
|
||||
reached_at DATETIME NULL,
|
||||
reached_donation_id BIGINT UNSIGNED NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY goal_target (goal_id,target_minor),
|
||||
KEY reached_donation (reached_donation_id)
|
||||
) $c;" );
|
||||
|
||||
update_option( 'sg_db_version', self::DB_VERSION );
|
||||
}
|
||||
}
|
||||
@@ -34,6 +34,7 @@ final class Settings {
|
||||
'profanity_words' => '', // streamer's extra words, one per line
|
||||
'message_max_length' => 200,
|
||||
'min_donation_minor' => 100,
|
||||
'donation_notice' => 'Donations are non-refundable.', // shown under the donation form; empty hides it
|
||||
'overlay_token' => '',
|
||||
'visitor_ip_header' => 'auto', // auto | '' (direct) | cloudflare | real_ip | forwarded (see Core\ClientIp)
|
||||
'funding_paylater' => false, // show PayPal "Pay Later" button
|
||||
|
||||
@@ -20,7 +20,7 @@ interface AlertMediaSource {
|
||||
/**
|
||||
* Server-side attachment lookup (the only place media URLs come from). Null when it is gone.
|
||||
*
|
||||
* @return array{url:string,mime:string}|null
|
||||
* @return array{url:string,mime:string,v?:int,modified?:string}|null (v = file mtime, modified = post_modified_gmt; used only for the ?v= cache-bust suffix)
|
||||
*/
|
||||
public function attachment( int $id ): ?array;
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/**
|
||||
* Overlay build id: plugin version + a manual "epoch". The overlay page embeds it, every overlay REST response
|
||||
* repeats it in a header, and a page that sees a different value reloads itself (OBS never does that on its own).
|
||||
*/
|
||||
final class Build {
|
||||
|
||||
public const HEADER = 'X-SG-Build';
|
||||
public const OPTION = 'sg_overlay_epoch';
|
||||
|
||||
/** Pure: the build id string for a version and epoch. Only [A-Za-z0-9._-] survive, so it is header- and attribute-safe. */
|
||||
public static function id( string $version, mixed $epoch ): string {
|
||||
$v = preg_replace( '/[^A-Za-z0-9._-]/', '', $version ) ?? '';
|
||||
return ( '' === $v ? '0' : $v ) . '-' . self::epochInt( $epoch );
|
||||
}
|
||||
|
||||
/** Pure: stored option value (anything) to a non-negative integer. */
|
||||
public static function epochInt( mixed $raw ): int {
|
||||
return ( is_int( $raw ) || ( is_string( $raw ) && ctype_digit( $raw ) && strlen( $raw ) < 15 ) ) ? max( 0, (int) $raw ) : 0;
|
||||
}
|
||||
|
||||
/** Pure: the epoch after a bump. Strictly increasing, never lower than the clock so a deleted option cannot repeat an old value. */
|
||||
public static function nextEpoch( mixed $current, int $now ): int {
|
||||
return max( self::epochInt( $current ) + 1, $now );
|
||||
}
|
||||
|
||||
/** Pure: response headers carrying the build id (merged into the existing ones; ETag semantics untouched). */
|
||||
public static function headers( string $build ): array {
|
||||
return array( self::HEADER => $build );
|
||||
}
|
||||
|
||||
public static function current(): string {
|
||||
return self::id( defined( 'STREAMGOALS_VERSION' ) ? (string) STREAMGOALS_VERSION : '', get_option( self::OPTION, 0 ) );
|
||||
}
|
||||
|
||||
/** Reloads every open overlay at its next poll. */
|
||||
public static function bump(): void {
|
||||
update_option( self::OPTION, self::nextEpoch( get_option( self::OPTION, 0 ), time() ), false );
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,8 @@ final class OverlayService {
|
||||
$gid = $goal ? (int) $goal['id'] : 0;
|
||||
switch ( $widget ) {
|
||||
case 'goal':
|
||||
return Payloads::goal( $goal, $goal ? $this->source->raisedMinor( $goal ) : 0 );
|
||||
$tiers = ( $gid && $this->source instanceof TiersSource ) ? $this->source->tiersFor( $gid ) : array();
|
||||
return Payloads::goal( $goal, $goal ? $this->source->raisedMinor( $goal ) : 0, $tiers ?: null );
|
||||
case 'timer':
|
||||
return Payloads::timer(
|
||||
$gid ? $this->source->stateValue( $gid, 'timer_ends_at' ) : null,
|
||||
@@ -55,9 +56,11 @@ final class OverlayService {
|
||||
$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();
|
||||
$tiers = ( ( $recent || null !== $since ) && $ids && $this->source instanceof TiersSource ) ? $this->source->tiersReachedFor( $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();
|
||||
$rows[ $i ]['tiers'] = $tiers[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
}
|
||||
$mediaFor = null;
|
||||
$defs = ( $recent || null !== $since ) ? $this->defs() : array();
|
||||
|
||||
@@ -4,6 +4,7 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Tiers\TierPolicy;
|
||||
|
||||
/**
|
||||
* Pure, WordPress-free payload builders. Everything returned here is public-safe.
|
||||
@@ -31,7 +32,10 @@ final class Payloads {
|
||||
return max( 0, min( 100, intdiv( max( 0, $raised ) * 100, $target ) ) );
|
||||
}
|
||||
|
||||
public static function goal( ?array $goal, int $raised ): array {
|
||||
/**
|
||||
* @param array<int,array<string,mixed>>|null $tiers Raw sg_goal_tiers rows; null/empty = an ordinary (untiered) goal, payload unchanged.
|
||||
*/
|
||||
public static function goal( ?array $goal, int $raised, ?array $tiers = null ): array {
|
||||
if ( null === $goal ) {
|
||||
return array( 'active' => false, 'title' => '', 'raised_minor' => 0, 'target_minor' => 0, 'percent' => 0,
|
||||
'currency' => 'USD', 'raised_display' => '', 'target_display' => '' );
|
||||
@@ -39,6 +43,9 @@ final class Payloads {
|
||||
$cur = strtoupper( (string) ( $goal['currency'] ?? 'USD' ) );
|
||||
$target = max( 0, (int) ( $goal['target_minor'] ?? 0 ) );
|
||||
$raised = max( 0, $raised );
|
||||
if ( $tiers ) {
|
||||
return self::tieredGoal( $goal, $raised, $cur, $tiers );
|
||||
}
|
||||
return array(
|
||||
'active' => true,
|
||||
'title' => (string) ( $goal['title'] ?? '' ),
|
||||
@@ -51,6 +58,40 @@ final class Payloads {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tiered goal: raised stays cumulative; target/percent describe the CURRENT tier (percent is within the tier).
|
||||
* When every tier is reached the bar is full at the top tier's target.
|
||||
*/
|
||||
private static function tieredGoal( array $goal, int $raised, string $cur, array $tiers ): array {
|
||||
$sorted = TierPolicy::sorted( $tiers );
|
||||
$current = TierPolicy::currentTier( $sorted );
|
||||
$all = null === $current;
|
||||
$target = $all ? TierPolicy::derivedGoalTarget( $sorted ) : max( 0, (int) $current['target_minor'] );
|
||||
$floor = TierPolicy::floorMinor( $sorted );
|
||||
return array(
|
||||
'active' => true,
|
||||
'title' => (string) ( $goal['title'] ?? '' ),
|
||||
'raised_minor' => $raised,
|
||||
'target_minor' => $target,
|
||||
'percent' => TierPolicy::percentFor( $sorted, $raised ),
|
||||
'currency' => $cur,
|
||||
'raised_display' => self::money( $raised, $cur ),
|
||||
'target_display' => self::money( $target, $cur ),
|
||||
'tiers' => array(
|
||||
'count' => count( $sorted ),
|
||||
'index' => TierPolicy::currentIndex( $sorted ),
|
||||
'current' => $all ? null : array(
|
||||
'title' => self::text( $current['title'] ?? '', 120 ),
|
||||
'description' => self::text( $current['description'] ?? '', 255 ),
|
||||
'target_minor' => $target,
|
||||
'target_display' => self::money( $target, $cur ),
|
||||
'floor_minor' => $floor,
|
||||
),
|
||||
'all_reached' => $all,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|null $endsAt sg_state `timer_ends_at` (epoch seconds, or a UTC datetime string).
|
||||
* @param string|null $pausedRemaining sg_state `paused_remaining` seconds; non-null means paused.
|
||||
@@ -132,6 +173,7 @@ final class Payloads {
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
|
||||
'actions' => self::actionEvents( $r['actions'] ?? array() ),
|
||||
'tiers' => self::tierEvents( $r['tiers'] ?? array() ),
|
||||
'media' => $mediaFor ? $mediaFor( $r, $pub, $disp ) : null,
|
||||
);
|
||||
}
|
||||
@@ -200,6 +242,27 @@ final class Payloads {
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tiers a donation unlocked, for the "TIER UNLOCKED" pill: [ {title} ]. At most 5, titles capped at 80 chars, blanks dropped.
|
||||
*
|
||||
* @param mixed $events
|
||||
* @return array<int,array{title:string}>
|
||||
*/
|
||||
public static function tierEvents( mixed $events ): array {
|
||||
$out = array();
|
||||
foreach ( is_array( $events ) ? $events : array() as $e ) {
|
||||
$title = self::text( is_array( $e ) ? ( $e['title'] ?? '' ) : '', 80 );
|
||||
if ( '' === $title ) {
|
||||
continue;
|
||||
}
|
||||
$out[] = array( 'title' => $title );
|
||||
if ( count( $out ) >= 5 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The on-stream reward menu for the active goal. Empty list means "render nothing".
|
||||
*
|
||||
|
||||
@@ -74,7 +74,7 @@ final class Router {
|
||||
<title>StreamGoals overlay</title>
|
||||
<link rel="stylesheet" href="<?php echo $asset( 'overlay.css' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>">
|
||||
</head>
|
||||
<body class="sg-theme-<?php echo esc_attr( $style['theme'] ); ?> sg-w-<?php echo esc_attr( $widget ); ?>" data-widget="<?php echo esc_attr( $widget ); ?>" data-endpoint="<?php echo esc_url( $endpoint ); ?>" data-poll="2500">
|
||||
<body class="sg-theme-<?php echo esc_attr( $style['theme'] ); ?> sg-w-<?php echo esc_attr( $widget ); ?>" data-widget="<?php echo esc_attr( $widget ); ?>" data-endpoint="<?php echo esc_url( $endpoint ); ?>" data-poll="2500" data-build="<?php echo esc_attr( Build::current() ); ?>">
|
||||
<main id="sg-root" aria-live="polite"></main>
|
||||
<script src="<?php echo $asset( 'overlay.js' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>"></script>
|
||||
</body>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** Optional capability: goal tiers (milestones). Sources without it behave as if no goal had tiers. */
|
||||
interface TiersSource {
|
||||
|
||||
/**
|
||||
* Tiers of a goal ordered by target ascending. Rows with keys id, target_minor, title, description, reached_at.
|
||||
*
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function tiersFor( int $goalId ): array;
|
||||
|
||||
/**
|
||||
* Tiers unlocked by each donation, ONE lookup for the whole page: donation id => [ {title} ].
|
||||
*
|
||||
* @param int[] $donationIds
|
||||
* @return array<int,array<int,array<string,mixed>>>
|
||||
*/
|
||||
public function tiersReachedFor( array $donationIds ): array;
|
||||
}
|
||||
@@ -4,9 +4,9 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource {
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource, TiersSource {
|
||||
|
||||
/** @var array<int,?array{url:string,mime:string}> */
|
||||
/** @var array<int,?array{url:string,mime:string,v:int,modified:string}> */
|
||||
private array $attachments = array();
|
||||
|
||||
private function t( string $name ): string {
|
||||
@@ -120,6 +120,14 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function tiersFor( int $goalId ): array {
|
||||
return ( new \StreamGoals\Tiers\TierRepository( $GLOBALS['wpdb'] ) )->forGoal( $goalId );
|
||||
}
|
||||
|
||||
public function tiersReachedFor( array $donationIds ): array {
|
||||
return ( new \StreamGoals\Tiers\TierRepository( $GLOBALS['wpdb'] ) )->reachedByDonation( $donationIds );
|
||||
}
|
||||
|
||||
public function alertDefs(): array {
|
||||
return ( new \StreamGoals\Alerts\DefRepository( $GLOBALS['wpdb'] ) )->enabled();
|
||||
}
|
||||
@@ -152,7 +160,9 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
|
||||
$mime = (string) get_post_mime_type( $id );
|
||||
$url = wp_get_attachment_url( $id );
|
||||
if ( \StreamGoals\Alerts\Media::isAllowed( $mime ) && is_string( $url ) && '' !== $url ) {
|
||||
$out = array( 'url' => $url, 'mime' => $mime );
|
||||
$path = get_attached_file( $id );
|
||||
$mtime = ( is_string( $path ) && is_file( $path ) ) ? (int) @filemtime( $path ) : 0;
|
||||
$out = array( 'url' => $url, 'mime' => $mime, 'v' => $mtime, 'modified' => (string) get_post_field( 'post_modified_gmt', $id ) );
|
||||
}
|
||||
}
|
||||
return $this->attachments[ $id ] = $out;
|
||||
|
||||
@@ -93,6 +93,13 @@ final class DonationStore {
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: Recorder failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
}
|
||||
// Goal tiers: unlock every tier this donation reaches. MUST run before the close-at-target check below
|
||||
// (the final tier's target is the goal target). Own try/catch; never throws, never delays a capture.
|
||||
try {
|
||||
\StreamGoals\Tiers\Recorder::forDonation( $id );
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: tier unlock failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
}
|
||||
self::close_goal_if_target_reached( $id );
|
||||
}
|
||||
|
||||
|
||||
@@ -162,7 +162,8 @@ final class DonateController {
|
||||
if ( $pinned && (int) $g['id'] !== $pinned ) {
|
||||
continue;
|
||||
}
|
||||
$goals[] = array(
|
||||
$next = self::next_unlock( $g );
|
||||
$goals[] = ( null === $next ? array() : array( 'nextUnlock' => $next ) ) + array(
|
||||
'id' => (int) $g['id'],
|
||||
'title' => (string) $g['title'],
|
||||
'currency' => strtoupper( (string) $g['currency'] ),
|
||||
@@ -187,6 +188,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'] ),
|
||||
'notice' => (string) ( $s['donation_notice'] ?? '' ),
|
||||
'disableFunding' => array_values( array_filter( array( empty( $s['funding_paylater'] ) ? 'paylater' : '', empty( $s['funding_card'] ) ? 'card' : '' ) ) ),
|
||||
'goals' => $goals,
|
||||
'i18n' => array(
|
||||
@@ -206,6 +208,8 @@ final class DonateController {
|
||||
'customPlaceholder' => __( 'Other amount', 'streamgoals-donate' ),
|
||||
/* translators: %s: formatted amount, e.g. $5.00 */
|
||||
'everyLabel' => __( 'Every %s', 'streamgoals-donate' ),
|
||||
/* translators: 1: item/unlock title, 2: formatted amount still needed, e.g. $106.00 */
|
||||
'nextUnlock' => __( 'Next unlock: %1$s — %2$s to go', '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' ),
|
||||
@@ -222,6 +226,27 @@ final class DonateController {
|
||||
|
||||
/* ------------------------------------------------------------- Helpers */
|
||||
|
||||
/**
|
||||
* "Next unlock" hint for a tiered goal: the current (first unreached) tier's title and the amount still needed, in minor units.
|
||||
* Null for goals without tiers or with every tier reached. Computed when the page renders.
|
||||
*
|
||||
* @return array{title:string,remaining_minor:int}|null
|
||||
*/
|
||||
private static function next_unlock( array $goal ): ?array {
|
||||
try {
|
||||
global $wpdb;
|
||||
$tiers = ( new \StreamGoals\Tiers\TierRepository( $wpdb ) )->forGoal( (int) $goal['id'] );
|
||||
$cur = $tiers ? \StreamGoals\Tiers\TierPolicy::currentTier( $tiers ) : null;
|
||||
if ( null === $cur ) {
|
||||
return null;
|
||||
}
|
||||
$raised = ( new \StreamGoals\Core\GoalRepository( $wpdb ) )->raised_minor( (int) $goal['id'] );
|
||||
return array( 'title' => (string) $cur['title'], 'remaining_minor' => max( 1, (int) $cur['target_minor'] - $raised ) );
|
||||
} catch ( \Throwable $e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
|
||||
@@ -4,6 +4,7 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Rest;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Build;
|
||||
use StreamGoals\Overlay\OverlayService;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\Overlay\Router;
|
||||
@@ -56,7 +57,7 @@ final class OverlayController {
|
||||
}
|
||||
|
||||
$etag = Payloads::etag( $payload, $service->etagSalt( (string) $req['widget'] ) );
|
||||
$headers = array( 'ETag' => $etag, 'Cache-Control' => 'private, max-age=1, must-revalidate', 'X-Robots-Tag' => 'noindex' );
|
||||
$headers = array( 'ETag' => $etag, 'Cache-Control' => 'private, max-age=1, must-revalidate', 'X-Robots-Tag' => 'noindex' ) + Build::headers( Build::current() );
|
||||
$inm = (string) $req->get_header( 'if_none_match' );
|
||||
if ( '' !== $inm && in_array( $etag, array_map( 'trim', explode( ',', str_replace( 'W/', '', $inm ) ) ), true ) ) {
|
||||
$res = new \WP_REST_Response( null, 304 );
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tiers;
|
||||
|
||||
/** Unlocks the tiers a completed donation reaches. Runs BEFORE the "end at target" check. */
|
||||
final class Recorder {
|
||||
|
||||
/**
|
||||
* Never throws. Idempotent (atomic UPDATE ... WHERE reached_at IS NULL per tier). Test donations (goal_id 0) are skipped.
|
||||
*
|
||||
* @return int[] ids of the tiers this call unlocked.
|
||||
*/
|
||||
public static function forDonation( int $donationId ): array {
|
||||
try {
|
||||
global $wpdb;
|
||||
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT id, goal_id, status FROM ' . $wpdb->prefix . 'sg_donations WHERE id = %d', $donationId ), ARRAY_A );
|
||||
if ( ! is_array( $row ) || 'completed' !== ( $row['status'] ?? '' ) || (int) $row['goal_id'] <= 0 ) {
|
||||
return array();
|
||||
}
|
||||
$goalId = (int) $row['goal_id'];
|
||||
$repo = new TierRepository( $wpdb );
|
||||
if ( ! $repo->forGoal( $goalId ) ) {
|
||||
return array();
|
||||
}
|
||||
$raised = ( new \StreamGoals\Core\GoalRepository( $wpdb ) )->raised_minor( $goalId );
|
||||
return $repo->markReached( $goalId, $raised, $donationId );
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: tier unlock failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return array();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tiers;
|
||||
|
||||
/**
|
||||
* Pure rules for goal tiers (milestones). No WordPress / database access.
|
||||
* A tier row is an array with keys: id, target_minor, title, description, reached_at (null|string), reached_donation_id.
|
||||
*/
|
||||
final class TierPolicy {
|
||||
|
||||
public const TITLE_MAX = 120;
|
||||
public const DESC_MAX = 255;
|
||||
|
||||
/** Tiers ordered by target ascending (ties by id). Non-array entries are dropped. @return array[] */
|
||||
public static function sorted( array $tiers ): array {
|
||||
$tiers = array_values( array_filter( $tiers, 'is_array' ) );
|
||||
usort(
|
||||
$tiers,
|
||||
static fn( array $a, array $b ): int => ( (int) $a['target_minor'] <=> (int) $b['target_minor'] ) ?: ( (int) ( $a['id'] ?? 0 ) <=> (int) ( $b['id'] ?? 0 ) )
|
||||
);
|
||||
return $tiers;
|
||||
}
|
||||
|
||||
public static function isReached( array $tier ): bool {
|
||||
return ! empty( $tier['reached_at'] );
|
||||
}
|
||||
|
||||
/** The first tier (by target) that is not reached yet, or null (no tiers, or all reached). */
|
||||
public static function currentTier( array $tiers ): ?array {
|
||||
foreach ( self::sorted( $tiers ) as $t ) {
|
||||
if ( ! self::isReached( $t ) ) {
|
||||
return $t;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** True when there is at least one tier and every tier is reached. */
|
||||
public static function allReached( array $tiers ): bool {
|
||||
return $tiers && null === self::currentTier( $tiers );
|
||||
}
|
||||
|
||||
/** 1-based position of the current tier; when all are reached, the count; 0 without tiers. */
|
||||
public static function currentIndex( array $tiers ): int {
|
||||
$sorted = self::sorted( $tiers );
|
||||
foreach ( $sorted as $i => $t ) {
|
||||
if ( ! self::isReached( $t ) ) {
|
||||
return $i + 1;
|
||||
}
|
||||
}
|
||||
return count( $sorted );
|
||||
}
|
||||
|
||||
/** Start of the current tier's range: the previous tier's target (0 for the first / when none is current). */
|
||||
public static function floorMinor( array $tiers ): int {
|
||||
$prev = 0;
|
||||
foreach ( self::sorted( $tiers ) as $t ) {
|
||||
if ( ! self::isReached( $t ) ) {
|
||||
return $prev;
|
||||
}
|
||||
$prev = (int) $t['target_minor'];
|
||||
}
|
||||
return $prev; // all reached: the top tier's target
|
||||
}
|
||||
|
||||
/** Progress inside a tier, 0..100 (clamped). Below the floor = 0, at or above the target = 100. */
|
||||
public static function percent( int $raised, int $floor, int $target ): int {
|
||||
if ( $target <= $floor ) {
|
||||
return $raised >= $target && $target > 0 ? 100 : 0;
|
||||
}
|
||||
$p = intdiv( ( $raised - $floor ) * 100, $target - $floor );
|
||||
return max( 0, min( 100, $p ) );
|
||||
}
|
||||
|
||||
/** Percent within the current tier for the given tiers and raised total (100 when all reached, 0 without tiers). */
|
||||
public static function percentFor( array $tiers, int $raised ): int {
|
||||
$cur = self::currentTier( $tiers );
|
||||
if ( null === $cur ) {
|
||||
return $tiers ? 100 : 0;
|
||||
}
|
||||
return self::percent( $raised, self::floorMinor( $tiers ), (int) $cur['target_minor'] );
|
||||
}
|
||||
|
||||
/** Money still needed to reach the current tier (0 when none). */
|
||||
public static function remainingMinor( array $tiers, int $raised ): int {
|
||||
$cur = self::currentTier( $tiers );
|
||||
return null === $cur ? 0 : max( 0, (int) $cur['target_minor'] - $raised );
|
||||
}
|
||||
|
||||
/** Every unreached tier whose target is at or below the raised total, in target order. A big donation can unlock several. @return array[] */
|
||||
public static function newlyReached( array $tiers, int $raised ): array {
|
||||
$out = array();
|
||||
foreach ( self::sorted( $tiers ) as $t ) {
|
||||
if ( ! self::isReached( $t ) && (int) $t['target_minor'] <= $raised ) {
|
||||
$out[] = $t;
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** The goal's target when it has tiers: the highest tier target (0 when no tiers). */
|
||||
public static function derivedGoalTarget( array $tiers ): int {
|
||||
$max = 0;
|
||||
foreach ( $tiers as $t ) {
|
||||
$max = max( $max, (int) ( $t['target_minor'] ?? 0 ) );
|
||||
}
|
||||
return $max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a tier form submission.
|
||||
*
|
||||
* @param array $tiers All tiers of the goal (including the one being edited).
|
||||
* @param int|null $editId Tier id when editing, null when adding.
|
||||
* @param int|null $target Parsed target in minor units (null = not a valid amount).
|
||||
* @param int $raised Goal raised total (minor units).
|
||||
* @param int $minMinor Settings::effectiveMin().
|
||||
* @return array{data:?array{target_minor:int,title:string,description:string},error:?string}
|
||||
*/
|
||||
public static function validate( array $tiers, ?int $editId, ?int $target, string $title, string $description, int $raised, int $minMinor, string $minLabel = '' ): array {
|
||||
$fail = static fn( string $m ): array => array( 'data' => null, 'error' => $m );
|
||||
$title = trim( $title );
|
||||
$desc = trim( $description );
|
||||
if ( '' === $title ) {
|
||||
return $fail( 'Please name what unlocks at this tier, for example "New microphone".' );
|
||||
}
|
||||
if ( self::len( $title ) > self::TITLE_MAX ) {
|
||||
return $fail( 'The title can be at most ' . self::TITLE_MAX . ' characters.' );
|
||||
}
|
||||
if ( self::len( $desc ) > self::DESC_MAX ) {
|
||||
return $fail( 'The description can be at most ' . self::DESC_MAX . ' characters.' );
|
||||
}
|
||||
$existing = null;
|
||||
if ( null !== $editId ) {
|
||||
foreach ( $tiers as $t ) {
|
||||
if ( (int) ( $t['id'] ?? 0 ) === $editId ) {
|
||||
$existing = $t;
|
||||
}
|
||||
}
|
||||
if ( null === $existing ) {
|
||||
return $fail( 'That tier no longer exists.' );
|
||||
}
|
||||
}
|
||||
if ( null !== $existing && self::isReached( $existing ) ) {
|
||||
// Reached tiers: the target is locked, only the text can change.
|
||||
return array( 'data' => array( 'target_minor' => (int) $existing['target_minor'], 'title' => $title, 'description' => $desc ), 'error' => null );
|
||||
}
|
||||
if ( null === $target || $target <= 0 ) {
|
||||
return $fail( 'Please enter a target greater than zero, for example 250.00.' );
|
||||
}
|
||||
if ( $target < $minMinor ) {
|
||||
return $fail( 'The target must be at least the minimum donation' . ( '' !== $minLabel ? ' (' . $minLabel . ')' : '' ) . '.' );
|
||||
}
|
||||
foreach ( $tiers as $t ) {
|
||||
if ( (int) ( $t['id'] ?? 0 ) !== (int) $editId && (int) $t['target_minor'] === $target ) {
|
||||
return $fail( 'Another tier already has that target. Each tier needs its own amount.' );
|
||||
}
|
||||
}
|
||||
$unchanged = null !== $existing && (int) $existing['target_minor'] === $target;
|
||||
if ( ! $unchanged && $target <= $raised ) {
|
||||
return $fail( 'This goal has already raised more than that, so the tier would unlock instantly. Choose a target above the current total.' );
|
||||
}
|
||||
return array( 'data' => array( 'target_minor' => $target, 'title' => $title, 'description' => $desc ), 'error' => null );
|
||||
}
|
||||
|
||||
/** Display status of a tier given the sorted list: 'reached' | 'current' | 'upcoming'. */
|
||||
public static function status( array $tiers, array $tier ): string {
|
||||
if ( self::isReached( $tier ) ) {
|
||||
return 'reached';
|
||||
}
|
||||
$cur = self::currentTier( $tiers );
|
||||
return $cur && (int) $cur['id'] === (int) $tier['id'] ? 'current' : 'upcoming';
|
||||
}
|
||||
|
||||
private static function len( string $s ): int {
|
||||
return function_exists( 'mb_strlen' ) ? mb_strlen( $s ) : strlen( $s );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tiers;
|
||||
|
||||
/** $wpdb access to sg_goal_tiers (and keeping sg_goals.target_minor in step). */
|
||||
final class TierRepository {
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** @return array{id:int,goal_id:int,target_minor:int,title:string,description:string,reached_at:?string,reached_donation_id:?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 ),
|
||||
'target_minor' => (int) ( $r['target_minor'] ?? 0 ),
|
||||
'title' => (string) ( $r['title'] ?? '' ),
|
||||
'description' => (string) ( $r['description'] ?? '' ),
|
||||
'reached_at' => isset( $r['reached_at'] ) && '' !== (string) $r['reached_at'] ? (string) $r['reached_at'] : null,
|
||||
'reached_donation_id' => isset( $r['reached_donation_id'] ) && null !== $r['reached_donation_id'] ? (int) $r['reached_donation_id'] : null,
|
||||
'created_at' => (string) ( $r['created_at'] ?? '' ),
|
||||
);
|
||||
}
|
||||
|
||||
/** Tiers of a goal ordered by target ascending. @return array[] */
|
||||
public function forGoal( int $goalId ): array {
|
||||
$rows = $this->db->get_results(
|
||||
$this->db->prepare( 'SELECT * FROM ' . $this->t( 'goal_tiers' ) . ' WHERE goal_id = %d ORDER BY target_minor ASC, id ASC', $goalId ),
|
||||
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( 'goal_tiers' ) . ' WHERE id = %d', $id ), ARRAY_A );
|
||||
return $row ? self::cast( $row ) : null;
|
||||
}
|
||||
|
||||
/** Tier counts per goal id (one query) for the goals list. @return array<int,int> */
|
||||
public function countsByGoal(): array {
|
||||
$rows = $this->db->get_results( 'SELECT goal_id, COUNT(*) AS n FROM ' . $this->t( 'goal_tiers' ) . ' GROUP BY goal_id', ARRAY_A );
|
||||
$out = array();
|
||||
foreach ( (array) $rows as $r ) {
|
||||
$out[ (int) $r['goal_id'] ] = (int) $r['n'];
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** @param array{target_minor:int,title:string,description:string} $d @return int new id (0 on failure, e.g. duplicate target) */
|
||||
public function create( int $goalId, array $d ): int {
|
||||
$ok = $this->db->insert(
|
||||
$this->t( 'goal_tiers' ),
|
||||
array(
|
||||
'goal_id' => $goalId,
|
||||
'target_minor' => (int) $d['target_minor'],
|
||||
'title' => (string) $d['title'],
|
||||
'description' => (string) $d['description'],
|
||||
'created_at' => gmdate( 'Y-m-d H:i:s' ),
|
||||
),
|
||||
array( '%d', '%d', '%s', '%s', '%s' )
|
||||
);
|
||||
return $ok ? (int) $this->db->insert_id : 0;
|
||||
}
|
||||
|
||||
public function update( int $id, int $goalId, array $d ): void {
|
||||
$this->db->update(
|
||||
$this->t( 'goal_tiers' ),
|
||||
array( 'target_minor' => (int) $d['target_minor'], 'title' => (string) $d['title'], 'description' => (string) $d['description'] ),
|
||||
array( 'id' => $id, 'goal_id' => $goalId ),
|
||||
array( '%d', '%s', '%s' ),
|
||||
array( '%d', '%d' )
|
||||
);
|
||||
}
|
||||
|
||||
public function delete( int $id, int $goalId ): void {
|
||||
$this->db->delete( $this->t( 'goal_tiers' ), array( 'id' => $id, 'goal_id' => $goalId ), array( '%d', '%d' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark every unreached tier of the goal with target <= $raised as reached by $donationId. One atomic
|
||||
* UPDATE per tier (WHERE reached_at IS NULL): replays and concurrent callers cannot re-mark a tier.
|
||||
*
|
||||
* @return int[] ids of the tiers THIS call marked.
|
||||
*/
|
||||
public function markReached( int $goalId, int $raised, int $donationId ): array {
|
||||
$marked = array();
|
||||
if ( $goalId <= 0 || $donationId <= 0 ) {
|
||||
return $marked;
|
||||
}
|
||||
$now = gmdate( 'Y-m-d H:i:s' );
|
||||
foreach ( TierPolicy::newlyReached( $this->forGoal( $goalId ), $raised ) as $tier ) {
|
||||
$n = $this->db->query(
|
||||
$this->db->prepare(
|
||||
'UPDATE ' . $this->t( 'goal_tiers' ) . ' SET reached_at = %s, reached_donation_id = %d WHERE id = %d AND reached_at IS NULL',
|
||||
$now,
|
||||
$donationId,
|
||||
(int) $tier['id']
|
||||
)
|
||||
);
|
||||
if ( 1 === (int) $n ) {
|
||||
$marked[] = (int) $tier['id'];
|
||||
}
|
||||
}
|
||||
return $marked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tiers unlocked by each donation, one query for the whole page: donation id => [ {title}, ... ] in target order.
|
||||
*
|
||||
* @param int[] $donationIds
|
||||
* @return array<int,array<int,array{title:string}>>
|
||||
*/
|
||||
public function reachedByDonation( array $donationIds ): array {
|
||||
$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 = $this->db->get_results(
|
||||
$this->db->prepare( 'SELECT reached_donation_id, title FROM ' . $this->t( 'goal_tiers' ) . " WHERE reached_donation_id IN ($in) ORDER BY target_minor ASC, id ASC", ...$ids ),
|
||||
ARRAY_A
|
||||
);
|
||||
$out = array();
|
||||
foreach ( (array) $rows as $r ) {
|
||||
$out[ (int) $r['reached_donation_id'] ][] = array( 'title' => (string) $r['title'] );
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep sg_goals.target_minor equal to the highest tier target. Leaves the goal untouched when it has no tiers.
|
||||
*
|
||||
* @return bool true when the goal row was set from tiers.
|
||||
*/
|
||||
public function syncGoalTarget( int $goalId ): bool {
|
||||
$max = $this->db->get_var( $this->db->prepare( 'SELECT MAX(target_minor) FROM ' . $this->t( 'goal_tiers' ) . ' WHERE goal_id = %d', $goalId ) );
|
||||
if ( null === $max || (int) $max <= 0 ) {
|
||||
return false;
|
||||
}
|
||||
$this->db->query( $this->db->prepare( 'UPDATE ' . $this->t( 'goals' ) . ' SET target_minor = %d WHERE id = %d', (int) $max, $goalId ) );
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -103,4 +103,14 @@ final class AlertDefInputTest extends TestCase {
|
||||
$this->assertStringNotContainsString( '<', $this->run_( $this->post( array( 'title' => '<script>x</script>Hi', 'message' => '<b>hi</b>' ) ) )['data']['title'] );
|
||||
$this->assertStringNotContainsString( '<', $this->run_( $this->post( array( 'message' => '<b>hi</b>{name}' ) ) )['data']['message'] );
|
||||
}
|
||||
|
||||
public function test_frameless_checkbox_parsing_defaults_off(): void {
|
||||
$this->assertSame( 0, $this->run_( $this->post() )['data']['frameless'] );
|
||||
foreach ( array( '1', 'on', 1, true, 'true' ) as $on ) {
|
||||
$this->assertSame( 1, $this->run_( $this->post( array( 'frameless' => $on ) ) )['data']['frameless'], 'on: ' . var_export( $on, true ) );
|
||||
}
|
||||
foreach ( array( '0', '', 'off', array( '1' ), 'banana' ) as $off ) {
|
||||
$this->assertSame( 0, $this->run_( $this->post( array( 'frameless' => $off ) ) )['data']['frameless'], 'off: ' . var_export( $off, true ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\Input;
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
final class DonationNoticeTest extends TestCase {
|
||||
|
||||
public function test_default_notice_says_donations_are_non_refundable(): void {
|
||||
$d = Settings::defaults();
|
||||
$this->assertArrayHasKey( 'donation_notice', $d );
|
||||
$this->assertStringContainsString( 'non-refundable', strtolower( (string) $d['donation_notice'] ) );
|
||||
}
|
||||
|
||||
public function test_admin_input_is_plain_text_and_length_capped(): void {
|
||||
$this->assertSame( 'No refunds, sorry.', Input::text( ' No refunds, sorry. ', 200 ) );
|
||||
$this->assertStringNotContainsString( '<', Input::text( '<script>alert(1)</script><b>Hi</b>', 200 ), 'no markup survives (and it is rendered as text anyway)' );
|
||||
$this->assertStringNotContainsString( '<', Input::text( '<b>Bold</b> <i>text</i>', 200 ) );
|
||||
$this->assertSame( 200, strlen( Input::text( str_repeat( 'a', 500 ), 200 ) ) );
|
||||
$this->assertSame( '', Input::text( "\x00\x1F", 200 ) );
|
||||
}
|
||||
|
||||
public function test_form_script_renders_the_notice_with_textcontent_only(): void {
|
||||
$js = (string) file_get_contents( dirname( __DIR__, 2 ) . '/assets/donate/donate.js' );
|
||||
$this->assertMatchesRegularExpression( '/if \(C\.notice\).*sg-notice.*text: String\(C\.notice\)/s', $js, 'notice must be rendered as text, never HTML' );
|
||||
$this->assertStringNotContainsString( 'innerHTML', $js );
|
||||
}
|
||||
|
||||
public function test_form_config_passes_the_notice_through(): void {
|
||||
$php = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Rest/DonateController.php' );
|
||||
$this->assertStringContainsString( "'notice' => (string) ( \$s['donation_notice'] ?? '' )", $php );
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ final class OverlayAlertMediaTest extends TestCase {
|
||||
'volume' => 60,
|
||||
'duration_ms' => 7000,
|
||||
'message' => 'Al gave $25.00',
|
||||
'frameless' => false,
|
||||
), $m );
|
||||
}
|
||||
|
||||
@@ -169,4 +170,22 @@ final class OverlayAlertMediaTest extends TestCase {
|
||||
Payloads::alerts( array( $this->row( 1, array( 'is_anonymous' => 1 ) ), $this->row( 2, array( 'moderation' => 'rejected' ) ) ), null, 10, true, $cb );
|
||||
$this->assertSame( array( array( 1, 'Anonymous', '$25.00' ) ), $seen );
|
||||
}
|
||||
|
||||
public function test_frameless_passes_through_only_with_a_visual(): void {
|
||||
$this->assertTrue( $this->build( $this->def( 1, array( 'frameless' => 1 ) ) )['frameless'] );
|
||||
$this->assertFalse( $this->build( $this->def( 1, array( 'frameless' => 0 ) ) )['frameless'] );
|
||||
$this->assertFalse( $this->build( $this->def( 1, array( 'frameless' => 1, 'visual_id' => 0, 'message' => 'hi' ) ) )['frameless'], 'no visual, nothing to unframe' );
|
||||
$this->assertFalse( $this->build( $this->def( 1, array( 'frameless' => 1, 'visual_id' => 13 ) ) )['frameless'], 'rejected media never unframes' );
|
||||
}
|
||||
|
||||
public function test_media_url_gets_version_suffix_from_server_data_only(): void {
|
||||
$files = array( 10 => array( 'url' => 'https://cdn.test/a.png', 'mime' => 'image/png', 'v' => 1700000000 ), 11 => array( 'url' => 'https://cdn.test/a.png?x=1', 'mime' => 'image/png', 'modified' => '2024-01-02 03:04:05' ) );
|
||||
$get = static fn( int $id ): ?array => $files[ $id ] ?? null;
|
||||
$m = AlertMedia::fromDef( $this->def( 1, array( 'sound_id' => 0 ) ), 'Al', '$1', array(), $get );
|
||||
$this->assertSame( 'https://cdn.test/a.png?v=1700000000', $m['visual']['url'] );
|
||||
$m = AlertMedia::fromDef( $this->def( 1, array( 'visual_id' => 11, 'sound_id' => 0 ) ), 'Al', '$1', array(), $get );
|
||||
$this->assertSame( 'https://cdn.test/a.png?x=1&v=' . strtotime( '2024-01-02 03:04:05 UTC' ), $m['visual']['url'] );
|
||||
$row = $this->row( 1, array( 'media' => array( 'visual' => array( 'type' => 'image', 'url' => 'https://evil.test/z.png' ) ) ) );
|
||||
$this->assertNotSame( 'https://evil.test/z.png', $this->build( $this->def( 1 ), $row )['visual']['url'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Alerts\Media;
|
||||
use StreamGoals\Overlay\Build;
|
||||
|
||||
final class OverlayBuildTest extends TestCase {
|
||||
|
||||
public function test_build_id_combines_version_and_epoch_and_is_safe(): void {
|
||||
$this->assertSame( '0.1.0-0', Build::id( '0.1.0', false ) );
|
||||
$this->assertSame( '0.1.0-7', Build::id( '0.1.0', '7' ) );
|
||||
$this->assertSame( '1.2x-0', Build::id( '1.2"<x>', 'abc' ), 'junk characters are stripped, junk epoch is 0' );
|
||||
$this->assertSame( '0-0', Build::id( '', null ) );
|
||||
$this->assertNotSame( Build::id( '0.1.0', 1 ), Build::id( '0.1.1', 1 ) );
|
||||
$this->assertNotSame( Build::id( '0.1.0', 1 ), Build::id( '0.1.0', 2 ) );
|
||||
}
|
||||
|
||||
public function test_headers_carry_only_the_build_and_never_touch_the_etag(): void {
|
||||
$this->assertSame( array( 'X-SG-Build' => '0.1.0-3' ), Build::headers( '0.1.0-3' ) );
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Rest/OverlayController.php' );
|
||||
$this->assertStringContainsString( 'Build::headers( Build::current() )', $src );
|
||||
$this->assertStringContainsString( 'Payloads::etag( $payload, $service->etagSalt(', $src, 'ETag is still computed from the payload only' );
|
||||
}
|
||||
|
||||
public function test_epoch_bump_rules(): void {
|
||||
$this->assertSame( 1000, Build::nextEpoch( 0, 1000 ) );
|
||||
$this->assertSame( 1000, Build::nextEpoch( false, 1000 ) );
|
||||
$this->assertSame( 1000, Build::nextEpoch( '999', 1000 ) );
|
||||
$this->assertSame( 2001, Build::nextEpoch( 2000, 1000 ), 'strictly increasing even if the clock went back' );
|
||||
$this->assertSame( 1000, Build::nextEpoch( '-5', 1000 ) );
|
||||
$this->assertSame( 1000, Build::nextEpoch( array( 9 ), 1000 ) );
|
||||
$this->assertSame( 0, Build::epochInt( 1.5 ) );
|
||||
$this->assertSame( 0, Build::epochInt( '99999999999999999999' ) );
|
||||
}
|
||||
|
||||
public function test_refresh_handler_is_guarded_registered_and_option_is_not_autoloaded(): void {
|
||||
$root = dirname( __DIR__, 2 ) . '/includes/';
|
||||
$page = (string) file_get_contents( $root . 'Admin/OverlaysPage.php' );
|
||||
$start = strpos( $page, 'function handleRefreshAll' );
|
||||
$this->assertNotFalse( $start );
|
||||
$this->assertStringContainsString( "Admin::guard( 'sg_refresh_overlays' )", substr( $page, $start, 200 ) );
|
||||
$this->assertStringContainsString( "'sg_refresh_overlays' => array( OverlaysPage::class, 'handleRefreshAll' )", (string) file_get_contents( $root . 'Admin/Admin.php' ) );
|
||||
$this->assertStringContainsString( 'Reloads every open OBS source. Done automatically after a plugin update.', $page );
|
||||
$this->assertStringContainsString( ', false );', substr( (string) file_get_contents( $root . 'Overlay/Build.php' ), (int) strpos( (string) file_get_contents( $root . 'Overlay/Build.php' ), 'update_option' ) ) );
|
||||
$this->assertStringContainsString( 'data-build=', (string) file_get_contents( $root . 'Overlay/Router.php' ) );
|
||||
}
|
||||
|
||||
public function test_media_version_suffix_builder(): void {
|
||||
$this->assertSame( 'https://x.test/a.png?v=123', Media::withVersion( 'https://x.test/a.png', 123 ) );
|
||||
$this->assertSame( 'https://x.test/a.png?q=1&v=123', Media::withVersion( 'https://x.test/a.png?q=1', 123 ) );
|
||||
$this->assertSame( 'https://x.test/a.png?v=123', Media::withVersion( 'https://x.test/a.png?v=5', 123 ), 'replaces an old v' );
|
||||
$this->assertSame( 'https://x.test/a.png?q=1&v=123', Media::withVersion( 'https://x.test/a.png?v=5&q=1', 123 ) );
|
||||
$this->assertSame( 'https://x.test/a.png?v=' . strtotime( '2024-05-06 07:08:09 UTC' ), Media::withVersion( 'https://x.test/a.png', 0, '2024-05-06 07:08:09' ), 'falls back to post_modified_gmt' );
|
||||
$this->assertSame( 'https://x.test/a.png?v=50', Media::withVersion( 'https://x.test/a.png', 50, '2024-05-06 07:08:09' ), 'file mtime wins' );
|
||||
$this->assertSame( 'https://x.test/a.png', Media::withVersion( 'https://x.test/a.png', 0, '0000-00-00 00:00:00x' ) );
|
||||
$this->assertSame( 'https://x.test/a.png', Media::withVersion( 'https://x.test/a.png', 0 ) );
|
||||
$this->assertSame( 'https://x.test/a.png#f', Media::withVersion( 'https://x.test/a.png#f', 9 ) );
|
||||
$this->assertNotNull( Media::safeUrl( Media::withVersion( 'https://x.test/a.png', 123 ) ) );
|
||||
}
|
||||
|
||||
public function test_installer_has_frameless_column_and_version_five(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
|
||||
$this->assertSame( 1, preg_match( "/DB_VERSION = '(\\d+)'/", $src, $m ) );
|
||||
$this->assertGreaterThanOrEqual( 5, (int) $m[1] );
|
||||
$this->assertMatchesRegularExpression( '/CREATE TABLE \{\$p\}alert_defs \([^;]*frameless TINYINT\(1\) NOT NULL DEFAULT 0,/s', $src );
|
||||
}
|
||||
|
||||
public function test_overlay_js_checks_build_on_every_response_including_304(): void {
|
||||
$js = (string) file_get_contents( dirname( __DIR__, 2 ) . '/assets/overlay/overlay.js' );
|
||||
$this->assertLessThan( strpos( $js, 'r.status === 304' ), strpos( $js, 'checkBuild(r)' ), 'build is compared before the 304 shortcut' );
|
||||
$this->assertStringContainsString( 'X-SG-Build', $js );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?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;
|
||||
use StreamGoals\Overlay\TiersSource;
|
||||
|
||||
final class OverlayTiersTest extends TestCase {
|
||||
|
||||
private function tiers( array $reached = array() ): array {
|
||||
$rows = array( array( 1, 10000, 'Giveaway' ), array( 2, 25000, 'Microphone' ), array( 3, 50000, '24h stream' ) );
|
||||
return array_map( static fn( $r ) => array( 'id' => $r[0], 'target_minor' => $r[1], 'title' => $r[2], 'description' => 'd' . $r[0], 'reached_at' => in_array( $r[0], $reached, true ) ? '2026-01-01 00:00:00' : null ), $rows );
|
||||
}
|
||||
|
||||
private function svc( array $tiers, int $raised, array $db = array(), array $unlocked = array(), ?object &$probe = null ): OverlayService {
|
||||
$probe = new class( $tiers, $raised, $db, $unlocked ) implements OverlayDataSource, RecentDonationsSource, TiersSource {
|
||||
public int $reachedQueries = 0;
|
||||
public function __construct( private array $tiers, private int $raised, private array $db, private array $unlocked ) {}
|
||||
public function activeGoal(): ?array { return array( 'id' => 7, 'title' => 'Stream', 'currency' => 'USD', 'target_minor' => 50000 ); }
|
||||
public function raisedMinor( array $goal ): int { return $this->raised; }
|
||||
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 $this->db; }
|
||||
public function recentDonations( int $limit ): array { return $this->db; }
|
||||
public function tiersFor( int $goalId ): array { return $this->tiers; }
|
||||
public function tiersReachedFor( array $ids ): array { ++$this->reachedQueries; return $this->unlocked; }
|
||||
};
|
||||
return new OverlayService( $probe );
|
||||
}
|
||||
|
||||
private function row( int $id ): array {
|
||||
return array( 'id' => $id, 'base_minor' => 2500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
|
||||
}
|
||||
|
||||
public function test_untiered_goal_payload_is_unchanged(): void {
|
||||
$g = Payloads::goal( array( 'title' => 'G', 'currency' => 'USD', 'target_minor' => 20000 ), 5000 );
|
||||
$this->assertArrayNotHasKey( 'tiers', $g );
|
||||
$this->assertSame( 25, $g['percent'] );
|
||||
$this->assertSame( $g, Payloads::goal( array( 'title' => 'G', 'currency' => 'USD', 'target_minor' => 20000 ), 5000, array() ) );
|
||||
$this->assertArrayNotHasKey( 'tiers', $this->svc( array(), 100 )->payload( 'goal', 1 ) );
|
||||
}
|
||||
|
||||
public function test_tiered_goal_percent_is_within_tier_and_displays(): void {
|
||||
$g = $this->svc( $this->tiers( array( 1 ) ), 17500 )->payload( 'goal', 1 );
|
||||
$this->assertSame( 50, $g['percent'] );
|
||||
$this->assertSame( 17500, $g['raised_minor'] );
|
||||
$this->assertSame( '$175.00', $g['raised_display'] );
|
||||
$this->assertSame( 25000, $g['target_minor'] );
|
||||
$this->assertSame( '$250.00', $g['target_display'] );
|
||||
$t = $g['tiers'];
|
||||
$this->assertSame( 3, $t['count'] );
|
||||
$this->assertSame( 2, $t['index'] );
|
||||
$this->assertFalse( $t['all_reached'] );
|
||||
$this->assertSame( array( 'title' => 'Microphone', 'description' => 'd2', 'target_minor' => 25000, 'target_display' => '$250.00', 'floor_minor' => 10000 ), $t['current'] );
|
||||
}
|
||||
|
||||
public function test_tiered_goal_below_first_tier_and_all_reached(): void {
|
||||
$g = $this->svc( $this->tiers(), 2500 )->payload( 'goal', 1 );
|
||||
$this->assertSame( 25, $g['percent'] );
|
||||
$this->assertSame( 1, $g['tiers']['index'] );
|
||||
$this->assertSame( 0, $g['tiers']['current']['floor_minor'] );
|
||||
$all = $this->svc( $this->tiers( array( 1, 2, 3 ) ), 60000 )->payload( 'goal', 1 );
|
||||
$this->assertSame( 100, $all['percent'] );
|
||||
$this->assertTrue( $all['tiers']['all_reached'] );
|
||||
$this->assertNull( $all['tiers']['current'] );
|
||||
$this->assertSame( 3, $all['tiers']['index'] );
|
||||
$this->assertSame( '$500.00', $all['target_display'] );
|
||||
$this->assertSame( '$600.00', $all['raised_display'] );
|
||||
}
|
||||
|
||||
public function test_tier_text_is_sanitized(): void {
|
||||
$t = $this->tiers();
|
||||
$t[0]['title'] = '<script>x</script>Hi' . str_repeat( 'a', 300 );
|
||||
$g = $this->svc( $t, 0 )->payload( 'goal', 1 );
|
||||
$this->assertStringNotContainsString( '<', $g['tiers']['current']['title'] );
|
||||
$this->assertLessThanOrEqual( 120, mb_strlen( $g['tiers']['current']['title'] ) );
|
||||
}
|
||||
|
||||
public function test_alert_tiers_in_since_and_recent_with_one_query(): void {
|
||||
$probe = null;
|
||||
$svc = $this->svc( array(), 0, array( $this->row( 3 ), $this->row( 4 ) ), array( 3 => array( array( 'title' => 'Giveaway' ), array( 'title' => 'Microphone' ) ) ), $probe );
|
||||
$since = $svc->payload( 'alerts', 1, 0 );
|
||||
$this->assertSame( 1, $probe->reachedQueries );
|
||||
$recent = $svc->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( 2, $probe->reachedQueries );
|
||||
$this->assertSame( $since['alerts'], $recent['alerts'] );
|
||||
$this->assertSame( array( array( 'title' => 'Giveaway' ), array( 'title' => 'Microphone' ) ), $recent['alerts'][0]['tiers'] );
|
||||
$this->assertSame( array(), $recent['alerts'][1]['tiers'] );
|
||||
$svc->payload( 'alerts', 1, null ); // baseline poll: no lookup
|
||||
$this->assertSame( 2, $probe->reachedQueries );
|
||||
}
|
||||
|
||||
public function test_alert_tier_events_sanitized_and_capped(): void {
|
||||
$ev = array( array( 'title' => '<b>Hi</b>' ), array( 'title' => '' ), 'junk', array( 'title' => str_repeat( 'é', 200 ) ) );
|
||||
for ( $i = 0; $i < 9; $i++ ) {
|
||||
$ev[] = array( 'title' => "T$i" );
|
||||
}
|
||||
$out = Payloads::tierEvents( $ev );
|
||||
$this->assertCount( 5, $out );
|
||||
$this->assertSame( array( 'title' => 'Hi' ), $out[0] );
|
||||
$this->assertSame( 80, mb_strlen( $out[1]['title'] ) );
|
||||
$this->assertSame( array(), Payloads::tierEvents( 'nope' ) );
|
||||
}
|
||||
|
||||
public function test_etag_changes_when_a_tier_unlocks_or_current_tier_moves(): void {
|
||||
$a = Payloads::etag( $this->svc( array(), 0, array( $this->row( 3 ) ) )->payload( 'alerts', 1, null, true ) );
|
||||
$b = Payloads::etag( $this->svc( array(), 0, array( $this->row( 3 ) ), array( 3 => array( array( 'title' => 'X' ) ) ) )->payload( 'alerts', 1, null, true ) );
|
||||
$this->assertNotSame( $a, $b );
|
||||
$g1 = Payloads::etag( $this->svc( $this->tiers(), 9000 )->payload( 'goal', 1 ) );
|
||||
$g2 = Payloads::etag( $this->svc( $this->tiers( array( 1 ) ), 10000 )->payload( 'goal', 1 ) );
|
||||
$this->assertNotSame( $g1, $g2 );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Tiers\TierPolicy;
|
||||
|
||||
final class TierPolicyTest extends TestCase {
|
||||
|
||||
private function tiers( array $reachedIds = array() ): array {
|
||||
$rows = array( array( 1, 10000, 'Giveaway' ), array( 2, 25000, 'Microphone' ), array( 3, 50000, '24h stream' ) );
|
||||
$out = array();
|
||||
foreach ( $rows as [ $id, $t, $title ] ) {
|
||||
$out[] = array( 'id' => $id, 'target_minor' => $t, 'title' => $title, 'description' => '', 'reached_at' => in_array( $id, $reachedIds, true ) ? '2026-01-01 00:00:00' : null );
|
||||
}
|
||||
return array_reverse( $out ); // unsorted on purpose
|
||||
}
|
||||
|
||||
public function test_current_tier_and_index(): void {
|
||||
$this->assertSame( 1, TierPolicy::currentTier( $this->tiers() )['id'] );
|
||||
$this->assertSame( 1, TierPolicy::currentIndex( $this->tiers() ) );
|
||||
$this->assertSame( 3, TierPolicy::currentTier( $this->tiers( array( 1, 2 ) ) )['id'] );
|
||||
$this->assertSame( 3, TierPolicy::currentIndex( $this->tiers( array( 1, 2 ) ) ) );
|
||||
$this->assertNull( TierPolicy::currentTier( $this->tiers( array( 1, 2, 3 ) ) ) );
|
||||
$this->assertSame( 3, TierPolicy::currentIndex( $this->tiers( array( 1, 2, 3 ) ) ) );
|
||||
$this->assertTrue( TierPolicy::allReached( $this->tiers( array( 1, 2, 3 ) ) ) );
|
||||
$this->assertFalse( TierPolicy::allReached( $this->tiers( array( 1 ) ) ) );
|
||||
$this->assertFalse( TierPolicy::allReached( array() ) );
|
||||
$this->assertSame( 0, TierPolicy::currentIndex( array() ) );
|
||||
}
|
||||
|
||||
public function test_floor(): void {
|
||||
$this->assertSame( 0, TierPolicy::floorMinor( $this->tiers() ) );
|
||||
$this->assertSame( 10000, TierPolicy::floorMinor( $this->tiers( array( 1 ) ) ) );
|
||||
$this->assertSame( 25000, TierPolicy::floorMinor( $this->tiers( array( 1, 2 ) ) ) );
|
||||
$this->assertSame( 50000, TierPolicy::floorMinor( $this->tiers( array( 1, 2, 3 ) ) ), 'all reached: top target' );
|
||||
}
|
||||
|
||||
public function test_percent_within_tier_clamped(): void {
|
||||
$this->assertSame( 0, TierPolicy::percent( 0, 0, 10000 ) );
|
||||
$this->assertSame( 50, TierPolicy::percent( 5000, 0, 10000 ) );
|
||||
$this->assertSame( 50, TierPolicy::percent( 17500, 10000, 25000 ) );
|
||||
$this->assertSame( 0, TierPolicy::percent( 10000, 10000, 25000 ), 'exactly at the floor' );
|
||||
$this->assertSame( 0, TierPolicy::percent( 500, 10000, 25000 ), 'raised below the floor clamps to 0' );
|
||||
$this->assertSame( 100, TierPolicy::percent( 25000, 10000, 25000 ), 'exactly at the target' );
|
||||
$this->assertSame( 100, TierPolicy::percent( 99999, 10000, 25000 ), 'above clamps to 100' );
|
||||
$this->assertSame( 0, TierPolicy::percent( 5, 100, 100 ), 'degenerate range, not reached' );
|
||||
$this->assertSame( 100, TierPolicy::percent( 100, 100, 100 ), 'degenerate range, reached' );
|
||||
}
|
||||
|
||||
public function test_percent_for_walks_the_ladder(): void {
|
||||
$this->assertSame( 25, TierPolicy::percentFor( $this->tiers(), 2500 ) );
|
||||
$this->assertSame( 0, TierPolicy::percentFor( $this->tiers( array( 1 ) ), 10000 ) );
|
||||
$this->assertSame( 50, TierPolicy::percentFor( $this->tiers( array( 1 ) ), 17500 ) );
|
||||
$this->assertSame( 100, TierPolicy::percentFor( $this->tiers( array( 1, 2, 3 ) ), 60000 ) );
|
||||
$this->assertSame( 0, TierPolicy::percentFor( array(), 500 ) );
|
||||
$this->assertSame( 7500, TierPolicy::remainingMinor( $this->tiers(), 2500 ) );
|
||||
$this->assertSame( 0, TierPolicy::remainingMinor( $this->tiers( array( 1, 2, 3 ) ), 60000 ) );
|
||||
}
|
||||
|
||||
public function test_newly_reached_several_in_one_donation_in_order(): void {
|
||||
$ids = array_column( TierPolicy::newlyReached( $this->tiers(), 30000 ), 'id' );
|
||||
$this->assertSame( array( 1, 2 ), $ids );
|
||||
$this->assertSame( array( 1, 2, 3 ), array_column( TierPolicy::newlyReached( $this->tiers(), 50000 ), 'id' ), 'exactly at the last target counts' );
|
||||
$this->assertSame( array(), TierPolicy::newlyReached( $this->tiers(), 9999 ) );
|
||||
$this->assertSame( array( 2 ), array_column( TierPolicy::newlyReached( $this->tiers( array( 1 ) ), 30000 ), 'id' ), 'reached ones are skipped' );
|
||||
}
|
||||
|
||||
public function test_replay_is_idempotent_at_policy_level(): void {
|
||||
$tiers = $this->tiers();
|
||||
$first = TierPolicy::newlyReached( $tiers, 30000 );
|
||||
foreach ( $tiers as &$t ) {
|
||||
if ( in_array( $t['id'], array_column( $first, 'id' ), true ) ) {
|
||||
$t['reached_at'] = '2026-02-02 00:00:00';
|
||||
}
|
||||
}
|
||||
unset( $t );
|
||||
$this->assertSame( array(), TierPolicy::newlyReached( $tiers, 30000 ) );
|
||||
$this->assertSame( array(), TierPolicy::newlyReached( $tiers, 12000 ), 'a lower total (refund) never un-reaches or re-reaches' );
|
||||
}
|
||||
|
||||
public function test_derived_target_is_highest(): void {
|
||||
$this->assertSame( 50000, TierPolicy::derivedGoalTarget( $this->tiers() ) );
|
||||
$this->assertSame( 0, TierPolicy::derivedGoalTarget( array() ) );
|
||||
}
|
||||
|
||||
public function test_status(): void {
|
||||
$t = $this->tiers( array( 1 ) );
|
||||
$by = array();
|
||||
foreach ( $t as $row ) {
|
||||
$by[ $row['id'] ] = TierPolicy::status( $t, $row );
|
||||
}
|
||||
$this->assertSame( array( 3 => 'upcoming', 2 => 'current', 1 => 'reached' ), $by );
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ validation */
|
||||
|
||||
private function v( ?int $target, string $title = 'Mic', string $desc = '', ?int $edit = null, int $raised = 0, ?array $tiers = null ): array {
|
||||
return TierPolicy::validate( $tiers ?? $this->tiers( array( 1 ) ), $edit, $target, $title, $desc, $raised, 100, '$1.00' );
|
||||
}
|
||||
|
||||
public function test_valid_new_tier(): void {
|
||||
$r = $this->v( 70000, ' New desk ', ' nice ', null, 12000 );
|
||||
$this->assertNull( $r['error'] );
|
||||
$this->assertSame( array( 'target_minor' => 70000, 'title' => 'New desk', 'description' => 'nice' ), $r['data'] );
|
||||
}
|
||||
|
||||
public function test_rejects_bad_values(): void {
|
||||
$this->assertNotNull( $this->v( null )['error'] );
|
||||
$this->assertNotNull( $this->v( 0 )['error'] );
|
||||
$this->assertStringContainsString( 'minimum', (string) $this->v( 50 )['error'] );
|
||||
$this->assertStringContainsString( 'title', (string) $this->v( 70000, ' ' )['error'] . ' title' );
|
||||
$this->assertNotNull( $this->v( 70000, ' ' )['error'] );
|
||||
$this->assertNotNull( $this->v( 70000, str_repeat( 'a', 121 ) )['error'] );
|
||||
$this->assertNull( $this->v( 70000, str_repeat( 'a', 120 ) )['error'] );
|
||||
$this->assertNotNull( $this->v( 70000, 'x', str_repeat( 'd', 256 ) )['error'] );
|
||||
$this->assertNull( $this->v( 70000, 'x', str_repeat( 'd', 255 ) )['error'] );
|
||||
}
|
||||
|
||||
public function test_target_must_be_unique_and_above_raised(): void {
|
||||
$this->assertStringContainsString( 'already', (string) $this->v( 25000 )['error'] );
|
||||
$this->assertStringContainsString( 'already raised', (string) $this->v( 20000, 'x', '', null, 20000 )['error'], 'equal to raised unlocks instantly' );
|
||||
$this->assertNull( $this->v( 20001, 'x', '', null, 20000 )['error'] );
|
||||
}
|
||||
|
||||
public function test_reached_tier_target_is_locked_but_text_editable(): void {
|
||||
$r = $this->v( 999999, 'Renamed', 'd', 1, 12000 );
|
||||
$this->assertNull( $r['error'] );
|
||||
$this->assertSame( 10000, $r['data']['target_minor'] );
|
||||
$this->assertSame( 'Renamed', $r['data']['title'] );
|
||||
$r2 = $this->v( null, 'Renamed', '', 1, 12000 );
|
||||
$this->assertSame( 10000, $r2['data']['target_minor'] );
|
||||
}
|
||||
|
||||
public function test_edit_unreached_keeps_or_moves_target(): void {
|
||||
$this->assertNull( $this->v( 25000, 'Mic2', '', 2, 12000 )['error'], 'unchanged target is fine' );
|
||||
$this->assertNull( $this->v( 30000, 'Mic', '', 2, 12000 )['error'] );
|
||||
$this->assertStringContainsString( 'already', (string) $this->v( 50000, 'Mic', '', 2, 12000 )['error'] );
|
||||
$this->assertStringContainsString( 'no longer', (string) $this->v( 30000, 'Mic', '', 99, 12000 )['error'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Tiers\TierRepository;
|
||||
|
||||
final class TierRepositoryTest extends TestCase {
|
||||
|
||||
private function fake( array $rows = array(), $var = null ): object {
|
||||
if ( ! defined( 'ARRAY_A' ) ) {
|
||||
define( 'ARRAY_A', 'ARRAY_A' );
|
||||
}
|
||||
return new class( $rows, $var ) {
|
||||
public string $prefix = 'wp_';
|
||||
public array $sql = array();
|
||||
public int $insert_id = 9;
|
||||
public array $queryResults = array();
|
||||
public function __construct( public array $rows, public $var ) {}
|
||||
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 array_shift( $this->queryResults ) ?? 1; }
|
||||
public function get_results( string $q, $o = null ): array { $this->sql[] = $q; return $this->rows; }
|
||||
public function get_var( string $q ) { $this->sql[] = $q; return $this->var; }
|
||||
public function insert( string $t, array $d, array $f ) { $this->sql[] = 'INSERT ' . $t . ' ' . json_encode( $d ); return 1; }
|
||||
};
|
||||
}
|
||||
|
||||
private function row( int $id, int $target, ?string $reached = null ): array {
|
||||
return array( 'id' => (string) $id, 'goal_id' => '7', 'target_minor' => (string) $target, 'title' => "T$id", 'description' => '', 'reached_at' => $reached, 'reached_donation_id' => null, 'created_at' => '2026-01-01 00:00:00' );
|
||||
}
|
||||
|
||||
public function test_for_goal_orders_by_target_and_casts(): void {
|
||||
$db = $this->fake( array( $this->row( 1, 10000 ) ) );
|
||||
$rows = ( new TierRepository( $db ) )->forGoal( 7 );
|
||||
$this->assertStringContainsString( 'WHERE goal_id = 7 ORDER BY target_minor ASC', $db->sql[0] );
|
||||
$this->assertSame( 10000, $rows[0]['target_minor'] );
|
||||
$this->assertNull( $rows[0]['reached_at'] );
|
||||
}
|
||||
|
||||
public function test_mark_reached_is_atomic_per_tier_and_only_for_reachable(): void {
|
||||
$db = $this->fake( array( $this->row( 1, 10000 ), $this->row( 2, 25000 ), $this->row( 3, 50000 ), $this->row( 4, 5000, '2026-01-01 00:00:00' ) ) );
|
||||
$marked = ( new TierRepository( $db ) )->markReached( 7, 30000, 55 );
|
||||
$this->assertSame( array( 1, 2 ), $marked );
|
||||
$updates = array_values( array_filter( $db->sql, static fn( $q ) => str_starts_with( $q, 'UPDATE' ) ) );
|
||||
$this->assertCount( 2, $updates );
|
||||
foreach ( $updates as $q ) {
|
||||
$this->assertStringContainsString( 'reached_at IS NULL', $q );
|
||||
$this->assertStringContainsString( 'reached_donation_id = 55', $q );
|
||||
$this->assertStringContainsString( 'UPDATE wp_sg_goal_tiers', $q );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_mark_reached_replay_loses_race_and_reports_nothing(): void {
|
||||
$db = $this->fake( array( $this->row( 1, 10000 ) ) );
|
||||
$db->queryResults = array( 0 ); // someone else already marked it
|
||||
$this->assertSame( array(), ( new TierRepository( $db ) )->markReached( 7, 30000, 55 ) );
|
||||
}
|
||||
|
||||
public function test_mark_reached_ignores_invalid_ids(): void {
|
||||
$db = $this->fake( array( $this->row( 1, 10000 ) ) );
|
||||
$this->assertSame( array(), ( new TierRepository( $db ) )->markReached( 0, 30000, 55 ) );
|
||||
$this->assertSame( array(), ( new TierRepository( $db ) )->markReached( 7, 30000, 0 ) );
|
||||
$this->assertSame( array(), $db->sql );
|
||||
}
|
||||
|
||||
public function test_reached_by_donation_is_one_query_and_grouped(): void {
|
||||
$db = $this->fake( array( array( 'reached_donation_id' => '5', 'title' => 'A' ), array( 'reached_donation_id' => '5', 'title' => 'B' ), array( 'reached_donation_id' => '6', 'title' => 'C' ) ) );
|
||||
$out = ( new TierRepository( $db ) )->reachedByDonation( array( 5, 6, 6, 0, -1 ) );
|
||||
$this->assertCount( 1, $db->sql );
|
||||
$this->assertStringContainsString( 'reached_donation_id IN (5,6)', $db->sql[0] );
|
||||
$this->assertSame( array( 5 => array( array( 'title' => 'A' ), array( 'title' => 'B' ) ), 6 => array( array( 'title' => 'C' ) ) ), $out );
|
||||
$this->assertSame( array(), ( new TierRepository( $this->fake() ) )->reachedByDonation( array() ) );
|
||||
}
|
||||
|
||||
public function test_sync_goal_target_sets_highest_and_skips_untiered(): void {
|
||||
$db = $this->fake( array(), '50000' );
|
||||
$this->assertTrue( ( new TierRepository( $db ) )->syncGoalTarget( 7 ) );
|
||||
$this->assertStringContainsString( 'MAX(target_minor)', $db->sql[0] );
|
||||
$this->assertStringContainsString( 'UPDATE wp_sg_goals SET target_minor = 50000 WHERE id = 7', $db->sql[1] );
|
||||
$none = $this->fake( array(), null );
|
||||
$this->assertFalse( ( new TierRepository( $none ) )->syncGoalTarget( 7 ) );
|
||||
$this->assertCount( 1, $none->sql, 'no UPDATE when the goal has no tiers' );
|
||||
}
|
||||
|
||||
public function test_installer_defines_tier_table_unique_key_and_version(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
|
||||
$this->assertSame( 1, preg_match( "/DB_VERSION = '(\\d+)'/", $src, $m ) );
|
||||
$this->assertGreaterThanOrEqual( 4, (int) $m[1] );
|
||||
$this->assertStringContainsString( 'CREATE TABLE {$p}goal_tiers (', $src );
|
||||
$this->assertStringContainsString( 'UNIQUE KEY goal_target (goal_id,target_minor)', $src );
|
||||
$this->assertStringContainsString( 'reached_donation_id BIGINT UNSIGNED NULL', $src );
|
||||
}
|
||||
|
||||
public function test_donation_store_marks_tiers_before_close_at_target(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/PayPal/DonationStore.php' );
|
||||
$start = strpos( $src, 'function notify_applied' );
|
||||
$body = substr( $src, $start, strpos( $src, 'function close_goal_if_target_reached' ) - $start );
|
||||
$a = strpos( $body, 'Recorder::forDonation' );
|
||||
$tier = strpos( $body, 'Tiers\\Recorder::forDonation' );
|
||||
$close = strpos( $body, 'self::close_goal_if_target_reached' );
|
||||
$this->assertNotFalse( $tier );
|
||||
$this->assertNotFalse( $a );
|
||||
$this->assertLessThan( $tier, strpos( $body, 'call_engine' ), 'engine first' );
|
||||
$this->assertLessThan( $close, $tier, 'tiers before the close check' );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user