Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
39840a20d7 | ||
|
|
2c16a9ebbb | ||
|
|
1201db175b | ||
|
|
43106d9edc | ||
|
|
5ea1e1d273 | ||
|
|
1c6d93ad5f | ||
|
|
da1365f060 | ||
|
|
f8d6bc2195 | ||
|
|
e9e3265b22 |
No files matched your search
@@ -48,7 +48,20 @@ jobs:
|
||||
|
||||
- name: Compute version
|
||||
id: ver
|
||||
run: echo "version=$(date -u +'%Y.%m.%d-%H%M')" >> "$GITHUB_OUTPUT"
|
||||
run: |
|
||||
# Date-based version to the minute. Two pushes in the same minute would collide on the tag,
|
||||
# so keep moving to the next minute until the tag is unused (format stays YYYY.MM.DD-HHMM).
|
||||
git fetch --tags --quiet origin || true
|
||||
TS=$(date -u +%s)
|
||||
while true; do
|
||||
V=$(date -u -d "@$TS" +'%Y.%m.%d-%H%M')
|
||||
if git rev-parse -q --verify "refs/tags/$V" >/dev/null || git ls-remote --exit-code --tags origin "refs/tags/$V" >/dev/null 2>&1; then
|
||||
TS=$((TS + 60))
|
||||
else
|
||||
break
|
||||
fi
|
||||
done
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Generate release notes
|
||||
id: notes
|
||||
|
||||
@@ -45,6 +45,12 @@ with the Live credentials and switch the mode to Live in Settings.
|
||||
or a bonus event above a minimum amount. Amounts can be measured on the base donation or including fee cover.
|
||||
- **Overlays:** StreamGoals → Overlays. Copy a widget URL into OBS as a **Browser Source** (suggested 800×200
|
||||
for the goal bar; transparent background is built in). Keep the URL private; "Regenerate token" invalidates it.
|
||||
- **Rewards (actions for set amounts):** StreamGoals > Rewards. Add things you do on stream for a set amount, for example
|
||||
"$5: eat an every-flavor bean" or "$25: 25 pushups". Each reward is either *exactly this amount* or *every time the
|
||||
donation adds up to this amount* (a $10 donation triggers a $5 reward twice). Rewards appear as buttons on the donation
|
||||
form, as a **Rewards menu** overlay for OBS, and as a highlighted line in the donation alert. Triggered rewards land in a
|
||||
**queue** on the Rewards screen so you can tick them off as you do them. Rewards count the donation amount, not the
|
||||
optional fee cover, and must be at least your minimum donation.
|
||||
- **Test:** "Send test donation" on the Overlays screen shows an alert without touching real totals.
|
||||
|
||||
## Privacy and moderation
|
||||
|
||||
@@ -44,3 +44,10 @@
|
||||
.sg-admin .sg-filter { display: inline-block; margin: 8px 8px 8px 0; }
|
||||
.sg-admin .sg-table { max-width: 100%; }
|
||||
@media (max-width: 782px) { .sg-admin .sg-copy { flex-direction: column; align-items: stretch; } }
|
||||
/* 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 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; }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
.sga-help{list-style:disc;margin-left:1.4em}
|
||||
.sga-media{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
|
||||
.sga-media-name{font-weight:600;overflow-wrap:anywhere}
|
||||
.sga-media-warn{flex-basis:100%;margin:0;color:#996800}
|
||||
.sga-media-warn:empty{display:none}
|
||||
.sga-form input[type=range]{vertical-align:middle;width:220px;max-width:100%}
|
||||
.sga-stage{min-height:140px;display:flex;align-items:flex-end;justify-content:center;padding:16px;background:repeating-conic-gradient(#2b2b33 0 25%,#34343d 0 50%) 0 0/20px 20px;border-radius:6px;font-size:18px;color:#fff;line-height:1.2}
|
||||
.sga-alert{width:100%;max-width:560px;text-align:center;background:rgba(0,0,0,.45);border:2px solid #7c5cff;border-radius:12px;padding:10px 14px}
|
||||
.sga-alert-media{display:flex;justify-content:center;margin-bottom:6px}
|
||||
.sga-alert-media img,.sga-alert-media video{display:block;max-width:100%;max-height:260px;object-fit:contain;border-radius:6px}
|
||||
.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}
|
||||
@@ -0,0 +1,150 @@
|
||||
/* StreamGoals alert editor: Media Library pickers (wp.media) and a live preview that mirrors the overlay. */
|
||||
( function () {
|
||||
'use strict';
|
||||
var form = document.querySelector( '.sga-form' );
|
||||
var dataEl = document.getElementById( 'sga-data' );
|
||||
var stage = document.getElementById( 'sga-stage' );
|
||||
var playBtn = document.getElementById( 'sga-play' );
|
||||
if ( ! form || ! dataEl || ! stage || ! playBtn ) { return; }
|
||||
var cfg = { currency: 'USD', exp: 2, rewards: [], videoCap: 30000, warnBytes: 26214400, allowed: {} };
|
||||
try { cfg = JSON.parse( dataEl.textContent ); } catch ( e ) { /* defaults */ }
|
||||
var timers = [], media = [];
|
||||
|
||||
function el( tag, cls, text ) {
|
||||
var e = document.createElement( tag );
|
||||
if ( cls ) { e.className = cls; }
|
||||
if ( text != null ) { e.textContent = text; }
|
||||
return e;
|
||||
}
|
||||
|
||||
/* ---- Media Library pickers ---- */
|
||||
Array.prototype.forEach.call( form.querySelectorAll( '.sga-media' ), function ( box ) {
|
||||
var input = box.querySelector( 'input[type=hidden]' );
|
||||
var nameEl = box.querySelector( '.sga-media-name' );
|
||||
var warnEl = box.querySelector( '.sga-media-warn' );
|
||||
var kind = box.getAttribute( 'data-kind' );
|
||||
var frame = null;
|
||||
|
||||
function set( id, url, mime, name, size ) {
|
||||
input.value = String( id || 0 );
|
||||
input.setAttribute( 'data-url', url || '' );
|
||||
input.setAttribute( 'data-mime', mime || '' );
|
||||
nameEl.textContent = id ? name : 'Nothing chosen';
|
||||
var msg = '';
|
||||
if ( id && size > cfg.warnBytes ) {
|
||||
msg = 'This file is over 25 MB. Big files load slowly' + ( /^video\//.test( mime ) ? ' and large videos can make OBS stutter. A short, compressed clip is much better.' : '.' );
|
||||
}
|
||||
warnEl.textContent = msg;
|
||||
input.dispatchEvent( new Event( 'change', { bubbles: true } ) );
|
||||
}
|
||||
function accepts( mime ) {
|
||||
var k = cfg.allowed[ String( mime ).toLowerCase() ];
|
||||
return kind === 'sound' ? k === 'audio' : ( k === 'image' || k === 'video' );
|
||||
}
|
||||
box.querySelector( '.sga-pick' ).addEventListener( 'click', function () {
|
||||
if ( ! window.wp || ! wp.media ) { nameEl.textContent = 'The Media Library could not be loaded. Reload the page.'; return; }
|
||||
if ( ! frame ) {
|
||||
frame = wp.media( {
|
||||
title: kind === 'sound' ? 'Choose a sound' : 'Choose a picture, GIF or video',
|
||||
button: { text: 'Use this file' },
|
||||
library: { type: kind === 'sound' ? [ 'audio' ] : [ 'image', 'video' ] },
|
||||
multiple: false
|
||||
} );
|
||||
frame.on( 'select', function () {
|
||||
var a = frame.state().get( 'selection' ).first().toJSON();
|
||||
if ( ! accepts( a.mime ) ) {
|
||||
warnEl.textContent = 'That file type is not allowed (' + a.mime + '). ' + ( kind === 'sound' ? 'Use MP3, OGG or WAV.' : 'Use PNG, JPEG, GIF, WebP, MP4 or WebM.' );
|
||||
return;
|
||||
}
|
||||
set( a.id, a.url, a.mime, a.filename || a.title || ( 'File ' + a.id ), a.filesizeInBytes || 0 );
|
||||
} );
|
||||
}
|
||||
frame.open();
|
||||
} );
|
||||
box.querySelector( '.sga-clear' ).addEventListener( 'click', function () { set( 0, '', '', '', 0 ); } );
|
||||
} );
|
||||
|
||||
var vol = form.elements.volume, volOut = document.getElementById( 'sga_volume_out' );
|
||||
if ( vol && volOut ) { vol.addEventListener( 'input', function () { volOut.textContent = vol.value; } ); }
|
||||
|
||||
/* ---- preview ---- */
|
||||
function toMinor( raw ) {
|
||||
var s = String( raw == null ? '' : raw ).replace( /[,\s$€£¥]/g, '' );
|
||||
var m = /^(\d+)(?:\.(\d+))?$/.exec( s );
|
||||
if ( ! m ) { return null; }
|
||||
var frac = m[ 2 ] || '';
|
||||
if ( frac.length > cfg.exp ) { return null; }
|
||||
while ( frac.length < cfg.exp ) { frac += '0'; }
|
||||
return parseInt( m[ 1 ] + frac, 10 );
|
||||
}
|
||||
function money( minor ) {
|
||||
var s = String( minor );
|
||||
if ( cfg.exp === 0 ) { return cfg.currency + ' ' + s; }
|
||||
while ( s.length <= cfg.exp ) { s = '0' + s; }
|
||||
return cfg.currency + ' ' + s.slice( 0, -cfg.exp ) + '.' + s.slice( -cfg.exp );
|
||||
}
|
||||
function clean( s ) { return String( s ).replace( /<[^>]*>/g, '' ).replace( /[<>\u0000-\u001f\u007f]/g, ' ' ).replace( /\s+/g, ' ' ).trim(); }
|
||||
function render( tpl, vals ) {
|
||||
var t = clean( tpl );
|
||||
if ( ! t ) { return ''; }
|
||||
return t.replace( /\{([A-Za-z_]{1,20})\}/g, function ( m, k ) { return vals[ k.toLowerCase() ] || ''; } ).replace( /\s+/g, ' ' ).trim().slice( 0, 200 );
|
||||
}
|
||||
function stop() {
|
||||
timers.forEach( clearTimeout ); timers = [];
|
||||
media.forEach( function ( m ) { try { m.pause(); } catch ( e ) { /* ignore */ } } ); media = [];
|
||||
}
|
||||
function inp( name ) { return form.querySelector( '[name="' + name + '"]' ); }
|
||||
|
||||
function play() {
|
||||
stop();
|
||||
stage.textContent = '';
|
||||
var vis = inp( 'visual_id' ), snd = inp( 'sound_id' );
|
||||
var visUrl = vis.value !== '0' ? vis.getAttribute( 'data-url' ) : '', visMime = vis.getAttribute( 'data-mime' ) || '';
|
||||
var sndUrl = snd.value !== '0' ? snd.getAttribute( 'data-url' ) : '';
|
||||
var volume = Math.max( 0, Math.min( 100, parseInt( form.elements.volume.value, 10 ) || 0 ) ) / 100;
|
||||
var dur = Math.max( 1, Math.min( 60, parseFloat( form.elements.duration.value ) || 6 ) ) * 1000;
|
||||
var trig = form.querySelector( 'input[name="trigger_type"]:checked' );
|
||||
var amt = trig && trig.value === 'amount' ? toMinor( form.elements.amount.value ) : null;
|
||||
var rewardSel = form.elements.action_id;
|
||||
var reward = rewardSel && rewardSel.value !== '0' && rewardSel.selectedIndex > 0 ? rewardSel.options[ rewardSel.selectedIndex ].text.replace( / \(turned off\)$/, '' ) : 'Your reward';
|
||||
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 isVideo = /^video\//.test( visMime ), video = null;
|
||||
if ( visUrl ) {
|
||||
var box = el( 'div', 'sga-alert-media' );
|
||||
if ( isVideo ) {
|
||||
video = document.createElement( 'video' );
|
||||
video.playsInline = true; video.setAttribute( 'playsinline', '' );
|
||||
video.muted = !! sndUrl || volume === 0; video.volume = volume;
|
||||
video.src = visUrl; box.appendChild( video );
|
||||
} else {
|
||||
var img = new Image(); img.alt = ''; img.src = visUrl; box.appendChild( img );
|
||||
}
|
||||
card.appendChild( box );
|
||||
}
|
||||
var head = el( 'div', 'sga-alert-head' );
|
||||
if ( msg ) { head.textContent = msg; }
|
||||
else { head.appendChild( el( 'b', null, vals.name ) ); head.appendChild( document.createTextNode( ' donated ' ) ); head.appendChild( el( 'b', null, vals.amount ) ); }
|
||||
card.appendChild( head );
|
||||
stage.appendChild( card );
|
||||
|
||||
if ( sndUrl ) {
|
||||
var au = new Audio( sndUrl ); au.volume = volume; media.push( au );
|
||||
var p = au.play(); if ( p && p.catch ) { p.catch( function () { head.appendChild( el( 'div', 'sga-idle', 'Sound was blocked by the browser.' ) ); } ); }
|
||||
}
|
||||
var end = function () { stop(); stage.textContent = ''; stage.appendChild( el( 'span', 'sga-idle', 'Preview finished.' ) ); };
|
||||
if ( video ) {
|
||||
media.push( video );
|
||||
video.onended = end;
|
||||
var vp = video.play();
|
||||
if ( vp && vp.catch ) { vp.catch( function () { video.muted = true; var again = video.play(); if ( again && again.catch ) { again.catch( function () {} ); } } ); }
|
||||
timers.push( setTimeout( end, cfg.videoCap ) );
|
||||
} else {
|
||||
timers.push( setTimeout( end, dur ) );
|
||||
}
|
||||
}
|
||||
playBtn.addEventListener( 'click', play );
|
||||
stage.appendChild( el( 'span', 'sga-idle', 'Press "Play preview".' ) );
|
||||
}() );
|
||||
@@ -1,11 +1,13 @@
|
||||
.sg-donate{max-width:28rem;font:inherit}
|
||||
.sg-donate{max-width:min(100%,440px);font:inherit}
|
||||
.sg-donate .sg-row{margin:0 0 .9rem}
|
||||
.sg-donate label{display:block;font-weight:600;margin-bottom:.25rem}
|
||||
.sg-donate label.sg-inline{display:flex;gap:.5rem;align-items:center;font-weight:400}
|
||||
.sg-donate input[type=text],.sg-donate input[type=number],.sg-donate select,.sg-donate textarea{width:100%;box-sizing:border-box}
|
||||
.sg-donate .sg-presets{display:flex;flex-wrap:wrap;gap:.4rem;margin-bottom:.4rem}
|
||||
.sg-donate .sg-presets button{cursor:pointer}
|
||||
.sg-donate .sg-presets button[aria-pressed=true]{font-weight:700;outline:2px solid currentColor}
|
||||
.sg-donate .sg-presets button{position:relative}
|
||||
.sg-donate .sg-presets button[aria-pressed=true]{font-weight:700;outline:0;box-shadow:0 0 0 2px #fff,0 0 0 5px #1d2327}
|
||||
.sg-donate .sg-presets button[aria-pressed=true]::after{content:"\2713";position:absolute;top:.35rem;right:.6rem;font-weight:700}
|
||||
.sg-donate .sg-total{font-weight:700}
|
||||
.sg-donate .sg-msg{margin-top:.6rem}
|
||||
.sg-donate .sg-msg.sg-error{color:#b32d2e}
|
||||
@@ -14,7 +16,8 @@
|
||||
.sg-donate label.sg-sub{font-weight:400;margin:.2rem 0 .25rem}
|
||||
.sg-donate .sg-hint{font-size:.85em;opacity:.75;margin-top:.25rem}
|
||||
.sg-donate .sg-cover{display:flex;align-items:center;gap:.5rem}
|
||||
.sg-donate .sg-info{flex:none;width:1.4rem;height:1.4rem;padding:0;border-radius:50%;border:1.5px solid currentColor;background:transparent;color:inherit;font:italic 700 .85rem/1 Georgia,serif;cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
|
||||
.sg-donate .sg-info{flex:none;width:44px;height:44px;margin:-12px -12px -12px -8px;padding:0;position:relative;border:0;border-radius:50%;background:transparent;color:inherit;font:italic 700 14px/1 Georgia,serif;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;touch-action:manipulation}
|
||||
.sg-donate .sg-info::before{content:"";position:absolute;top:50%;left:50%;width:20px;height:20px;margin:-11px 0 0 -11px;border:1.5px solid currentColor;border-radius:50%;box-sizing:content-box}
|
||||
.sg-donate .sg-info:focus-visible{outline:2px solid currentColor;outline-offset:2px}
|
||||
.sg-donate .sg-tip{margin-top:.4rem;padding:.6rem .75rem;border:1px solid rgba(128,128,128,.5);border-radius:.4rem;font-size:.9em;line-height:1.4}
|
||||
.sg-donate .sg-presets.sg-actions{flex-direction:column;flex-wrap:nowrap;align-items:stretch}
|
||||
@@ -22,3 +25,13 @@
|
||||
.sg-donate .sg-act-title{font-weight:600}
|
||||
.sg-donate .sg-act-desc{font-size:.85em;font-weight:400;opacity:.8}
|
||||
.sg-donate .sg-presets button.sg-action:focus-visible{outline:2px solid currentColor;outline-offset:2px}
|
||||
|
||||
/* Mobile: 44px tap targets and 16px inputs (stops iOS Safari auto-zoom). px units on purpose: some themes shrink the root rem. */
|
||||
.sg-donate input[type=text],.sg-donate input[type=number],.sg-donate select,.sg-donate textarea{font-size:16px;min-height:44px}
|
||||
.sg-donate textarea{min-height:88px}
|
||||
.sg-donate .sg-presets button{min-height:44px}
|
||||
.sg-donate .sg-presets button.sg-action{min-height:44px}
|
||||
.sg-donate label.sg-inline{min-height:44px}
|
||||
.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}
|
||||
@@ -24,6 +24,8 @@ body.sg-offline #sg-root{opacity:.6}
|
||||
.sg-w-alerts #sg-root{align-items:flex-end}
|
||||
.sg-alert{width:100%;text-align:center;background:var(--sg-bg);border:.1em solid var(--sg-accent);border-radius:.7em;padding:.6em .9em;animation:sg-in .6s cubic-bezier(.22,1,.36,1) both}
|
||||
.sg-alert.sg-out{animation:sg-out .5s ease-in both}
|
||||
.sg-alert-media{display:flex;justify-content:center;margin-bottom:.4em}
|
||||
.sg-alert-media img,.sg-alert-media video{display:block;max-width:100%;max-height:45vh;object-fit:contain;border-radius:.4em;background:transparent}
|
||||
.sg-alert-head{font-weight:800;font-size:1.2em}
|
||||
.sg-alert-head b{color:var(--sg-accent2)}
|
||||
.sg-alert-msg{margin-top:.3em;font-size:.85em;overflow-wrap:anywhere;max-height:5.2em;overflow:hidden}
|
||||
@@ -38,8 +40,8 @@ body.sg-offline #sg-root{opacity:.6}
|
||||
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out,.sg-alert.sg-bonus,.sg-alert.sg-bonus.sg-out{animation:none}.sg-alert.sg-bonus{box-shadow:0 0 .8em var(--sg-accent2)}}
|
||||
.sg-w-actions #sg-root{align-items:flex-start}
|
||||
.sg-w-actions #sg-root:empty{display:none}
|
||||
.sg-menu{height:100%;display:flex;flex-direction:column;overflow:hidden}
|
||||
.sg-menu-view{flex:1;min-height:0;overflow:hidden}
|
||||
.sg-menu{height:auto;display:flex;flex-direction:column;overflow:hidden;font-size:calc(1em * var(--sg-menu-scale,1))}
|
||||
.sg-menu-view{flex:none;min-height:0;overflow:hidden}
|
||||
.sg-menu-list{list-style:none;margin:0;padding:0}
|
||||
.sg-menu-item{padding:.3em 0;font-weight:600;overflow-wrap:anywhere}
|
||||
.sg-menu-item b{color:var(--sg-accent2);font-weight:800}
|
||||
|
||||
+157
-17
@@ -113,16 +113,87 @@
|
||||
firstAlertPoll = false;
|
||||
next();
|
||||
}
|
||||
// Alert media (optional per alert): {visual:{type,url}|null, sound:{url}|null, volume, duration_ms, message}.
|
||||
// Everything is built with createElement + property assignment; nothing from the server is parsed as HTML.
|
||||
var MEDIA_TIMEOUT = 8000, DEFAULT_HOLD = 6500, VIDEO_CAP = 30000;
|
||||
function okUrl(u) { return typeof u === 'string' && /^(https?:\/\/|\/)/i.test(u); }
|
||||
function cleanMedia(m) {
|
||||
if (!m || typeof m !== 'object') return null;
|
||||
var v = m.visual && typeof m.visual === 'object' && okUrl(m.visual.url) && (m.visual.type === 'image' || m.visual.type === 'video') ? m.visual : null;
|
||||
var s = m.sound && typeof m.sound === 'object' && okUrl(m.sound.url) ? m.sound : null;
|
||||
var msg = typeof m.message === 'string' && m.message ? m.message : null;
|
||||
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 };
|
||||
}
|
||||
// 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.
|
||||
function preload(m, cb) {
|
||||
var out = { visual: null, sound: null }, pending = 0, fired = false, timer = 0;
|
||||
function finish() { if (fired) return; fired = true; clearTimeout(timer); cb(out); }
|
||||
function part() { pending++; var once = false; return function (ok, set) { if (once) return; once = true; if (ok && set) set(); if (--pending <= 0) finish(); }; }
|
||||
try {
|
||||
if (m.visual) {
|
||||
var vd = part();
|
||||
if (m.visual.type === 'image') {
|
||||
var img = new Image();
|
||||
img.onload = function () { vd(true, function () { out.visual = img; }); };
|
||||
img.onerror = function () { vd(false); };
|
||||
img.src = m.visual.url;
|
||||
} else {
|
||||
var vid = document.createElement('video');
|
||||
vid.preload = 'auto'; vid.playsInline = true; vid.muted = true;
|
||||
vid.setAttribute('playsinline', ''); vid.setAttribute('muted', '');
|
||||
vid.onloadeddata = function () { vd(true, function () { out.visual = vid; }); };
|
||||
vid.onerror = function () { vd(false); };
|
||||
vid.src = m.visual.url;
|
||||
try { vid.load(); } catch (e) { vd(false); }
|
||||
}
|
||||
}
|
||||
if (m.sound) {
|
||||
var sd = part();
|
||||
var au = new Audio();
|
||||
au.preload = 'auto';
|
||||
au.oncanplaythrough = function () { sd(true, function () { out.sound = au; }); };
|
||||
au.onerror = function () { sd(false); };
|
||||
au.src = m.sound.url;
|
||||
try { au.load(); } catch (e2) { sd(false); }
|
||||
}
|
||||
} catch (e3) { /* fall through to the timeout/finish below */ }
|
||||
if (!pending) { finish(); return; }
|
||||
timer = setTimeout(finish, MEDIA_TIMEOUT);
|
||||
}
|
||||
function next() {
|
||||
if (showing || !queue.length) return;
|
||||
showing = true;
|
||||
var a = queue.shift();
|
||||
var m = null;
|
||||
try { m = cleanMedia(a.media); } catch (e) { m = null; }
|
||||
if (!m) { present(a, null, null); return; }
|
||||
var called = false;
|
||||
function go(assets) { if (called) return; called = true; try { present(a, m, assets); } catch (err) { forceDone(); } }
|
||||
try { preload(m, go); } catch (e2) { go({ visual: null, sound: null }); }
|
||||
}
|
||||
function forceDone() { root.textContent = ''; showing = false; setTimeout(next, 0); }
|
||||
function present(a, m, assets) {
|
||||
root.textContent = '';
|
||||
var card = el('div', 'sg-alert');
|
||||
var head = el('div', 'sg-alert-head');
|
||||
head.appendChild(el('b', null, a.name));
|
||||
head.appendChild(document.createTextNode(' donated '));
|
||||
head.appendChild(el('b', null, a.amount_display));
|
||||
var vis = assets && assets.visual, snd = assets && assets.sound;
|
||||
if (vis) {
|
||||
var box = el('div', 'sg-alert-media');
|
||||
box.appendChild(vis);
|
||||
card.appendChild(box);
|
||||
card.classList.add('sg-has-media');
|
||||
}
|
||||
if (m && m.message) {
|
||||
head.textContent = m.message;
|
||||
} else {
|
||||
head.appendChild(el('b', null, a.name));
|
||||
head.appendChild(document.createTextNode(' donated '));
|
||||
head.appendChild(el('b', null, a.amount_display));
|
||||
}
|
||||
card.appendChild(head);
|
||||
var bonuses = Array.isArray(a.bonuses) ? a.bonuses : [];
|
||||
if (bonuses.length) {
|
||||
@@ -139,21 +210,98 @@
|
||||
}
|
||||
if (a.message) card.appendChild(el('div', 'sg-alert-msg', a.message));
|
||||
root.appendChild(card);
|
||||
setTimeout(function () {
|
||||
|
||||
var finished = false, holdTimer = 0, capTimer = 0;
|
||||
function stopMedia() {
|
||||
try { if (snd) snd.pause(); } catch (e) { /* ignore */ }
|
||||
try { if (vis && vis.tagName === 'VIDEO') { vis.pause(); vis.removeAttribute('src'); vis.load(); } } catch (e2) { /* ignore */ }
|
||||
}
|
||||
function exit() {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(holdTimer); clearTimeout(capTimer);
|
||||
stopMedia();
|
||||
card.classList.add('sg-out');
|
||||
setTimeout(function () { root.textContent = ''; showing = false; next(); }, 500);
|
||||
}, 6500);
|
||||
}
|
||||
var hold = m ? m.duration : DEFAULT_HOLD, isVideo = false;
|
||||
if (snd) {
|
||||
try {
|
||||
snd.volume = m.volume; snd.currentTime = 0;
|
||||
var sp = snd.play();
|
||||
if (sp && typeof sp.catch === 'function') sp.catch(function () { /* autoplay blocked: silent alert */ });
|
||||
} catch (e3) { /* ignore */ }
|
||||
}
|
||||
if (vis && vis.tagName === 'VIDEO') {
|
||||
isVideo = true;
|
||||
try {
|
||||
vis.loop = false;
|
||||
vis.muted = !!snd || m.volume === 0; // a separate sound wins; otherwise the clip's own audio at the set volume
|
||||
vis.volume = m.volume;
|
||||
vis.onended = exit;
|
||||
vis.onerror = exit;
|
||||
var vp = vis.play();
|
||||
if (vp && typeof vp.catch === 'function') {
|
||||
vp.catch(function () {
|
||||
// Autoplay with sound refused: retry muted so the picture still plays; give up (text only) if that fails too.
|
||||
try {
|
||||
vis.muted = true;
|
||||
var again = vis.play();
|
||||
if (again && typeof again.catch === 'function') again.catch(function () { if (vis.parentNode) vis.parentNode.removeChild(vis); clearTimeout(capTimer); holdTimer = setTimeout(exit, DEFAULT_HOLD); });
|
||||
} catch (e4) { exit(); }
|
||||
});
|
||||
}
|
||||
} catch (e5) { isVideo = false; }
|
||||
}
|
||||
if (isVideo) capTimer = setTimeout(exit, VIDEO_CAP); // videos play to the end, never longer than 30 s
|
||||
else holdTimer = setTimeout(exit, hold);
|
||||
}
|
||||
|
||||
// ---- actions (reward menu) ----
|
||||
// Renders nothing visible when there are no actions. Long lists scroll gently via CSS (--sg-rows sets the duration).
|
||||
var actionsSig = null;
|
||||
// Renders nothing visible when there are no actions. The card hugs its content and the text is scaled to the
|
||||
// LARGEST size that still fits the browser-source window (shrinks for long lists, grows for short ones), and
|
||||
// re-fits when the window is resized. Only if even the smallest size does not fit does it fall back to a gentle scroll.
|
||||
var actionsSig = null, menuEls = null, fitTimer = 0;
|
||||
var MENU_MIN = 0.5, MENU_MAX = 1.8;
|
||||
function fitMenu() {
|
||||
if (!menuEls) return;
|
||||
var card = menuEls.card, view = menuEls.view, track = menuEls.track, ul = menuEls.ul;
|
||||
// reset any previous scroll fallback
|
||||
track.classList.remove('sg-scrolling');
|
||||
while (track.children.length > 1) track.removeChild(track.lastChild);
|
||||
view.style.height = '';
|
||||
var cs = getComputedStyle(root);
|
||||
var inner = root.clientHeight - parseFloat(cs.paddingTop) - parseFloat(cs.paddingBottom);
|
||||
if (inner <= 0) return;
|
||||
function fits(scale) {
|
||||
card.style.setProperty('--sg-menu-scale', String(scale));
|
||||
return card.offsetHeight <= inner;
|
||||
}
|
||||
var lo = MENU_MIN, hi = MENU_MAX, best = null;
|
||||
if (fits(hi)) { best = hi; }
|
||||
else if (!fits(lo)) { best = null; }
|
||||
else { for (var i = 0; i < 9; i++) { var mid = (lo + hi) / 2; if (fits(mid)) { lo = mid; } else { hi = mid; } } best = lo; }
|
||||
if (best !== null) { card.style.setProperty('--sg-menu-scale', String(best)); return; }
|
||||
// Even the smallest size overflows: use the smallest and scroll gently inside the window.
|
||||
card.style.setProperty('--sg-menu-scale', String(MENU_MIN));
|
||||
var chrome = card.offsetHeight - view.offsetHeight;
|
||||
view.style.height = Math.max(40, inner - chrome) + 'px';
|
||||
var dup = ul.cloneNode(true);
|
||||
dup.setAttribute('aria-hidden', 'true');
|
||||
track.appendChild(dup);
|
||||
track.style.setProperty('--sg-scroll-s', Math.max(8, menuEls.count * 3) + 's');
|
||||
track.classList.add('sg-scrolling');
|
||||
}
|
||||
function scheduleFit() { clearTimeout(fitTimer); fitTimer = setTimeout(fitMenu, 120); }
|
||||
window.addEventListener('resize', scheduleFit);
|
||||
if (typeof ResizeObserver === 'function') { try { new ResizeObserver(scheduleFit).observe(document.documentElement); } catch (e) { /* resize event is the fallback */ } }
|
||||
function renderActions(d) {
|
||||
var list = Array.isArray(d.actions) ? d.actions : [];
|
||||
var sig = JSON.stringify(list);
|
||||
if (sig === actionsSig) return;
|
||||
actionsSig = sig;
|
||||
root.textContent = '';
|
||||
menuEls = null;
|
||||
if (!d.active || !list.length) return;
|
||||
var card = el('div', 'sg-card sg-menu');
|
||||
var view = el('div', 'sg-menu-view');
|
||||
@@ -171,16 +319,8 @@
|
||||
view.appendChild(track);
|
||||
card.appendChild(view);
|
||||
root.appendChild(card);
|
||||
// Overflow check after layout: duplicate the list for a seamless loop and start the CSS scroll.
|
||||
requestAnimationFrame(function () {
|
||||
if (ul.scrollHeight > view.clientHeight + 2) {
|
||||
var dup = ul.cloneNode(true);
|
||||
dup.setAttribute('aria-hidden', 'true');
|
||||
track.appendChild(dup);
|
||||
track.style.setProperty('--sg-scroll-s', Math.max(8, list.length * 3) + 's');
|
||||
track.classList.add('sg-scrolling');
|
||||
}
|
||||
});
|
||||
menuEls = { card: card, view: view, track: track, ul: ul, count: list.length };
|
||||
requestAnimationFrame(fitMenu);
|
||||
}
|
||||
|
||||
// ---- polling ----
|
||||
|
||||
@@ -73,3 +73,22 @@ PHP (namespace `StreamGoals\Actions`):
|
||||
- `Recorder::forDonation(int $donationId): void` — called after a donation becomes `completed` (same place the rules engine is applied); matches on the donation's BASE amount (not fee cover) using the goal's enabled actions and records events. Never throws.
|
||||
Public/overlay: the donate form shows each enabled action as a button (amount + title); the overlay has a new `actions` widget (the menu for the active goal) and alert payloads gain `actions`: `[ {title, times} ]` read from sg_action_events (anonymous donors' actions are still shown; names stay masked).
|
||||
Amounts must be >= Settings::effectiveMin().
|
||||
|
||||
## Schema v3 (Installer, DB_VERSION 3)
|
||||
- `sg_goals.close_at_target` TINYINT: when 1, the goal is closed to donors as soon as its raised total reaches or exceeds the target (status becomes `complete`, same as the manual "Complete" action).
|
||||
- `sg_alert_defs` — owner-defined alert presentations (media from the WordPress Media Library; attachment ids, never raw URLs):
|
||||
id, goal_id (0 = all goals), trigger_type `amount` | `reward`, min_minor (for `amount`: applies when the donation BASE amount >= min_minor; the highest matching min_minor wins),
|
||||
action_id (for `reward`: applies when that reward triggered; a reward definition wins over an amount definition), title (admin label),
|
||||
visual_id + visual_type (`image` | `video` | '' none), sound_id (audio attachment, 0 none), volume 0-100, duration_ms (how long an image/GIF stays; videos play to the end, capped),
|
||||
message (template with {name} {amount} {reward}; '' = default text), enabled, sort, created_at.
|
||||
|
||||
## Goal tiers (milestones) — contract (Installer DB_VERSION 4)
|
||||
A goal may have ordered TIERS; each is a cumulative target with an item/unlock (e.g. $100 "Giveaway", $250 "New microphone", $500 "24-hour stream").
|
||||
- `sg_goal_tiers`: id, goal_id, target_minor (cumulative raised total needed), title VARCHAR(120) (the item/unlock), description VARCHAR(255), reached_at DATETIME NULL,
|
||||
reached_donation_id BIGINT UNSIGNED NULL, created_at; UNIQUE(goal_id, target_minor). Tier order = target_minor ascending.
|
||||
- A goal WITH tiers keeps `sg_goals.target_minor` equal to its HIGHEST tier target (maintained automatically when tiers change; the goal form shows the target as derived/read-only). So "end at target" closes the goal when the FINAL tier is reached, and everything that reads goal target keeps working.
|
||||
- Raised total for tiers uses the same basis as the goal (`GoalRepository::raised_minor`, base vs total per counts_fees).
|
||||
- Reaching a tier: after a donation is completed (same finalize path as rules/actions, BEFORE the close-at-target check, never throwing, idempotent): for every tier of the goal with reached_at IS NULL and target_minor <= raised, set reached_at=NOW and reached_donation_id=that donation with `UPDATE ... WHERE id=? AND reached_at IS NULL` (a big donation can unlock several tiers at once; all get its id).
|
||||
- "Current tier" = the first tier (by target) with reached_at IS NULL. Goal bar progress for a tiered goal = (raised - floor) / (target - floor) clamped 0..1, where floor = previous tier's target (0 for the first); the cumulative raised and the current tier target are still displayed.
|
||||
- Reached tiers: title/description editable, target locked; a new tier's target must be above the goal's current raised total and unique.
|
||||
- Overlay `goal` payload for a tiered goal adds `tiers: {count, index (1-based current), current:{title,description,target_minor,target_display,floor_minor}|null, all_reached}`; untiered goals are unchanged. Alert payloads gain `tiers: [{title}]` = tiers whose reached_donation_id is that donation, shown as a "TIER UNLOCKED: title" pill.
|
||||
@@ -28,6 +28,9 @@ final class Admin {
|
||||
'sg_action_save' => array( ActionsPage::class, 'handleSave' ),
|
||||
'sg_action_toggle' => array( ActionsPage::class, 'handleToggle' ),
|
||||
'sg_action_delete' => array( ActionsPage::class, 'handleDelete' ),
|
||||
'sg_alert_save' => array( AlertsPage::class, 'handleSave' ),
|
||||
'sg_alert_toggle' => array( AlertsPage::class, 'handleToggle' ),
|
||||
'sg_alert_delete' => array( AlertsPage::class, 'handleDelete' ),
|
||||
'sg_event_done' => array( ActionsPage::class, 'handleDone' ),
|
||||
'sg_event_done_all' => array( ActionsPage::class, 'handleDoneAll' ),
|
||||
'sg_export_csv' => array( DonationsPage::class, 'handleExport' ),
|
||||
@@ -65,6 +68,7 @@ final class Admin {
|
||||
$queued = ActionsPage::queuedCount();
|
||||
$qbadge = $queued > 0 ? ' <span class="awaiting-mod">' . (int) $queued . '</span>' : '';
|
||||
add_submenu_page( self::HOME, 'Rewards', 'Rewards' . $qbadge, self::CAP, ActionsPage::PAGE, array( ActionsPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Alerts', 'Alerts', self::CAP, AlertsPage::PAGE, array( AlertsPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Overlays', 'Overlays', self::CAP, 'streamgoals-overlays', array( OverlaysPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Settings', 'Settings', self::CAP, 'streamgoals-settings', array( SettingsPage::class, 'render' ) );
|
||||
}
|
||||
@@ -101,6 +105,11 @@ final class Admin {
|
||||
if ( ActionsPage::PAGE === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-actions', STREAMGOALS_URL . 'assets/admin/actions.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
if ( AlertsPage::PAGE === $page ) {
|
||||
wp_enqueue_media();
|
||||
wp_enqueue_style( 'streamgoals-alerts', STREAMGOALS_URL . 'assets/admin/alerts.css', array( 'streamgoals-admin' ), STREAMGOALS_VERSION );
|
||||
wp_enqueue_script( 'streamgoals-alerts', STREAMGOALS_URL . 'assets/admin/alerts.js', array( 'streamgoals-admin', 'jquery' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
if ( 'streamgoals-overlays' === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-overlays', STREAMGOALS_URL . 'assets/admin/overlays.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
|
||||
@@ -0,0 +1,238 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Actions\ActionRepository;
|
||||
use StreamGoals\Alerts\DefInput;
|
||||
use StreamGoals\Alerts\DefRepository;
|
||||
use StreamGoals\Alerts\Media;
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/** "Alerts": pictures, GIFs, videos and sounds that play on the alerts overlay for certain donations or rewards. */
|
||||
final class AlertsPage {
|
||||
|
||||
public const PAGE = 'streamgoals-alerts';
|
||||
|
||||
private static function repo(): DefRepository {
|
||||
return new DefRepository();
|
||||
}
|
||||
|
||||
private static function minMinor(): int {
|
||||
return Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
|
||||
}
|
||||
|
||||
private static function url( array $args = array() ): string {
|
||||
return Admin::url( self::PAGE, $args );
|
||||
}
|
||||
|
||||
/** @return array<int,string> goal id => title */
|
||||
private static function goalTitles(): array {
|
||||
$out = array();
|
||||
foreach ( Store::goals()->all() as $g ) {
|
||||
$out[ (int) $g['id'] ] = (string) $g['title'];
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Attachment lookup for validation: mime + size, null when missing. */
|
||||
public static function attachmentInfo( int $id ): ?array {
|
||||
if ( $id <= 0 || 'attachment' !== get_post_type( $id ) ) {
|
||||
return null;
|
||||
}
|
||||
$path = get_attached_file( $id );
|
||||
return array(
|
||||
'mime' => (string) get_post_mime_type( $id ),
|
||||
'size' => ( is_string( $path ) && is_file( $path ) ) ? (int) filesize( $path ) : 0,
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- render */
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'Alerts' );
|
||||
$edit = Admin::get_int( 'edit' );
|
||||
if ( 'new' === Admin::get_str( 'view' ) || $edit ) {
|
||||
self::renderForm( $edit );
|
||||
} else {
|
||||
self::renderHelp();
|
||||
self::renderList();
|
||||
}
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
private static function renderHelp(): void {
|
||||
echo '<div class="sg-card"><h2>Make your alerts come alive</h2>';
|
||||
echo '<p>An alert is the pop-up on your stream when someone donates. Here you can give it a picture, a GIF or a video, and a sound. Pick the donation size (or a reward) that should trigger it.</p>';
|
||||
echo '<ul class="sga-help">';
|
||||
echo '<li><strong>By amount:</strong> "Any donation of at least $X". If several match, the one with the highest $X wins.</li>';
|
||||
echo '<li><strong>By reward:</strong> plays when a donor triggers one of your rewards. A reward alert beats an amount alert.</li>';
|
||||
echo '<li>Nothing set up? Alerts look and work exactly as before.</li>';
|
||||
echo '<li><strong>In OBS media plays automatically. In a normal browser tab you must click the page once before sound is allowed.</strong></li>';
|
||||
echo '<li>Pictures and GIFs stay for the time you choose. Videos play to the end, for at most 30 seconds.</li>';
|
||||
echo '<li>Keep files small (under 25 MB). Big videos make OBS slow to load and can make your stream stutter.</li>';
|
||||
echo '</ul></div>';
|
||||
}
|
||||
|
||||
private static function renderList(): void {
|
||||
$cur = Admin::currency();
|
||||
$defs = self::repo()->all();
|
||||
$goals = self::goalTitles();
|
||||
$rewards = array();
|
||||
foreach ( ( new ActionRepository() )->all() as $a ) {
|
||||
$rewards[ $a['id'] ] = $a['title'];
|
||||
}
|
||||
echo '<div class="sg-card"><h2>Your alerts</h2>';
|
||||
echo '<p><a class="button button-primary" href="' . esc_url( self::url( array( 'view' => 'new' ) ) ) . '">Add an alert</a></p>';
|
||||
if ( ! $defs ) {
|
||||
echo '<p>No custom alerts yet.</p></div>';
|
||||
return;
|
||||
}
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Name</th><th>Plays when</th><th>Applies to</th><th>Media</th><th>Order</th><th>Actions</th></tr></thead><tbody>';
|
||||
foreach ( $defs as $d ) {
|
||||
$id = (int) $d['id'];
|
||||
$when = 'reward' === $d['trigger_type']
|
||||
? 'Reward: ' . ( $rewards[ $d['action_id'] ] ?? 'a reward that was deleted' )
|
||||
: 'Donation of at least ' . Format::money( (int) $d['min_minor'], $cur );
|
||||
$media = array();
|
||||
if ( $d['visual_id'] ) {
|
||||
$media[] = 'video' === $d['visual_type'] ? 'Video' : 'Picture/GIF';
|
||||
}
|
||||
if ( $d['sound_id'] ) {
|
||||
$media[] = 'Sound';
|
||||
}
|
||||
echo '<tr' . ( $d['enabled'] ? '' : ' class="sg-off"' ) . '><td><strong>' . esc_html( $d['title'] ) . '</strong></td>';
|
||||
echo '<td>' . esc_html( $when ) . '</td>';
|
||||
echo '<td>' . esc_html( 0 === $d['goal_id'] ? 'All goals' : ( $goals[ $d['goal_id'] ] ?? 'Goal #' . $d['goal_id'] ) ) . '</td>';
|
||||
echo '<td>' . esc_html( $media ? implode( ', ', $media ) : 'Text only' ) . '</td>';
|
||||
echo '<td>' . (int) $d['sort'] . '</td><td class="sg-actions">';
|
||||
echo '<a class="button" href="' . esc_url( self::url( array( 'edit' => $id ) ) ) . '">Edit</a> ';
|
||||
Admin::form( 'sg_alert_toggle', array( 'alert_id' => $id, 'enabled' => $d['enabled'] ? 0 : 1 ), 'sg-inline' );
|
||||
echo '<button class="button">' . ( $d['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
|
||||
Admin::form( 'sg_alert_delete', array( 'alert_id' => $id ), 'sg-inline sg-confirm' );
|
||||
echo '<button class="button button-link-delete" data-confirm="Delete this alert? Your media files stay in the Media Library.">Delete</button></form>';
|
||||
echo '</td></tr>';
|
||||
}
|
||||
echo '</tbody></table></div>';
|
||||
}
|
||||
|
||||
private static function mediaField( string $name, string $label, string $kind, int $id, string $help ): void {
|
||||
$url = '';
|
||||
$mime = '';
|
||||
if ( $id > 0 && null !== self::attachmentInfo( $id ) ) {
|
||||
$url = (string) wp_get_attachment_url( $id );
|
||||
$mime = (string) get_post_mime_type( $id );
|
||||
}
|
||||
echo '<tr><th scope="row">' . esc_html( $label ) . '</th><td>';
|
||||
echo '<div class="sga-media" data-kind="' . esc_attr( $kind ) . '">';
|
||||
echo '<input type="hidden" name="' . esc_attr( $name ) . '" value="' . ( $id > 0 ? (int) $id : 0 ) . '" data-url="' . esc_attr( $url ) . '" data-mime="' . esc_attr( $mime ) . '">';
|
||||
echo '<span class="sga-media-name">' . esc_html( '' !== $url ? wp_basename( $url ) : 'Nothing chosen' ) . '</span> ';
|
||||
echo '<button type="button" class="button sga-pick">Choose from Media Library</button> ';
|
||||
echo '<button type="button" class="button sga-clear">Remove</button>';
|
||||
echo '<p class="description sga-media-warn" role="status"></p>';
|
||||
echo '</div><p class="description">' . esc_html( $help ) . '</p></td></tr>';
|
||||
}
|
||||
|
||||
private static function renderForm( int $id ): void {
|
||||
$d = $id ? self::repo()->find( $id ) : null;
|
||||
if ( $id && ! $d ) {
|
||||
echo '<p>That alert no longer exists. <a href="' . esc_url( self::url() ) . '">Back to alerts</a></p>';
|
||||
return;
|
||||
}
|
||||
$cur = Admin::currency();
|
||||
$goals = self::goalTitles();
|
||||
$val = static fn( string $k, $default = '' ) => $d[ $k ] ?? $default;
|
||||
$trigger = (string) $val( 'trigger_type', 'amount' );
|
||||
$rewards = array();
|
||||
foreach ( ( new ActionRepository() )->all() as $a ) {
|
||||
if ( $a['enabled'] || (int) $a['id'] === (int) $val( 'action_id', 0 ) ) {
|
||||
$rewards[] = array( 'id' => $a['id'], 'title' => $a['title'], 'enabled' => (bool) $a['enabled'] );
|
||||
}
|
||||
}
|
||||
$data = array(
|
||||
'currency' => $cur,
|
||||
'exp' => Money::exponent( $cur ),
|
||||
'rewards' => $rewards,
|
||||
'videoCap' => Media::VIDEO_CAP_MS,
|
||||
'warnBytes' => Media::WARN_BYTES,
|
||||
'allowed' => Media::MIMES,
|
||||
);
|
||||
|
||||
echo '<h2>' . ( $d ? 'Edit alert' : 'Add an alert' ) . '</h2>';
|
||||
Admin::form( 'sg_alert_save', array( 'alert_id' => $id ), 'sga-form' );
|
||||
echo '<table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sga_title">Name</label></th><td><input type="text" required maxlength="120" id="sga_title" name="title" class="regular-text" value="' . esc_attr( (string) $val( 'title' ) ) . '"><p class="description">Only you see this, for example "Big donation fireworks".</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sga_goal">Applies to</label></th><td><select id="sga_goal" name="goal_id"><option value="0"' . selected( (int) $val( 'goal_id', 0 ), 0, false ) . '>All goals</option>';
|
||||
foreach ( $goals as $gid => $title ) {
|
||||
echo '<option value="' . (int) $gid . '"' . selected( (int) $val( 'goal_id', 0 ), $gid, false ) . '>' . esc_html( $title ) . '</option>';
|
||||
}
|
||||
echo '</select></td></tr>';
|
||||
echo '<tr><th scope="row">Plays when</th><td>';
|
||||
echo '<label><input type="radio" name="trigger_type" value="amount"' . checked( $trigger, 'amount', false ) . '> Any donation of at least <input type="text" inputmode="decimal" name="amount" class="small-text" value="' . esc_attr( $d && 'amount' === $trigger ? Format::decimal( (int) $d['min_minor'], $cur ) : '' ) . '"> ' . esc_html( $cur ) . '</label>';
|
||||
echo '<p class="description">At least ' . esc_html( Format::money( self::minMinor(), $cur ) ) . ' (your minimum donation). If several amount alerts match, the one with the highest amount wins.</p>';
|
||||
echo '<label><input type="radio" name="trigger_type" value="reward"' . checked( $trigger, 'reward', false ) . '> When a reward is triggered:</label> <select name="action_id"><option value="0">Choose a reward</option>';
|
||||
foreach ( $rewards as $r ) {
|
||||
echo '<option value="' . (int) $r['id'] . '"' . selected( (int) $val( 'action_id', 0 ), (int) $r['id'], false ) . '>' . esc_html( $r['title'] . ( $r['enabled'] ? '' : ' (turned off)' ) ) . '</option>';
|
||||
}
|
||||
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"><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>';
|
||||
echo '<tr><th scope="row"><label for="sga_sort">Order</label></th><td><input type="number" min="0" max="99999" id="sga_sort" name="sort" class="small-text" value="' . ( $d ? (int) $d['sort'] : '' ) . '"><p class="description">Lower numbers win when two alerts are otherwise equal. Leave empty to put it last.</p></td></tr>';
|
||||
echo '</table>';
|
||||
|
||||
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 '<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>';
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- handlers */
|
||||
|
||||
public static function handleSave(): void {
|
||||
Admin::guard( 'sg_alert_save' );
|
||||
$post = Admin::post_raw();
|
||||
$id = isset( $post['alert_id'] ) ? absint( $post['alert_id'] ) : 0;
|
||||
$back = self::url( $id ? array( 'edit' => $id ) : array( 'view' => 'new' ) );
|
||||
$repo = self::repo();
|
||||
if ( $id && ! $repo->find( $id ) ) {
|
||||
Admin::redirect( self::url(), 'error', 'That alert no longer exists.' );
|
||||
}
|
||||
$enabled = array();
|
||||
foreach ( ( new ActionRepository() )->all() as $a ) {
|
||||
if ( $a['enabled'] ) {
|
||||
$enabled[] = (int) $a['id'];
|
||||
}
|
||||
}
|
||||
$res = DefInput::validate( $post, self::minMinor(), Admin::currency(), array_keys( self::goalTitles() ), $enabled, array( self::class, 'attachmentInfo' ), $repo->nextSort() );
|
||||
if ( null === $res['data'] ) {
|
||||
Admin::redirect( $back, 'error', (string) $res['error'] );
|
||||
}
|
||||
if ( $id ) {
|
||||
$repo->update( $id, $res['data'] );
|
||||
} else {
|
||||
$repo->create( $res['data'] );
|
||||
}
|
||||
$msg = 'Alert saved.' . ( $res['warnings'] ? ' Heads up: ' . implode( ' ', $res['warnings'] ) : '' );
|
||||
Admin::redirect( self::url(), $res['warnings'] ? 'warning' : 'success', $msg );
|
||||
}
|
||||
|
||||
public static function handleToggle(): void {
|
||||
Admin::guard( 'sg_alert_toggle' );
|
||||
$post = Admin::post_raw();
|
||||
self::repo()->setEnabled( isset( $post['alert_id'] ) ? absint( $post['alert_id'] ) : 0, ! empty( $post['enabled'] ) );
|
||||
Admin::redirect( self::url(), 'success', 'Alert updated.' );
|
||||
}
|
||||
|
||||
public static function handleDelete(): void {
|
||||
Admin::guard( 'sg_alert_delete' );
|
||||
$post = Admin::post_raw();
|
||||
self::repo()->delete( isset( $post['alert_id'] ) ? absint( $post['alert_id'] ) : 0 );
|
||||
Admin::redirect( self::url(), 'success', 'Alert deleted.' );
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,7 @@ final class GoalsPage {
|
||||
$pct = $target > 0 ? min( 100, intdiv( $raised * 100, $target ) ) : 0;
|
||||
echo '<tr><td><strong>' . esc_html( (string) $g['title'] ) . '</strong><br><span class="description">ID ' . $gid . ' · <code>[streamgoals_donate goal="' . $gid . '"]</code></span></td>';
|
||||
echo '<td><span class="sg-badge sg-' . esc_attr( (string) $g['status'] ) . '">' . esc_html( self::STATUSES[ $g['status'] ] ?? (string) $g['status'] ) . '</span></td>';
|
||||
echo '<td>' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div></td>';
|
||||
echo '<td>' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div>' . ( ! empty( $g['close_at_target'] ) ? '<span class="description">Closes at target</span>' : '' ) . '</td>';
|
||||
echo '<td>' . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '<br>' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '</td><td class="sg-actions">';
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'edit', 'goal' => $gid ) ) ) . '">Edit</a> ';
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ) ) . '">Rules</a> ';
|
||||
@@ -90,6 +90,7 @@ final class GoalsPage {
|
||||
echo '<tr><th scope="row"><label for="sg_start">Starts</label></th><td><input type="datetime-local" id="sg_start" name="starts_at" value="' . esc_attr( $fmt( $g['starts_at'] ?? null ) ) . '"> <span class="description">Optional. Your site time zone. Empty = starts immediately.</span></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_end">Ends</label></th><td><input type="datetime-local" id="sg_end" name="ends_at" value="' . esc_attr( $fmt( $g['ends_at'] ?? null ) ) . '"> <span class="description">Optional. Donations stop after this time.</span></td></tr>';
|
||||
echo '<tr><th scope="row">Fees</th><td><label><input type="checkbox" name="counts_fees" value="1"' . checked( ! empty( $g['counts_fees'] ), true, false ) . '> Count fees covered by donors towards the goal</label><p class="description">Off (recommended): only the amount the donor chose counts, so a $10 donation always adds $10 even if they also covered the fee.</p></td></tr>';
|
||||
echo '<tr><th scope="row">End at target</th><td><label><input type="checkbox" name="close_at_target" value="1"' . checked( ! empty( $g['close_at_target'] ), true, false ) . '> Close this goal to donations when the target is reached</label><p class="description">When the raised total reaches or goes over the target, the goal is marked complete and the donation page stops taking donations to it. Donations already in checkout still complete. You can reopen it with "Reopen" (raise the target first if you want more donations: a reopened goal that is still at or over its target closes again after the next donation).</p></td></tr>';
|
||||
echo '</table><p><button class="button button-primary">' . ( $g ? 'Save goal' : 'Create goal' ) . '</button> <a class="button" href="' . esc_url( Admin::url() ) . '">Cancel</a></p></form>';
|
||||
Admin::close();
|
||||
}
|
||||
@@ -131,7 +132,7 @@ final class GoalsPage {
|
||||
if ( $start && $end && strtotime( $end . ' UTC' ) <= strtotime( $start . ' UTC' ) ) {
|
||||
Admin::redirect( $back, 'error', 'The end must be after the start.' );
|
||||
}
|
||||
$data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1 );
|
||||
$data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1, 'close_at_target' => \StreamGoals\Core\GoalTargetPolicy::flagFromPost( $post['close_at_target'] ?? null ) );
|
||||
if ( $id ) {
|
||||
Store::goals()->update( $id, $data );
|
||||
} else {
|
||||
|
||||
@@ -56,7 +56,7 @@ final class SettingsPage {
|
||||
foreach ( \StreamGoals\Core\ClientIp::MODES as $k => $l ) {
|
||||
echo '<option value="' . esc_attr( $k ) . '"' . selected( (string) $s['visitor_ip_header'], $k, false ) . '>' . esc_html( $l ) . '</option>';
|
||||
}
|
||||
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). If your site is behind Cloudflare or another proxy, choose it here so each visitor is counted separately; otherwise everyone looks like the same visitor and a busy moment, like a raid, could block donations. Only choose a proxy option if <em>all</em> traffic to your site really goes through it.</p>';
|
||||
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). Behind a proxy, every visitor can look like the same address, and a busy moment, like a raid, could block donations. <strong>Automatic</strong> recognises Cloudflare by its published addresses and counts each visitor separately; it ignores forged headers from anywhere else. For another kind of proxy, choose its option here, but only if <em>all</em> traffic to your site really goes through it.</p>';
|
||||
self::ipDiagnostics( (string) $s['visitor_ip_header'] );
|
||||
echo '</td></tr></table></div>';
|
||||
|
||||
@@ -80,7 +80,7 @@ final class SettingsPage {
|
||||
|
||||
/** Shows the owner what their server passes to the plugin right now, to help pick the right option. */
|
||||
private static function ipDiagnostics( string $mode ): void {
|
||||
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
|
||||
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_CF_RAY' => 'CF-Ray', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
|
||||
$server = array();
|
||||
foreach ( $keys as $k => $_ ) {
|
||||
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
|
||||
@@ -91,8 +91,10 @@ final class SettingsPage {
|
||||
foreach ( $keys as $k => $label ) {
|
||||
echo '<tr><td>' . esc_html( $label ) . '</td><td><code>' . ( isset( $server[ $k ] ) ? esc_html( $server[ $k ] ) : '(not sent)' ) . '</code></td></tr>';
|
||||
}
|
||||
$viaCf = isset( $server['REMOTE_ADDR'] ) && \StreamGoals\Core\CloudflareRanges::isCloudflare( $server['REMOTE_ADDR'], (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
|
||||
echo '<tr><td>Is this connection from Cloudflare?</td><td>' . ( $viaCf ? '<strong>Yes</strong> - the connection comes from a Cloudflare address' : 'No' ) . '</td></tr>';
|
||||
echo '<tr><td><strong>Visitor address used with the saved option</strong></td><td><code>' . esc_html( \StreamGoals\Core\ClientIp::resolve( $server, $mode ) ) . '</code></td></tr>';
|
||||
echo '</tbody></table><p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
|
||||
echo '</tbody></table>' . ( ! $viaCf && ( isset( $server['HTTP_CF_RAY'] ) || isset( $server['HTTP_CF_CONNECTING_IP'] ) ) ? '<p class="sg-warn">Cloudflare headers were sent, but the connection is not from a known Cloudflare address, so "Automatic" ignores them. If your site really is behind Cloudflare, choose "Cloudflare" above (or update the plugin, as Cloudflare may have added new addresses).</p>' : '' ) . '<p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
|
||||
}
|
||||
|
||||
public static function handleSave(): void {
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/**
|
||||
* Builds the public `media` block for one alert. URLs only ever come from the $attachment callback
|
||||
* (WordPress attachment lookup); the DB row contributes ids, never URLs.
|
||||
*/
|
||||
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
|
||||
*/
|
||||
public static function build( array $row, string $name, string $amountDisplay, array $defs, array $triggered, callable $attachment ): ?array {
|
||||
if ( ! $defs ) {
|
||||
return null;
|
||||
}
|
||||
$ids = array();
|
||||
$amounts = array();
|
||||
foreach ( $triggered as $t ) {
|
||||
$aid = (int) ( $t['action_id'] ?? 0 );
|
||||
$ids[] = $aid;
|
||||
$amounts[ $aid ] = (int) ( $t['amount_minor'] ?? 0 );
|
||||
}
|
||||
$def = Resolver::pick( (int) ( $row['goal_id'] ?? 0 ), (int) ( $row['base_minor'] ?? 0 ), $ids, $defs, $amounts );
|
||||
if ( null === $def ) {
|
||||
return null;
|
||||
}
|
||||
return self::fromDef( $def, $name, $amountDisplay, $triggered, $attachment );
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public static function fromDef( array $def, string $name, string $amountDisplay, array $triggered, callable $attachment ): ?array {
|
||||
$visual = null;
|
||||
$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'] );
|
||||
}
|
||||
}
|
||||
$sound = null;
|
||||
$sid = (int) ( $def['sound_id'] ?? 0 );
|
||||
if ( $sid > 0 ) {
|
||||
$a = self::lookup( $attachment, $sid );
|
||||
if ( $a && Media::isSound( $a['mime'] ) ) {
|
||||
$sound = array( 'url' => $a['url'] );
|
||||
}
|
||||
}
|
||||
$reward = '';
|
||||
$best = -1;
|
||||
foreach ( $triggered as $t ) {
|
||||
$amt = (int) ( $t['amount_minor'] ?? 0 );
|
||||
if ( 'reward' === ( $def['trigger_type'] ?? '' ) ) {
|
||||
if ( (int) ( $t['action_id'] ?? 0 ) === (int) $def['action_id'] ) {
|
||||
$reward = (string) ( $t['title'] ?? '' );
|
||||
break;
|
||||
}
|
||||
} elseif ( $amt > $best ) {
|
||||
$best = $amt;
|
||||
$reward = (string) ( $t['title'] ?? '' );
|
||||
}
|
||||
}
|
||||
$msg = Template::render( (string) ( $def['message'] ?? '' ), $name, $amountDisplay, $reward );
|
||||
if ( null === $visual && null === $sound && '' === $msg ) {
|
||||
return null; // nothing usable left: behave exactly as a plain alert
|
||||
}
|
||||
$duration = Media::clampDurationMs( $def['duration_ms'] ?? Media::DEFAULT_MS );
|
||||
if ( $visual && 'video' === $visual['type'] ) {
|
||||
$duration = Media::VIDEO_CAP_MS;
|
||||
}
|
||||
return array(
|
||||
'visual' => $visual,
|
||||
'sound' => $sound,
|
||||
'volume' => Media::clampVolume( $def['volume'] ?? 80 ),
|
||||
'duration_ms' => $duration,
|
||||
'message' => '' === $msg ? null : $msg,
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array{url:string,mime:string}|null */
|
||||
private static function lookup( callable $attachment, int $id ): ?array {
|
||||
try {
|
||||
$a = $attachment( $id );
|
||||
} catch ( \Throwable ) {
|
||||
return null;
|
||||
}
|
||||
if ( ! is_array( $a ) || ! Media::isAllowed( $a['mime'] ?? null ) ) {
|
||||
return null;
|
||||
}
|
||||
$url = Media::safeUrl( $a['url'] ?? null );
|
||||
return null === $url ? null : array( 'url' => $url, 'mime' => (string) $a['mime'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
use StreamGoals\Admin\Input;
|
||||
|
||||
/** Pure validation/sanitizing for the alert definition form. */
|
||||
final class DefInput {
|
||||
|
||||
/**
|
||||
* @param int[] $validGoalIds Existing goal ids (0 = all goals always allowed).
|
||||
* @param int[] $enabledActionIds Enabled rewards that may be chosen as a trigger.
|
||||
* @param callable(int):?array{mime:string,size?:int} $attachment Lookup of an attachment by id (null = missing).
|
||||
* @return array{data:?array,error:?string,warnings:string[]}
|
||||
*/
|
||||
public static function validate( array $post, int $minMinor, string $currency, array $validGoalIds, array $enabledActionIds, callable $attachment, int $defaultSort = 0 ): array {
|
||||
$fail = static fn( string $m ): array => array( 'data' => null, 'error' => $m, 'warnings' => array() );
|
||||
|
||||
$title = Input::text( $post['title'] ?? '', 200 );
|
||||
if ( '' === $title ) {
|
||||
return $fail( 'Please give this alert a name, for example "Big donation fireworks".' );
|
||||
}
|
||||
if ( mb_strlen( $title ) > 120 ) {
|
||||
return $fail( 'The name can be at most 120 characters.' );
|
||||
}
|
||||
$goal = Input::int( $post['goal_id'] ?? '0', 0, PHP_INT_MAX >> 1 );
|
||||
if ( null === $goal || ( 0 !== $goal && ! in_array( $goal, array_map( 'intval', $validGoalIds ), true ) ) ) {
|
||||
return $fail( 'Please choose all goals or one of your goals.' );
|
||||
}
|
||||
$trigger = is_scalar( $post['trigger_type'] ?? null ) ? (string) $post['trigger_type'] : '';
|
||||
$min = 0;
|
||||
$action = 0;
|
||||
if ( 'amount' === $trigger ) {
|
||||
$min = Input::amountToMinor( $post['amount'] ?? '', $currency );
|
||||
if ( null === $min || $min <= 0 ) {
|
||||
return $fail( 'Please enter the smallest donation that should trigger this alert, for example 10.00.' );
|
||||
}
|
||||
if ( $min < $minMinor ) {
|
||||
return $fail( 'The amount must be at least the minimum donation (' . \StreamGoals\Admin\Format::money( $minMinor, $currency ) . ').' );
|
||||
}
|
||||
} elseif ( 'reward' === $trigger ) {
|
||||
$action = Input::int( $post['action_id'] ?? '', 1, PHP_INT_MAX >> 1 );
|
||||
if ( null === $action || ! in_array( $action, array_map( 'intval', $enabledActionIds ), true ) ) {
|
||||
return $fail( 'Please choose one of your turned-on rewards.' );
|
||||
}
|
||||
} else {
|
||||
return $fail( 'Please choose when this alert plays.' );
|
||||
}
|
||||
|
||||
$warnings = array();
|
||||
$visualId = 0;
|
||||
$visual = '';
|
||||
$sound = 0;
|
||||
$vRaw = Input::int( $post['visual_id'] ?? '0', 0, PHP_INT_MAX >> 1 );
|
||||
$sRaw = Input::int( $post['sound_id'] ?? '0', 0, PHP_INT_MAX >> 1 );
|
||||
if ( null === $vRaw || null === $sRaw ) {
|
||||
return $fail( 'The chosen media file is not valid. Please pick it again.' );
|
||||
}
|
||||
if ( $vRaw > 0 ) {
|
||||
$a = $attachment( $vRaw );
|
||||
if ( ! is_array( $a ) ) {
|
||||
return $fail( 'The picture or video you chose no longer exists in your Media Library. Please pick it again.' );
|
||||
}
|
||||
$type = Media::visualType( $a['mime'] ?? null );
|
||||
if ( null === $type ) {
|
||||
return $fail( 'The picture or video must be PNG, JPEG, GIF, WebP, MP4 or WebM. Other file types are not allowed.' );
|
||||
}
|
||||
$visualId = $vRaw;
|
||||
$visual = $type;
|
||||
self::sizeWarning( $a, 'picture or video', 'video' === $type, $warnings );
|
||||
}
|
||||
if ( $sRaw > 0 ) {
|
||||
$a = $attachment( $sRaw );
|
||||
if ( ! is_array( $a ) ) {
|
||||
return $fail( 'The sound you chose no longer exists in your Media Library. Please pick it again.' );
|
||||
}
|
||||
if ( ! Media::isSound( $a['mime'] ?? null ) ) {
|
||||
return $fail( 'The sound must be an MP3, OGG or WAV file.' );
|
||||
}
|
||||
$sound = $sRaw;
|
||||
self::sizeWarning( $a, 'sound', false, $warnings );
|
||||
}
|
||||
|
||||
$vol = Input::int( $post['volume'] ?? '80', 0, 100 );
|
||||
if ( null === $vol ) {
|
||||
return $fail( 'Volume must be a whole number from 0 to 100.' );
|
||||
}
|
||||
$dur = Media::secondsToMs( $post['duration'] ?? '6' );
|
||||
if ( null === $dur || (int) round( (float) $post['duration'] * 1000 ) !== $dur ) {
|
||||
return $fail( 'How long the picture stays must be between 1 and 60 seconds.' );
|
||||
}
|
||||
$message = Input::text( $post['message'] ?? '', 400 );
|
||||
if ( mb_strlen( $message ) > 255 ) {
|
||||
return $fail( 'The message can be at most 255 characters.' );
|
||||
}
|
||||
$sortRaw = $post['sort'] ?? '';
|
||||
$sort = ( is_scalar( $sortRaw ) && '' === trim( (string) $sortRaw ) ) ? $defaultSort : Input::int( $sortRaw, 0, 99999 );
|
||||
if ( null === $sort ) {
|
||||
return $fail( 'The sort order must be a whole number from 0 to 99999.' );
|
||||
}
|
||||
return array(
|
||||
'data' => array(
|
||||
'goal_id' => $goal,
|
||||
'trigger_type' => $trigger,
|
||||
'min_minor' => $min,
|
||||
'action_id' => $action,
|
||||
'title' => $title,
|
||||
'visual_id' => $visualId,
|
||||
'visual_type' => $visual,
|
||||
'sound_id' => $sound,
|
||||
'volume' => $vol,
|
||||
'duration_ms' => $dur,
|
||||
'message' => $message,
|
||||
'sort' => $sort,
|
||||
),
|
||||
'error' => null,
|
||||
'warnings' => $warnings,
|
||||
);
|
||||
}
|
||||
|
||||
/** @param string[] $warnings */
|
||||
private static function sizeWarning( array $a, string $what, bool $video, array &$warnings ): void {
|
||||
if ( (int) ( $a['size'] ?? 0 ) > Media::WARN_BYTES ) {
|
||||
$warnings[] = 'The ' . $what . ' is over 25 MB.' . ( $video ? ' Big videos can make OBS stutter or load slowly; a short, compressed clip works much better.' : ' Large files take longer to load, so the alert may start late.' );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** $wpdb access to sg_alert_defs. */
|
||||
final class DefRepository {
|
||||
|
||||
private object $db;
|
||||
|
||||
public function __construct( ?object $db = null ) {
|
||||
$this->db = $db ?? $GLOBALS['wpdb'];
|
||||
}
|
||||
|
||||
private function t(): string {
|
||||
return $this->db->prefix . 'sg_alert_defs';
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private static function cast( array $r ): array {
|
||||
return array(
|
||||
'id' => (int) ( $r['id'] ?? 0 ),
|
||||
'goal_id' => (int) ( $r['goal_id'] ?? 0 ),
|
||||
'trigger_type' => 'reward' === ( $r['trigger_type'] ?? '' ) ? 'reward' : 'amount',
|
||||
'min_minor' => (int) ( $r['min_minor'] ?? 0 ),
|
||||
'action_id' => (int) ( $r['action_id'] ?? 0 ),
|
||||
'title' => (string) ( $r['title'] ?? '' ),
|
||||
'visual_id' => (int) ( $r['visual_id'] ?? 0 ),
|
||||
'visual_type' => (string) ( $r['visual_type'] ?? '' ),
|
||||
'sound_id' => (int) ( $r['sound_id'] ?? 0 ),
|
||||
'volume' => (int) ( $r['volume'] ?? 80 ),
|
||||
'duration_ms' => (int) ( $r['duration_ms'] ?? 6000 ),
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'enabled' => (int) ( $r['enabled'] ?? 0 ),
|
||||
'sort' => (int) ( $r['sort'] ?? 0 ),
|
||||
'created_at' => (string) ( $r['created_at'] ?? '' ),
|
||||
);
|
||||
}
|
||||
|
||||
public function all(): array {
|
||||
return array_map( array( self::class, 'cast' ), (array) $this->db->get_results( 'SELECT * FROM ' . $this->t() . ' ORDER BY sort ASC, id ASC', ARRAY_A ) );
|
||||
}
|
||||
|
||||
/** All enabled definitions (one query); the Resolver filters by goal. */
|
||||
public function enabled(): array {
|
||||
return array_map( array( self::class, 'cast' ), (array) $this->db->get_results( 'SELECT * FROM ' . $this->t() . ' WHERE enabled = 1 ORDER BY sort ASC, id ASC', ARRAY_A ) );
|
||||
}
|
||||
|
||||
public function find( int $id ): ?array {
|
||||
$row = $this->db->get_row( $this->db->prepare( 'SELECT * FROM ' . $this->t() . ' WHERE id = %d', $id ), ARRAY_A );
|
||||
return $row ? self::cast( $row ) : null;
|
||||
}
|
||||
|
||||
public function nextSort(): int {
|
||||
return (int) $this->db->get_var( 'SELECT COALESCE(MAX(sort),0)+10 FROM ' . $this->t() );
|
||||
}
|
||||
|
||||
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',
|
||||
);
|
||||
|
||||
public function create( array $d ): int {
|
||||
$row = array();
|
||||
foreach ( self::COLS as $k => $f ) {
|
||||
$row[ $k ] = $d[ $k ];
|
||||
}
|
||||
$row['enabled'] = 1;
|
||||
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
|
||||
$ok = $this->db->insert( $this->t(), $row, array_merge( array_values( self::COLS ), array( '%d', '%s' ) ) );
|
||||
return $ok ? (int) $this->db->insert_id : 0;
|
||||
}
|
||||
|
||||
public function update( int $id, array $d ): void {
|
||||
$row = array();
|
||||
foreach ( self::COLS as $k => $f ) {
|
||||
$row[ $k ] = $d[ $k ];
|
||||
}
|
||||
$this->db->update( $this->t(), $row, array( 'id' => $id ), array_values( self::COLS ), array( '%d' ) );
|
||||
}
|
||||
|
||||
public function setEnabled( int $id, bool $on ): void {
|
||||
$this->db->update( $this->t(), array( 'enabled' => $on ? 1 : 0 ), array( 'id' => $id ), array( '%d' ), array( '%d' ) );
|
||||
}
|
||||
|
||||
public function delete( int $id ): void {
|
||||
$this->db->delete( $this->t(), array( 'id' => $id ), array( '%d' ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** Pure helpers: MIME whitelist, type classification and duration clamping for alert media. */
|
||||
final class Media {
|
||||
|
||||
/** Exact MIME => kind. Everything else (svg, html, ...) is rejected. */
|
||||
public const MIMES = array(
|
||||
'image/png' => 'image',
|
||||
'image/jpeg' => 'image',
|
||||
'image/gif' => 'image',
|
||||
'image/webp' => 'image',
|
||||
'video/mp4' => 'video',
|
||||
'video/webm' => 'video',
|
||||
'audio/mpeg' => 'audio',
|
||||
'audio/ogg' => 'audio',
|
||||
'audio/wav' => 'audio',
|
||||
);
|
||||
|
||||
public const WARN_BYTES = 26214400; // 25 MB
|
||||
public const MIN_DURATION_MS = 1000;
|
||||
public const MAX_DURATION_MS = 60000;
|
||||
public const DEFAULT_MS = 6000;
|
||||
public const VIDEO_CAP_MS = 30000;
|
||||
|
||||
/** 'image' | 'video' | 'audio' for an allowed MIME, else null. Strict: no parameters, no case games. */
|
||||
public static function kind( mixed $mime ): ?string {
|
||||
if ( ! is_string( $mime ) ) {
|
||||
return null;
|
||||
}
|
||||
return self::MIMES[ strtolower( $mime ) ] ?? null;
|
||||
}
|
||||
|
||||
public static function isAllowed( mixed $mime ): bool {
|
||||
return null !== self::kind( $mime );
|
||||
}
|
||||
|
||||
/** 'image' | 'video' for a visual attachment MIME, else null (audio is not a visual). */
|
||||
public static function visualType( mixed $mime ): ?string {
|
||||
$k = self::kind( $mime );
|
||||
return 'image' === $k || 'video' === $k ? $k : null;
|
||||
}
|
||||
|
||||
public static function isSound( mixed $mime ): bool {
|
||||
return 'audio' === self::kind( $mime );
|
||||
}
|
||||
|
||||
public static function clampDurationMs( mixed $ms, int $default = self::DEFAULT_MS ): int {
|
||||
if ( ! is_numeric( $ms ) ) {
|
||||
return $default;
|
||||
}
|
||||
return max( self::MIN_DURATION_MS, min( self::MAX_DURATION_MS, (int) $ms ) );
|
||||
}
|
||||
|
||||
/** Whole seconds (1-60) to clamped milliseconds; null when the input is not a number. */
|
||||
public static function secondsToMs( mixed $s ): ?int {
|
||||
if ( ! is_scalar( $s ) || ! preg_match( '/^\s*\d{1,4}(\.\d+)?\s*$/', (string) $s ) ) {
|
||||
return null;
|
||||
}
|
||||
return self::clampDurationMs( (int) round( (float) $s * 1000 ) );
|
||||
}
|
||||
|
||||
public static function clampVolume( mixed $v, int $default = 80 ): int {
|
||||
return is_numeric( $v ) ? max( 0, min( 100, (int) $v ) ) : $default;
|
||||
}
|
||||
|
||||
/** 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 ) ) {
|
||||
return null;
|
||||
}
|
||||
return preg_match( '#^https?://[^/]#i', $url ) ? $url : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** Picks the single alert definition that applies to one donation. Pure. */
|
||||
final class Resolver {
|
||||
|
||||
/**
|
||||
* @param int[] $triggeredActionIds Rewards triggered by this donation.
|
||||
* @param array<int,array<string,mixed>> $defs Raw sg_alert_defs rows (any state; filtered here).
|
||||
* @param array<int,int> $actionAmounts action id => reward amount (minor); ties fall back to sort, id.
|
||||
* @return array<string,mixed>|null the winning row (with ints normalised) or null
|
||||
*/
|
||||
public static function pick( int $goalId, int $baseMinor, array $triggeredActionIds, array $defs, array $actionAmounts = array() ): ?array {
|
||||
$triggered = array_flip( array_map( 'intval', $triggeredActionIds ) );
|
||||
$reward = array();
|
||||
$amount = array();
|
||||
foreach ( $defs as $d ) {
|
||||
if ( ! is_array( $d ) || empty( $d['enabled'] ) ) {
|
||||
continue;
|
||||
}
|
||||
$dg = (int) ( $d['goal_id'] ?? 0 );
|
||||
if ( 0 !== $dg && $dg !== $goalId ) {
|
||||
continue;
|
||||
}
|
||||
$d['id'] = (int) ( $d['id'] ?? 0 );
|
||||
$d['sort'] = (int) ( $d['sort'] ?? 0 );
|
||||
$d['min_minor'] = (int) ( $d['min_minor'] ?? 0 );
|
||||
$d['action_id'] = (int) ( $d['action_id'] ?? 0 );
|
||||
$d['goal_id'] = $dg;
|
||||
if ( 'reward' === ( $d['trigger_type'] ?? '' ) ) {
|
||||
if ( $d['action_id'] > 0 && isset( $triggered[ $d['action_id'] ] ) ) {
|
||||
$reward[] = $d;
|
||||
}
|
||||
} elseif ( 'amount' === ( $d['trigger_type'] ?? '' ) && $baseMinor >= $d['min_minor'] ) {
|
||||
$amount[] = $d;
|
||||
}
|
||||
}
|
||||
if ( $reward ) {
|
||||
usort( $reward, static function ( array $a, array $b ) use ( $actionAmounts ): int {
|
||||
return ( (int) ( $actionAmounts[ $b['action_id'] ] ?? 0 ) <=> (int) ( $actionAmounts[ $a['action_id'] ] ?? 0 ) )
|
||||
?: ( $a['sort'] <=> $b['sort'] )
|
||||
?: ( $a['id'] <=> $b['id'] );
|
||||
} );
|
||||
return $reward[0];
|
||||
}
|
||||
if ( $amount ) {
|
||||
usort( $amount, static fn( array $a, array $b ): int => ( $b['min_minor'] <=> $a['min_minor'] ) ?: ( $a['sort'] <=> $b['sort'] ) ?: ( $a['id'] <=> $b['id'] ) );
|
||||
return $amount[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** Renders the custom alert message. Output is plain text: no tags, no control characters, length-capped. */
|
||||
final class Template {
|
||||
|
||||
public const MAX = 200;
|
||||
|
||||
public static function clean( string $s ): string {
|
||||
$s = strip_tags( $s );
|
||||
$s = (string) preg_replace( '/[\x00-\x1F\x7F\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}\x{FEFF}]+/u', ' ', $s );
|
||||
$s = str_replace( array( '<', '>' ), '', $s );
|
||||
return trim( (string) preg_replace( '/\s+/u', ' ', $s ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokens: {name} {amount} {reward} (case-insensitive). Unknown tokens are dropped. Substituted values are never
|
||||
* re-scanned for tokens. Empty template (or empty result) returns '' meaning "use the default text".
|
||||
*/
|
||||
public static function render( string $template, string $name, string $amount, string $reward, int $max = self::MAX ): string {
|
||||
$tpl = self::clean( $template );
|
||||
if ( '' === $tpl ) {
|
||||
return '';
|
||||
}
|
||||
$name = self::clean( $name );
|
||||
$vals = array(
|
||||
'name' => '' === $name ? 'Anonymous' : mb_substr( $name, 0, 60 ),
|
||||
'amount' => mb_substr( self::clean( $amount ), 0, 30 ),
|
||||
'reward' => mb_substr( self::clean( $reward ), 0, 80 ),
|
||||
);
|
||||
$out = (string) preg_replace_callback(
|
||||
'/\{([A-Za-z_]{1,20})\}/',
|
||||
static fn( array $m ): string => $vals[ strtolower( $m[1] ) ] ?? '',
|
||||
$tpl
|
||||
);
|
||||
$out = trim( (string) preg_replace( '/\s+/u', ' ', $out ) );
|
||||
return mb_substr( $out, 0, max( 1, $max ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/** Pure IPv4/IPv6 CIDR membership test (no WordPress, no network). Malformed input never matches. */
|
||||
final class CidrMatcher {
|
||||
|
||||
/** @param string[] $cidrs e.g. ['173.245.48.0/20', '2606:4700::/32'] */
|
||||
public static function contains( string $ip, array $cidrs ): bool {
|
||||
$ipBin = @inet_pton( trim( $ip ) );
|
||||
if ( false === $ipBin ) {
|
||||
return false;
|
||||
}
|
||||
foreach ( $cidrs as $cidr ) {
|
||||
if ( self::inRange( $ipBin, (string) $cidr ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function inRange( string $ipBin, string $cidr ): bool {
|
||||
$parts = explode( '/', trim( $cidr ), 2 );
|
||||
if ( 2 !== count( $parts ) || ! ctype_digit( $parts[1] ) ) {
|
||||
return false;
|
||||
}
|
||||
$netBin = @inet_pton( $parts[0] );
|
||||
if ( false === $netBin || strlen( $netBin ) !== strlen( $ipBin ) ) { // different address families never match
|
||||
return false;
|
||||
}
|
||||
$bits = (int) $parts[1];
|
||||
if ( $bits < 0 || $bits > strlen( $netBin ) * 8 ) {
|
||||
return false;
|
||||
}
|
||||
$fullBytes = intdiv( $bits, 8 );
|
||||
if ( $fullBytes > 0 && substr( $ipBin, 0, $fullBytes ) !== substr( $netBin, 0, $fullBytes ) ) {
|
||||
return false;
|
||||
}
|
||||
$rest = $bits % 8;
|
||||
if ( 0 === $rest ) {
|
||||
return true;
|
||||
}
|
||||
$mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF;
|
||||
return ( ord( $ipBin[ $fullBytes ] ) & $mask ) === ( ord( $netBin[ $fullBytes ] ) & $mask );
|
||||
}
|
||||
}
|
||||
@@ -12,12 +12,14 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class ClientIp {
|
||||
|
||||
public const MODE_AUTO = 'auto'; // detect Cloudflare automatically (recommended)
|
||||
public const MODE_DIRECT = ''; // no proxy: use REMOTE_ADDR
|
||||
public const MODE_CLOUDFLARE = 'cloudflare'; // CF-Connecting-IP
|
||||
public const MODE_REAL_IP = 'real_ip'; // X-Real-IP (nginx and many hosts)
|
||||
public const MODE_FORWARDED = 'forwarded'; // last address in X-Forwarded-For (exactly one proxy in front)
|
||||
|
||||
public const MODES = array(
|
||||
self::MODE_AUTO => 'Automatic (recommended): detects Cloudflare',
|
||||
self::MODE_DIRECT => 'Not behind a proxy or CDN (most sites)',
|
||||
self::MODE_CLOUDFLARE => 'Cloudflare (CF-Connecting-IP)',
|
||||
self::MODE_REAL_IP => 'X-Real-IP header',
|
||||
@@ -25,10 +27,16 @@ final class ClientIp {
|
||||
);
|
||||
|
||||
/** @param array<string,mixed> $server $_SERVER-style values (already unslashed). */
|
||||
public static function resolve( array $server, string $mode = self::MODE_DIRECT ): string {
|
||||
public static function resolve( array $server, string $mode = self::MODE_DIRECT, ?array $extraCloudflareRanges = null ): string {
|
||||
$remote = self::valid( $server['REMOTE_ADDR'] ?? null );
|
||||
$fromHeader = null;
|
||||
switch ( $mode ) {
|
||||
case self::MODE_AUTO:
|
||||
// Trust CF-Connecting-IP only when the connection itself comes from a Cloudflare address.
|
||||
if ( null !== $remote && CloudflareRanges::isCloudflare( $remote, $extraCloudflareRanges ) ) {
|
||||
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
|
||||
}
|
||||
break;
|
||||
case self::MODE_CLOUDFLARE:
|
||||
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
|
||||
break;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/**
|
||||
* Cloudflare's published proxy address ranges (https://www.cloudflare.com/ips-v4 and /ips-v6), fetched 2026-11-15.
|
||||
* They change very rarely. Sites can extend them with the `streamgoals_cloudflare_ranges` filter.
|
||||
* Used ONLY to decide whether a connection really comes from Cloudflare, so a forged CF-Connecting-IP header
|
||||
* from anywhere else is ignored.
|
||||
*/
|
||||
final class CloudflareRanges {
|
||||
|
||||
public const RANGES = array(
|
||||
'173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18',
|
||||
'190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
|
||||
'104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22',
|
||||
'2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32',
|
||||
);
|
||||
|
||||
/** @param string[]|null $extra additional ranges (from the filter) */
|
||||
public static function isCloudflare( string $ip, ?array $extra = null ): bool {
|
||||
return CidrMatcher::contains( $ip, array_merge( self::RANGES, $extra ?? array() ) );
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ namespace StreamGoals\Core;
|
||||
/** $wpdb-backed CRUD for sg_goals. Requires live WordPress. */
|
||||
final class GoalRepository {
|
||||
|
||||
private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d' );
|
||||
private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d', 'close_at_target' => '%d' );
|
||||
|
||||
private \wpdb $db;
|
||||
|
||||
@@ -21,7 +21,7 @@ final class GoalRepository {
|
||||
/** @return int new goal id */
|
||||
public function create( array $data ): int {
|
||||
$row = array_intersect_key( $data, self::FIELDS );
|
||||
$row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0 );
|
||||
$row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0, 'close_at_target' => 0 );
|
||||
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
|
||||
$this->db->insert( $this->table(), $row );
|
||||
return (int) $this->db->insert_id;
|
||||
@@ -62,9 +62,26 @@ final class GoalRepository {
|
||||
if ( ! $goal ) {
|
||||
return 0;
|
||||
}
|
||||
$col = ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor'; // whitelisted, not user input
|
||||
$col = GoalTargetPolicy::amountColumn( $goal ); // whitelisted, not user input
|
||||
$d = $this->db->prefix . 'sg_donations';
|
||||
$sum = $this->db->get_var( $this->db->prepare( "SELECT COALESCE(SUM({$col}), 0) FROM {$d} WHERE goal_id = %d AND status = 'completed'", $goalId ) );
|
||||
return (int) $sum;
|
||||
}
|
||||
|
||||
/**
|
||||
* "End at target": if the goal is active, flagged close_at_target and its raised total has reached the
|
||||
* target, set it to 'complete'. The UPDATE is conditional on status = 'active', so concurrent callers
|
||||
* change it once. Idempotent and cheap (one SELECT for non-flagged goals). Returns true if THIS call closed it.
|
||||
*/
|
||||
public function closeIfTargetReached( int $goalId ): bool {
|
||||
$goal = $this->find( $goalId );
|
||||
if ( ! $goal || empty( $goal['close_at_target'] ) || 'active' !== $goal['status'] ) {
|
||||
return false;
|
||||
}
|
||||
if ( ! GoalTargetPolicy::shouldClose( $goal, $this->raised_minor( $goalId ) ) ) {
|
||||
return false;
|
||||
}
|
||||
$n = $this->db->query( $this->db->prepare( "UPDATE {$this->table()} SET status = 'complete' WHERE id = %d AND status = 'active' AND close_at_target = 1", $goalId ) );
|
||||
return 1 === $n;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/** Pure rules for "end at target" goals (no WordPress / database access). */
|
||||
final class GoalTargetPolicy {
|
||||
|
||||
/** Donation column summed towards the goal: total (fees included) or base. Whitelisted values only. */
|
||||
public static function amountColumn( array $goal ): string {
|
||||
return ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor';
|
||||
}
|
||||
|
||||
/** True when the goal should now be auto-closed: flag on, currently active, target set and reached or exceeded. */
|
||||
public static function shouldClose( array $goal, int $raisedMinor ): bool {
|
||||
return ! empty( $goal['close_at_target'] )
|
||||
&& 'active' === ( $goal['status'] ?? '' )
|
||||
&& (int) ( $goal['target_minor'] ?? 0 ) > 0
|
||||
&& $raisedMinor >= (int) $goal['target_minor'];
|
||||
}
|
||||
|
||||
/** True for a goal that is closed to donors because it reached its target (flag on + complete). */
|
||||
public static function isClosedAtTarget( array $goal ): bool {
|
||||
return ! empty( $goal['close_at_target'] ) && 'complete' === ( $goal['status'] ?? '' );
|
||||
}
|
||||
|
||||
/** Checkbox value from a raw form field: 1 when ticked, else 0. */
|
||||
public static function flagFromPost( mixed $raw ): int {
|
||||
if ( is_array( $raw ) || null === $raw ) {
|
||||
return 0;
|
||||
}
|
||||
return in_array( strtolower( trim( (string) $raw ) ), array( '1', 'on', 'true', 'yes' ), true ) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,7 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class Installer {
|
||||
|
||||
public const DB_VERSION = '2';
|
||||
public const DB_VERSION = '3';
|
||||
|
||||
public static function activate(): void {
|
||||
self::install_schema();
|
||||
@@ -39,6 +39,7 @@ final class Installer {
|
||||
starts_at DATETIME NULL,
|
||||
ends_at DATETIME NULL,
|
||||
counts_fees TINYINT(1) NOT NULL DEFAULT 0,
|
||||
close_at_target TINYINT(1) NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id)
|
||||
) $c;" );
|
||||
@@ -122,6 +123,26 @@ final class Installer {
|
||||
KEY status_id (status,id)
|
||||
) $c;" );
|
||||
|
||||
dbDelta( "CREATE TABLE {$p}alert_defs (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
goal_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
trigger_type VARCHAR(8) NOT NULL DEFAULT 'amount',
|
||||
min_minor BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
action_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
title VARCHAR(120) NOT NULL DEFAULT '',
|
||||
visual_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
visual_type VARCHAR(6) NOT NULL DEFAULT '',
|
||||
sound_id BIGINT UNSIGNED NOT NULL DEFAULT 0,
|
||||
volume TINYINT UNSIGNED NOT NULL DEFAULT 80,
|
||||
duration_ms INT UNSIGNED NOT NULL DEFAULT 6000,
|
||||
message VARCHAR(255) NOT NULL DEFAULT '',
|
||||
enabled TINYINT(1) NOT NULL DEFAULT 1,
|
||||
sort INT NOT NULL DEFAULT 0,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY goal_enabled (goal_id,enabled)
|
||||
) $c;" );
|
||||
|
||||
update_option( 'sg_db_version', self::DB_VERSION );
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ final class Settings {
|
||||
'message_max_length' => 200,
|
||||
'min_donation_minor' => 100,
|
||||
'overlay_token' => '',
|
||||
'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp)
|
||||
'visitor_ip_header' => 'auto', // auto | '' (direct) | cloudflare | real_ip | forwarded (see Core\ClientIp)
|
||||
'funding_paylater' => false, // show PayPal "Pay Later" button
|
||||
'update_token' => '', // optional Gitea read token (only while the update repo is private)
|
||||
'funding_card' => true, // show the Debit/Credit Card button
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** Optional capability: configurable alert media (definitions, triggered rewards, attachment lookup). */
|
||||
interface AlertMediaSource {
|
||||
|
||||
/** Enabled alert definitions, raw rows. Called at most once per request. */
|
||||
public function alertDefs(): array;
|
||||
|
||||
/**
|
||||
* Rewards triggered per donation, one lookup for the whole page.
|
||||
*
|
||||
* @param int[] $donationIds
|
||||
* @return array<int,array<int,array{action_id:int,amount_minor:int,title:string}>> donation id => rewards
|
||||
*/
|
||||
public function triggeredActionsFor( array $donationIds ): array;
|
||||
|
||||
/**
|
||||
* Server-side attachment lookup (the only place media URLs come from). Null when it is gone.
|
||||
*
|
||||
* @return array{url:string,mime:string}|null
|
||||
*/
|
||||
public function attachment( int $id ): ?array;
|
||||
}
|
||||
@@ -8,8 +8,24 @@ final class OverlayService {
|
||||
|
||||
public const WIDGETS = array( 'goal', 'timer', 'counter', 'alerts', 'actions' );
|
||||
|
||||
/** @var array<int,array<string,mixed>>|null */
|
||||
private ?array $defs = null;
|
||||
|
||||
public function __construct( private OverlayDataSource $source ) {}
|
||||
|
||||
/** Enabled alert definitions, loaded at most once per service instance (= per request). */
|
||||
private function defs(): array {
|
||||
if ( null === $this->defs ) {
|
||||
$this->defs = $this->source instanceof AlertMediaSource ? array_values( $this->source->alertDefs() ) : array();
|
||||
}
|
||||
return $this->defs;
|
||||
}
|
||||
|
||||
/** Extra ETag input so editing media definitions invalidates cached alert payloads even when no alert is pending. */
|
||||
public function etagSalt( string $widget ): string {
|
||||
return 'alerts' === $widget && $this->defs() ? md5( (string) json_encode( $this->defs() ) ) : '';
|
||||
}
|
||||
|
||||
public function payload( string $widget, int $now, ?int $since = null, bool $recent = false ): ?array {
|
||||
$goal = $this->source->activeGoal();
|
||||
$gid = $goal ? (int) $goal['id'] : 0;
|
||||
@@ -43,7 +59,16 @@ final class OverlayService {
|
||||
$rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
$rows[ $i ]['actions'] = $actions[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
}
|
||||
return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent );
|
||||
$mediaFor = null;
|
||||
$defs = ( $recent || null !== $since ) ? $this->defs() : array();
|
||||
if ( $defs && $ids && $this->source instanceof AlertMediaSource ) {
|
||||
$src = $this->source;
|
||||
$triggered = $src->triggeredActionsFor( $ids );
|
||||
$mediaFor = static fn( array $r, string $name, string $amount ): ?array => \StreamGoals\Alerts\AlertMedia::build(
|
||||
$r, $name, $amount, $defs, $triggered[ (int) ( $r['id'] ?? 0 ) ] ?? array(), static fn( int $id ): ?array => $src->attachment( $id )
|
||||
);
|
||||
}
|
||||
return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent, $mediaFor );
|
||||
case 'actions':
|
||||
$rows = ( $gid && $this->source instanceof ActionsSource ) ? $this->source->menuActions( $gid ) : array();
|
||||
return Payloads::actionsMenu( $goal, $rows );
|
||||
|
||||
@@ -78,7 +78,7 @@ final class Payloads {
|
||||
* @param bool $recent Recent mode: ignore $since and return the newest $limit approved alerts (ascending id),
|
||||
* so a message approved after newer donations still shows up. The client dedupes by id.
|
||||
*/
|
||||
public static function alerts( array $rows, ?int $since, int $limit = 10, bool $recent = false ): array {
|
||||
public static function alerts( array $rows, ?int $since, int $limit = 10, bool $recent = false, ?callable $mediaFor = null ): array {
|
||||
$safe = array();
|
||||
foreach ( $rows as $r ) {
|
||||
if ( 'completed' !== ( $r['status'] ?? '' ) || 'approved' !== ( $r['moderation'] ?? '' ) ) {
|
||||
@@ -89,7 +89,7 @@ final class Payloads {
|
||||
usort( $safe, static fn( $a, $b ) => (int) $a['id'] <=> (int) $b['id'] );
|
||||
if ( $recent ) {
|
||||
$safe = array_slice( $safe, -max( 1, $limit ) );
|
||||
$alerts = array_map( array( self::class, 'alert' ), $safe );
|
||||
$alerts = array_map( static fn( array $r ): array => self::alert( $r, $mediaFor ), $safe );
|
||||
return array( 'alerts' => $alerts, 'last_id' => $alerts ? (int) end( $alerts )['id'] : 0 );
|
||||
}
|
||||
$lastId = $since ?? 0;
|
||||
@@ -104,7 +104,7 @@ final class Payloads {
|
||||
if ( (int) $r['id'] <= $since ) {
|
||||
continue;
|
||||
}
|
||||
$alerts[] = self::alert( $r );
|
||||
$alerts[] = self::alert( $r, $mediaFor );
|
||||
}
|
||||
$alerts = array_slice( $alerts, 0, max( 1, $limit ) );
|
||||
if ( $alerts ) {
|
||||
@@ -113,20 +113,26 @@ final class Payloads {
|
||||
return array( 'alerts' => $alerts, 'last_id' => $lastId );
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $r */
|
||||
private static function alert( array $r ): array {
|
||||
/**
|
||||
* @param array<string,mixed> $r
|
||||
* @param (callable(array,string,string):?array)|null $mediaFor Builds the `media` block from (row, public name, amount display).
|
||||
*/
|
||||
private static function alert( array $r, ?callable $mediaFor = null ): array {
|
||||
$cur = strtoupper( (string) ( $r['currency'] ?? 'USD' ) );
|
||||
$anon = ! empty( $r['is_anonymous'] );
|
||||
$name = trim( (string) ( $r['donor_name'] ?? '' ) );
|
||||
$pub = ( $anon || '' === $name ) ? self::ANON_NAME : $name;
|
||||
$disp = self::money( (int) $r['base_minor'], $cur );
|
||||
return array(
|
||||
'id' => (int) $r['id'],
|
||||
'name' => ( $anon || '' === $name ) ? self::ANON_NAME : $name,
|
||||
'name' => $pub,
|
||||
'amount_minor' => (int) $r['base_minor'],
|
||||
'amount_display' => self::money( (int) $r['base_minor'], $cur ),
|
||||
'amount_display' => $disp,
|
||||
'currency' => $cur,
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
|
||||
'actions' => self::actionEvents( $r['actions'] ?? array() ),
|
||||
'media' => $mediaFor ? $mediaFor( $r, $pub, $disp ) : null,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -223,10 +229,10 @@ final class Payloads {
|
||||
return array( 'active' => (bool) $list, 'currency' => $cur, 'actions' => $list );
|
||||
}
|
||||
|
||||
/** Strong ETag over the payload, ignoring the volatile server_now so unchanged data yields 304s. */
|
||||
public static function etag( array $payload ): string {
|
||||
/** Strong ETag over the payload (plus an optional salt, e.g. a hash of media definitions), ignoring the volatile server_now so unchanged data yields 304s. */
|
||||
public static function etag( array $payload, string $salt = '' ): string {
|
||||
unset( $payload['server_now'] );
|
||||
return '"' . md5( (string) json_encode( $payload, JSON_UNESCAPED_UNICODE ) ) . '"';
|
||||
return '"' . md5( $salt . (string) json_encode( $payload, JSON_UNESCAPED_UNICODE ) ) . '"';
|
||||
}
|
||||
|
||||
private static function toEpoch( ?string $v ): ?int {
|
||||
|
||||
@@ -4,7 +4,10 @@ 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 {
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource {
|
||||
|
||||
/** @var array<int,?array{url:string,mime:string}> */
|
||||
private array $attachments = array();
|
||||
|
||||
private function t( string $name ): string {
|
||||
global $wpdb;
|
||||
@@ -117,9 +120,47 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function alertDefs(): array {
|
||||
return ( new \StreamGoals\Alerts\DefRepository( $GLOBALS['wpdb'] ) )->enabled();
|
||||
}
|
||||
|
||||
public function triggeredActionsFor( array $donationIds ): array {
|
||||
global $wpdb;
|
||||
$ids = array_values( array_unique( array_filter( array_map( 'intval', $donationIds ), static fn( $i ) => $i > 0 ) ) );
|
||||
if ( ! $ids ) {
|
||||
return array();
|
||||
}
|
||||
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT e.donation_id, e.action_id, e.title, COALESCE(a.amount_minor,0) AS amount_minor FROM {$this->t('action_events')} e
|
||||
LEFT JOIN {$this->t('actions')} a ON a.id = e.action_id WHERE e.donation_id IN ($in) ORDER BY e.id ASC",
|
||||
$ids
|
||||
), ARRAY_A );
|
||||
$out = array();
|
||||
foreach ( (array) $rows as $row ) {
|
||||
$out[ (int) $row['donation_id'] ][] = array( 'action_id' => (int) $row['action_id'], 'amount_minor' => (int) $row['amount_minor'], 'title' => (string) $row['title'] );
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function attachment( int $id ): ?array {
|
||||
if ( array_key_exists( $id, $this->attachments ) ) {
|
||||
return $this->attachments[ $id ];
|
||||
}
|
||||
$out = null;
|
||||
if ( $id > 0 && 'attachment' === get_post_type( $id ) ) {
|
||||
$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 );
|
||||
}
|
||||
}
|
||||
return $this->attachments[ $id ] = $out;
|
||||
}
|
||||
|
||||
public function donations( ?int $sinceId, int $limit ): array {
|
||||
global $wpdb;
|
||||
$cols = 'id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
|
||||
$cols = 'id, goal_id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
|
||||
$where = "status = 'completed' AND moderation = 'approved'";
|
||||
if ( null === $sinceId ) {
|
||||
$rows = $wpdb->get_results( "SELECT $cols FROM {$this->t('donations')} WHERE $where ORDER BY id DESC LIMIT 1", ARRAY_A );
|
||||
@@ -136,7 +177,7 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
|
||||
public function recentDonations( int $limit ): array {
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT id, base_minor, currency, donor_name, is_anonymous, message, status, moderation FROM {$this->t('donations')}
|
||||
"SELECT id, goal_id, base_minor, currency, donor_name, is_anonymous, message, status, moderation FROM {$this->t('donations')}
|
||||
WHERE status = 'completed' AND moderation = 'approved' ORDER BY id DESC LIMIT %d",
|
||||
max( 1, $limit )
|
||||
), ARRAY_A );
|
||||
|
||||
@@ -93,6 +93,28 @@ final class DonationStore {
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: Recorder failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
}
|
||||
self::close_goal_if_target_reached( $id );
|
||||
}
|
||||
|
||||
/**
|
||||
* "End at target": runs after the donation is already completed and counted, so it can never refuse or
|
||||
* undo a capture. Failures are logged and swallowed. Idempotent (atomic UPDATE ... WHERE status='active').
|
||||
*/
|
||||
public static function close_goal_if_target_reached( int $donationId ): void {
|
||||
try {
|
||||
$row = self::find( $donationId );
|
||||
if ( $row && (int) $row->goal_id > 0 ) {
|
||||
( new \StreamGoals\Core\GoalRepository() )->closeIfTargetReached( (int) $row->goal_id );
|
||||
}
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: end-at-target check failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
}
|
||||
}
|
||||
|
||||
/** Goals closed because they reached their target (newest first), for the donor-facing "goal reached" message. @return array[] */
|
||||
public static function reached_goals(): array {
|
||||
global $wpdb;
|
||||
return (array) $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'complete' AND close_at_target = 1 ORDER BY id DESC LIMIT 20", ARRAY_A );
|
||||
}
|
||||
|
||||
private static function call_engine( string $method, int $id ): void {
|
||||
|
||||
@@ -84,6 +84,9 @@ final class OrderValidator {
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public static function quote( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array {
|
||||
if ( 'complete' === ( $goal['status'] ?? '' ) ) {
|
||||
throw new ValidationException( 'goal_inactive', 'This goal is closed and no longer accepting donations. Thank you for your support!', 409 );
|
||||
}
|
||||
if ( ! self::goalIsOpen( $goal, $nowTs ) ) {
|
||||
throw new ValidationException( 'goal_inactive', 'This goal is not accepting donations.', 409 );
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Rest;
|
||||
|
||||
use StreamGoals\Core\GoalTargetPolicy;
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\PayPal\CaptureFinalizer;
|
||||
@@ -170,6 +171,11 @@ final class DonateController {
|
||||
);
|
||||
}
|
||||
if ( ! $goals ) {
|
||||
$reached = $pinned ? DonationStore::goal( $pinned ) : null;
|
||||
$reached = $pinned ? ( $reached && GoalTargetPolicy::isClosedAtTarget( $reached ) ) : (bool) DonationStore::reached_goals();
|
||||
if ( $reached ) {
|
||||
return '<p class="sg-donate-unavailable sg-donate-reached">' . esc_html__( 'This goal has been reached - thank you for your support!', 'streamgoals-donate' ) . '</p>';
|
||||
}
|
||||
return '<p class="sg-donate-unavailable">' . esc_html__( 'There is no active goal to donate to right now.', 'streamgoals-donate' ) . '</p>';
|
||||
}
|
||||
|
||||
@@ -278,7 +284,7 @@ final class DonateController {
|
||||
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
|
||||
}
|
||||
}
|
||||
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', '' ) );
|
||||
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', 'auto' ), (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
|
||||
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -49,12 +49,13 @@ final class OverlayController {
|
||||
}
|
||||
$since = $req->has_param( 'since' ) && '' !== (string) $req->get_param( 'since' ) ? absint( $req->get_param( 'since' ) ) : null;
|
||||
$recent = $req->has_param( 'recent' ) && 1 === absint( $req->get_param( 'recent' ) );
|
||||
$payload = ( new OverlayService( new WpdbDataSource() ) )->payload( (string) $req['widget'], time(), $since, $recent );
|
||||
$service = new OverlayService( new WpdbDataSource() );
|
||||
$payload = $service->payload( (string) $req['widget'], time(), $since, $recent );
|
||||
if ( null === $payload ) {
|
||||
return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) );
|
||||
}
|
||||
|
||||
$etag = Payloads::etag( $payload );
|
||||
$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' );
|
||||
$inm = (string) $req->get_header( 'if_none_match' );
|
||||
if ( '' !== $inm && in_array( $etag, array_map( 'trim', explode( ',', str_replace( 'W/', '', $inm ) ) ), true ) ) {
|
||||
|
||||
@@ -67,7 +67,8 @@ final class ActionRepositoryTest extends TestCase {
|
||||
|
||||
public function test_installer_schema_defines_both_tables_and_unique_key(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
|
||||
$this->assertStringContainsString( "DB_VERSION = '2'", $src );
|
||||
$this->assertSame( 1, preg_match( "/DB_VERSION = '(\\d+)'/", $src, $m ), 'DB_VERSION constant not found' );
|
||||
$this->assertGreaterThanOrEqual( 2, (int) $m[1], 'the actions tables arrived in schema version 2; later versions must keep them' );
|
||||
$this->assertStringContainsString( 'CREATE TABLE {$p}actions (', $src );
|
||||
$this->assertStringContainsString( 'CREATE TABLE {$p}action_events (', $src );
|
||||
$this->assertStringContainsString( 'UNIQUE KEY donation_action (donation_id,action_id)', $src );
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Alerts\DefInput;
|
||||
|
||||
final class AlertDefInputTest extends TestCase {
|
||||
|
||||
private function att(): callable {
|
||||
$files = array(
|
||||
10 => array( 'mime' => 'image/gif', 'size' => 1000 ),
|
||||
11 => array( 'mime' => 'video/mp4', 'size' => 30 * 1024 * 1024 ),
|
||||
12 => array( 'mime' => 'audio/mpeg', 'size' => 5000 ),
|
||||
13 => array( 'mime' => 'image/svg+xml', 'size' => 10 ),
|
||||
14 => array( 'mime' => 'text/html', 'size' => 10 ),
|
||||
15 => array( 'mime' => 'image/png', 'size' => 10 ),
|
||||
);
|
||||
return static fn( int $id ): ?array => $files[ $id ] ?? null;
|
||||
}
|
||||
|
||||
private function post( array $o = array() ): array {
|
||||
return $o + array( 'title' => 'Big', 'goal_id' => '0', 'trigger_type' => 'amount', 'amount' => '10.00', 'visual_id' => '10', 'sound_id' => '12',
|
||||
'volume' => '70', 'duration' => '8', 'message' => '{name} sent {amount}', 'sort' => '' );
|
||||
}
|
||||
|
||||
private function run_( array $post, int $min = 100 ): array {
|
||||
return DefInput::validate( $post, $min, 'USD', array( 3 ), array( 5 ), $this->att(), 40 );
|
||||
}
|
||||
|
||||
public function test_valid_amount_def(): void {
|
||||
$r = $this->run_( $this->post() );
|
||||
$this->assertNull( $r['error'] );
|
||||
$d = $r['data'];
|
||||
$this->assertSame( array( 0, 'amount', 1000, 0, 10, 'image', 12, 70, 8000, 40 ), array( $d['goal_id'], $d['trigger_type'], $d['min_minor'], $d['action_id'], $d['visual_id'], $d['visual_type'], $d['sound_id'], $d['volume'], $d['duration_ms'], $d['sort'] ) );
|
||||
$this->assertSame( array(), $r['warnings'] );
|
||||
}
|
||||
|
||||
public function test_valid_reward_def_ignores_amount(): void {
|
||||
$r = $this->run_( $this->post( array( 'trigger_type' => 'reward', 'action_id' => '5', 'amount' => '' ) ) );
|
||||
$this->assertNull( $r['error'] );
|
||||
$this->assertSame( array( 'reward', 0, 5 ), array( $r['data']['trigger_type'], $r['data']['min_minor'], $r['data']['action_id'] ) );
|
||||
}
|
||||
|
||||
public function test_reward_must_be_enabled_one(): void {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'trigger_type' => 'reward', 'action_id' => '6' ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'trigger_type' => 'reward', 'action_id' => '0' ) ) )['error'] );
|
||||
}
|
||||
|
||||
public function test_amount_must_reach_effective_minimum(): void {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'amount' => '0.50' ) ), 100 )['error'] );
|
||||
$this->assertNull( $this->run_( $this->post( array( 'amount' => '1.00' ) ), 100 )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'amount' => 'abc' ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'amount' => '' ) ) )['error'] );
|
||||
}
|
||||
|
||||
public function test_rejects_bad_mime_and_missing_attachments(): void {
|
||||
foreach ( array( 13, 14, 12, 99 ) as $bad ) {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'visual_id' => (string) $bad ) ) )['error'], "visual $bad" );
|
||||
}
|
||||
foreach ( array( 13, 10, 11, 99 ) as $bad ) {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'sound_id' => (string) $bad ) ) )['error'], "sound $bad" );
|
||||
}
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'visual_id' => 'x' ) ) )['error'] );
|
||||
}
|
||||
|
||||
public function test_media_is_optional_and_type_is_detected_server_side(): void {
|
||||
$r = $this->run_( $this->post( array( 'visual_id' => '0', 'sound_id' => '0', 'visual_type' => 'video' ) ) );
|
||||
$this->assertSame( array( 0, '', 0 ), array( $r['data']['visual_id'], $r['data']['visual_type'], $r['data']['sound_id'] ) );
|
||||
$r = $this->run_( $this->post( array( 'visual_id' => '15', 'visual_type' => 'video' ) ) );
|
||||
$this->assertSame( 'image', $r['data']['visual_type'], 'client-supplied type is ignored' );
|
||||
}
|
||||
|
||||
public function test_big_files_warn_but_do_not_block(): void {
|
||||
$r = $this->run_( $this->post( array( 'visual_id' => '11' ) ) );
|
||||
$this->assertNull( $r['error'] );
|
||||
$this->assertSame( 'video', $r['data']['visual_type'] );
|
||||
$this->assertCount( 1, $r['warnings'] );
|
||||
$this->assertStringContainsString( 'OBS', $r['warnings'][0] );
|
||||
}
|
||||
|
||||
public function test_numeric_ranges(): void {
|
||||
foreach ( array( '-1', '101', 'x' ) as $v ) {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'volume' => $v ) ) )['error'], "volume $v" );
|
||||
}
|
||||
$this->assertSame( 0, $this->run_( $this->post( array( 'volume' => '0' ) ) )['data']['volume'] );
|
||||
foreach ( array( '0', '61', '0.5', 'x', '' , '-2' ) as $v ) {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'duration' => $v ) ) )['error'], "duration '$v'" );
|
||||
}
|
||||
$this->assertSame( 60000, $this->run_( $this->post( array( 'duration' => '60' ) ) )['data']['duration_ms'] );
|
||||
$this->assertSame( 1000, $this->run_( $this->post( array( 'duration' => '1' ) ) )['data']['duration_ms'] );
|
||||
}
|
||||
|
||||
public function test_title_goal_message_sort(): void {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'title' => ' ' ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'title' => str_repeat( 'a', 121 ) ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'goal_id' => '99' ) ) )['error'] );
|
||||
$this->assertSame( 3, $this->run_( $this->post( array( 'goal_id' => '3' ) ) )['data']['goal_id'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'trigger_type' => 'nope' ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'message' => str_repeat( 'm', 256 ) ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'sort' => '100000' ) ) )['error'] );
|
||||
$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'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Alerts\Media;
|
||||
use StreamGoals\Alerts\Template;
|
||||
|
||||
final class AlertHelpersTest extends TestCase {
|
||||
|
||||
public function test_mime_whitelist_and_kinds(): void {
|
||||
foreach ( array( 'image/png', 'image/jpeg', 'image/gif', 'image/webp' ) as $m ) {
|
||||
$this->assertSame( 'image', Media::kind( $m ) );
|
||||
$this->assertSame( 'image', Media::visualType( $m ) );
|
||||
}
|
||||
foreach ( array( 'video/mp4', 'video/webm' ) as $m ) {
|
||||
$this->assertSame( 'video', Media::visualType( $m ) );
|
||||
}
|
||||
foreach ( array( 'audio/mpeg', 'audio/ogg', 'audio/wav' ) as $m ) {
|
||||
$this->assertTrue( Media::isSound( $m ) );
|
||||
$this->assertNull( Media::visualType( $m ) );
|
||||
}
|
||||
$this->assertTrue( Media::isAllowed( 'IMAGE/PNG' ) );
|
||||
}
|
||||
|
||||
/** @dataProvider hostileMimes */
|
||||
public function test_hostile_mimes_rejected( mixed $mime ): void {
|
||||
$this->assertFalse( Media::isAllowed( $mime ) );
|
||||
$this->assertNull( Media::visualType( $mime ) );
|
||||
$this->assertFalse( Media::isSound( $mime ) );
|
||||
}
|
||||
|
||||
public static function hostileMimes(): array {
|
||||
return array(
|
||||
array( 'image/svg+xml' ), array( 'text/html' ), array( 'application/javascript' ), array( '' ), array( null ), array( 123 ),
|
||||
array( array( 'image/png' ) ), array( 'image/png; charset=x' ), array( "image/png\0.html" ), array( ' image/png' ), array( 'image/*' ),
|
||||
array( 'video/x-msvideo' ), array( 'audio/x-wav' ), array( 'image/png,text/html' ),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_duration_clamping(): void {
|
||||
$this->assertSame( 6000, Media::clampDurationMs( 'abc' ) );
|
||||
$this->assertSame( 1000, Media::clampDurationMs( 5 ) );
|
||||
$this->assertSame( 1000, Media::clampDurationMs( -9999 ) );
|
||||
$this->assertSame( 60000, Media::clampDurationMs( 9999999 ) );
|
||||
$this->assertSame( 12000, Media::clampDurationMs( '12000' ) );
|
||||
$this->assertSame( 8000, Media::secondsToMs( '8' ) );
|
||||
$this->assertSame( 1500, Media::secondsToMs( '1.5' ) );
|
||||
$this->assertNull( Media::secondsToMs( 'x' ) );
|
||||
$this->assertNull( Media::secondsToMs( '-3' ) );
|
||||
$this->assertNull( Media::secondsToMs( array() ) );
|
||||
$this->assertSame( 100, Media::clampVolume( 500 ) );
|
||||
$this->assertSame( 0, Media::clampVolume( -5 ) );
|
||||
$this->assertSame( 80, Media::clampVolume( 'loud' ) );
|
||||
}
|
||||
|
||||
public function test_safe_url(): void {
|
||||
$this->assertSame( 'https://x.test/a.png', Media::safeUrl( 'https://x.test/a.png' ) );
|
||||
foreach ( array( 'javascript:alert(1)', 'data:text/html,x', '//evil.test/x', '/relative.png', 'https://x.test/a b', "https://x.test/\"onerror=", '', null, 5 ) as $bad ) {
|
||||
$this->assertNull( Media::safeUrl( $bad ), var_export( $bad, true ) );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_template_tokens(): void {
|
||||
$this->assertSame( 'Al sent $5.00 for Bean!', Template::render( '{name} sent {amount} for {reward}!', 'Al', '$5.00', 'Bean' ) );
|
||||
$this->assertSame( 'Al sent', Template::render( '{Name} {nope} sent', 'Al', '$5', '' ), 'unknown tokens dropped, case-insensitive' );
|
||||
$this->assertSame( '', Template::render( '', 'Al', '$5', '' ) );
|
||||
$this->assertSame( '', Template::render( ' ', 'Al', '$5', '' ) );
|
||||
$this->assertSame( 'Anonymous rocks', Template::render( '{name} rocks', '', '$5', '' ) );
|
||||
}
|
||||
|
||||
public function test_template_is_html_free_and_not_reexpanded(): void {
|
||||
$out = Template::render( '<b>{name}</b><script>alert(1)</script> {amount}', '<img src=x onerror=alert(1)>Al', '$5', '' );
|
||||
$this->assertStringNotContainsString( '<', $out );
|
||||
$this->assertStringNotContainsString( '>', $out );
|
||||
$this->assertStringContainsString( 'Al', $out );
|
||||
$this->assertSame( '{amount} 5', Template::render( '{name} {amount}', '{amount}', '5', '' ) );
|
||||
$this->assertStringNotContainsString( '9', Template::render( '{name}', 'x{amount}', '9', '' ) );
|
||||
$this->assertStringNotContainsString( "\n", Template::render( "a\r\n\t{name}\x00\u{202E}", 'Al', '$5', '' ) );
|
||||
$this->assertStringNotContainsString( '<', Template::render( '<<b>script>x', 'Al', '$5', '' ) );
|
||||
}
|
||||
|
||||
public function test_template_length_capped(): void {
|
||||
$this->assertLessThanOrEqual( 200, mb_strlen( Template::render( str_repeat( 'x', 5000 ), 'Al', '$5', '' ) ) );
|
||||
$long = str_repeat( 'N', 500 );
|
||||
$this->assertLessThanOrEqual( 60, mb_strlen( Template::render( '{name}', $long, '$5', '' ) ) );
|
||||
$this->assertLessThanOrEqual( 80, mb_strlen( Template::render( '{reward}', 'Al', '$5', $long ) ) );
|
||||
$this->assertLessThanOrEqual( 10, mb_strlen( Template::render( str_repeat( 'x', 50 ), 'Al', '$5', '', 10 ) ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Alerts\Resolver;
|
||||
|
||||
final class AlertResolverTest extends TestCase {
|
||||
|
||||
private function def( int $id, array $o = array() ): array {
|
||||
return $o + array( 'id' => $id, 'goal_id' => 0, 'trigger_type' => 'amount', 'min_minor' => 100, 'action_id' => 0, 'enabled' => 1, 'sort' => 0 );
|
||||
}
|
||||
|
||||
public function test_highest_matching_amount_wins(): void {
|
||||
$defs = array( $this->def( 1, array( 'min_minor' => 100 ) ), $this->def( 2, array( 'min_minor' => 1000 ) ), $this->def( 3, array( 'min_minor' => 5000 ) ) );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 1000, array(), $defs )['id'] );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 4999, array(), $defs )['id'] );
|
||||
$this->assertSame( 3, Resolver::pick( 1, 99999, array(), $defs )['id'] );
|
||||
$this->assertSame( 1, Resolver::pick( 1, 100, array(), $defs )['id'] );
|
||||
}
|
||||
|
||||
public function test_none_when_below_every_minimum_or_no_defs(): void {
|
||||
$this->assertNull( Resolver::pick( 1, 99, array(), array( $this->def( 1 ) ) ) );
|
||||
$this->assertNull( Resolver::pick( 1, 5000, array(), array() ) );
|
||||
}
|
||||
|
||||
public function test_reward_beats_amount(): void {
|
||||
$defs = array( $this->def( 1, array( 'min_minor' => 100 ) ), $this->def( 2, array( 'trigger_type' => 'reward', 'action_id' => 9 ) ) );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 5000, array( 9 ), $defs )['id'] );
|
||||
$this->assertSame( 1, Resolver::pick( 1, 5000, array( 8 ), $defs )['id'], 'other reward does not match' );
|
||||
$this->assertSame( 1, Resolver::pick( 1, 5000, array(), $defs )['id'] );
|
||||
}
|
||||
|
||||
public function test_reward_def_matches_even_when_base_is_tiny(): void {
|
||||
$defs = array( $this->def( 2, array( 'trigger_type' => 'reward', 'action_id' => 9, 'min_minor' => 0 ) ) );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 1, array( 9 ), $defs )['id'] );
|
||||
}
|
||||
|
||||
public function test_several_rewards_highest_reward_amount_then_sort_then_id(): void {
|
||||
$defs = array(
|
||||
$this->def( 1, array( 'trigger_type' => 'reward', 'action_id' => 5, 'sort' => 0 ) ),
|
||||
$this->def( 2, array( 'trigger_type' => 'reward', 'action_id' => 6, 'sort' => 9 ) ),
|
||||
);
|
||||
$this->assertSame( 2, Resolver::pick( 1, 5000, array( 5, 6 ), $defs, array( 5 => 500, 6 => 2500 ) )['id'] );
|
||||
$this->assertSame( 1, Resolver::pick( 1, 5000, array( 5, 6 ), $defs, array( 5 => 500, 6 => 500 ) )['id'], 'tie: lower sort' );
|
||||
$defs[1]['sort'] = 0;
|
||||
$this->assertSame( 1, Resolver::pick( 1, 5000, array( 5, 6 ), $defs )['id'], 'tie: lower id' );
|
||||
}
|
||||
|
||||
public function test_goal_scoping(): void {
|
||||
$defs = array( $this->def( 1, array( 'goal_id' => 7, 'min_minor' => 100 ) ), $this->def( 2, array( 'goal_id' => 0, 'min_minor' => 100, 'sort' => 5 ) ) );
|
||||
$this->assertSame( 1, Resolver::pick( 7, 500, array(), $defs )['id'] );
|
||||
$this->assertSame( 2, Resolver::pick( 8, 500, array(), $defs )['id'], 'goal 8 never sees goal 7 defs' );
|
||||
$this->assertSame( 2, Resolver::pick( 0, 500, array(), $defs )['id'], 'test donations (goal 0) use goal-0 defs only' );
|
||||
$only7 = array( $defs[0] );
|
||||
$this->assertNull( Resolver::pick( 0, 500, array(), $only7 ) );
|
||||
}
|
||||
|
||||
public function test_disabled_ignored(): void {
|
||||
$defs = array( $this->def( 1, array( 'enabled' => 0, 'min_minor' => 1000 ) ), $this->def( 2, array( 'min_minor' => 100 ) ),
|
||||
$this->def( 3, array( 'trigger_type' => 'reward', 'action_id' => 9, 'enabled' => 0 ) ) );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 5000, array( 9 ), $defs )['id'] );
|
||||
}
|
||||
|
||||
public function test_string_columns_from_db_are_handled_and_unknown_trigger_ignored(): void {
|
||||
$defs = array( array( 'id' => '4', 'goal_id' => '0', 'trigger_type' => 'amount', 'min_minor' => '500', 'enabled' => '1', 'sort' => '0' ),
|
||||
array( 'id' => '5', 'trigger_type' => 'bogus', 'enabled' => 1 ) );
|
||||
$this->assertSame( 4, Resolver::pick( 3, 500, array(), $defs )['id'] );
|
||||
}
|
||||
|
||||
public function test_equal_minimum_tie_breaks_by_sort_then_id(): void {
|
||||
$defs = array( $this->def( 1, array( 'sort' => 5 ) ), $this->def( 2, array( 'sort' => 1 ) ) );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 500, array(), $defs )['id'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Core\CidrMatcher;
|
||||
use StreamGoals\Core\CloudflareRanges;
|
||||
|
||||
final class CidrMatcherTest extends TestCase {
|
||||
|
||||
public function test_ipv4_boundaries(): void {
|
||||
$r = array( '173.245.48.0/20' ); // 173.245.48.0 - 173.245.63.255
|
||||
$this->assertTrue( CidrMatcher::contains( '173.245.48.0', $r ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '173.245.63.255', $r ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '173.245.47.255', $r ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '173.245.64.0', $r ) );
|
||||
}
|
||||
|
||||
public function test_non_byte_aligned_and_wide_masks(): void {
|
||||
$this->assertTrue( CidrMatcher::contains( '104.27.255.255', array( '104.24.0.0/14' ) ) ); // /14 spans 104.24 - 104.27
|
||||
$this->assertFalse( CidrMatcher::contains( '104.28.0.0', array( '104.24.0.0/14' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '104.23.255.255', array( '104.24.0.0/14' ) ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '8.8.8.8', array( '0.0.0.0/0' ) ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '1.2.3.4', array( '1.2.3.4/32' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '1.2.3.5', array( '1.2.3.4/32' ) ) );
|
||||
}
|
||||
|
||||
public function test_ipv6(): void {
|
||||
$this->assertTrue( CidrMatcher::contains( '2606:4700::1', array( '2606:4700::/32' ) ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '2a06:98c7:ffff::1', array( '2a06:98c0::/29' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '2a06:98c8::1', array( '2a06:98c0::/29' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '2606:4701::1', array( '2606:4700::/32' ) ) );
|
||||
}
|
||||
|
||||
public function test_families_never_cross_match_and_bad_input_is_false(): void {
|
||||
$this->assertFalse( CidrMatcher::contains( '1.2.3.4', array( '2606:4700::/32' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '2606:4700::1', array( '173.245.48.0/20' ) ) );
|
||||
foreach ( array( 'garbage', '', '999.1.1.1', "1.2.3.4\nX: y", '1.2.3.4, 5.6.7.8' ) as $bad ) {
|
||||
$this->assertFalse( CidrMatcher::contains( $bad, array( '0.0.0.0/0' ) ), "matched bad ip: $bad" );
|
||||
}
|
||||
foreach ( array( '1.2.3.4', '1.2.3.4/x', '1.2.3.4/33', '1.2.3.4/-1', 'nope/8', '' ) as $badCidr ) {
|
||||
$this->assertFalse( CidrMatcher::contains( '1.2.3.4', array( $badCidr ) ), "matched bad cidr: $badCidr" );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_surrounding_whitespace_is_tolerated(): void {
|
||||
$this->assertTrue( CidrMatcher::contains( ' 173.245.48.1 ', array( '173.245.48.0/20' ) ) );
|
||||
}
|
||||
|
||||
public function test_cloudflare_ranges(): void {
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '172.70.1.1' ) );
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '104.16.0.1' ) );
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '2606:4700:3030::1' ) );
|
||||
$this->assertFalse( CloudflareRanges::isCloudflare( '203.0.113.9' ) );
|
||||
$this->assertFalse( CloudflareRanges::isCloudflare( '47.151.185.180' ) );
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '203.0.113.9', array( '203.0.113.0/24' ) ), 'filter-supplied ranges extend the list' );
|
||||
}
|
||||
}
|
||||
@@ -56,4 +56,28 @@ final class ClientIpTest extends TestCase {
|
||||
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4' );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, 'something_else' ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_trusts_cf_header_only_from_a_cloudflare_connection(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => '172.70.1.1', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
|
||||
$v6 = array( 'REMOTE_ADDR' => '2606:4700:3030::1', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $v6, ClientIp::MODE_AUTO ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_ignores_a_forged_header_from_a_non_cloudflare_connection(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => '47.151.185.180', 'HTTP_CF_CONNECTING_IP' => '6.6.6.6', 'HTTP_X_FORWARDED_FOR' => '7.7.7.7' );
|
||||
$this->assertSame( '47.151.185.180', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_falls_back_when_header_missing_or_invalid(): void {
|
||||
$this->assertSame( '172.70.1.1', ClientIp::resolve( array( 'REMOTE_ADDR' => '172.70.1.1' ), ClientIp::MODE_AUTO ) );
|
||||
$this->assertSame( '172.70.1.1', ClientIp::resolve( array( 'REMOTE_ADDR' => '172.70.1.1', 'HTTP_CF_CONNECTING_IP' => 'nope' ), ClientIp::MODE_AUTO ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_extra_ranges_from_the_filter(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => '198.18.0.5', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( '198.18.0.5', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO, array( '198.18.0.0/15' ) ) );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Core\FeeCalculator;
|
||||
use StreamGoals\Core\GoalTargetPolicy;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\PayPal\OrderValidator;
|
||||
use StreamGoals\PayPal\ValidationException;
|
||||
|
||||
final class GoalTargetPolicyTest extends TestCase {
|
||||
|
||||
private function goal( array $o = array() ): array {
|
||||
return array_merge( array( 'id' => 3, 'currency' => 'USD', 'status' => 'active', 'target_minor' => 10000, 'close_at_target' => 1, 'counts_fees' => 0, 'starts_at' => null, 'ends_at' => null ), $o );
|
||||
}
|
||||
|
||||
public function test_below_equal_and_over_target(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal(), 9999 ) );
|
||||
$this->assertTrue( GoalTargetPolicy::shouldClose( $this->goal(), 10000 ) );
|
||||
$this->assertTrue( GoalTargetPolicy::shouldClose( $this->goal(), 25000 ) );
|
||||
}
|
||||
|
||||
public function test_flag_off_or_missing_never_closes(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'close_at_target' => 0 ) ), 99999 ) );
|
||||
$g = $this->goal();
|
||||
unset( $g['close_at_target'] );
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $g, 99999 ) );
|
||||
}
|
||||
|
||||
public function test_only_active_goals_are_closed(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'status' => 'complete' ) ), 20000 ) );
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'status' => 'paused' ) ), 20000 ) );
|
||||
}
|
||||
|
||||
public function test_target_zero_never_closes(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'target_minor' => 0 ) ), 0 ) );
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'target_minor' => 0 ) ), 500 ) );
|
||||
}
|
||||
|
||||
public function test_base_vs_total_basis(): void {
|
||||
$this->assertSame( 'base_minor', GoalTargetPolicy::amountColumn( $this->goal() ) );
|
||||
$this->assertSame( 'total_minor', GoalTargetPolicy::amountColumn( $this->goal( array( 'counts_fees' => 1 ) ) ) );
|
||||
}
|
||||
|
||||
public function test_closed_at_target_detection_and_pause_is_not_closed(): void {
|
||||
$this->assertTrue( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'complete' ) ) ) );
|
||||
$this->assertFalse( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'paused' ) ) ) );
|
||||
$this->assertFalse( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'complete', 'close_at_target' => 0 ) ) ) );
|
||||
}
|
||||
|
||||
public function test_checkbox_parsing(): void {
|
||||
$this->assertSame( 1, GoalTargetPolicy::flagFromPost( '1' ) );
|
||||
$this->assertSame( 1, GoalTargetPolicy::flagFromPost( 'on' ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( null ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( '' ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( '0' ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( array( '1' ) ) );
|
||||
}
|
||||
|
||||
public function test_new_orders_for_a_closed_goal_get_a_friendly_409(): void {
|
||||
try {
|
||||
OrderValidator::validate( array( 'amount' => '5.00' ), $this->goal( array( 'status' => 'complete' ) ), Settings::defaults(), new FeeCalculator( 349, 49 ), 1800000000 );
|
||||
$this->fail( 'expected refusal' );
|
||||
} catch ( ValidationException $e ) {
|
||||
$this->assertSame( 'goal_inactive', $e->errorCode );
|
||||
$this->assertSame( 409, $e->status );
|
||||
$this->assertStringContainsString( 'Thank you', $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_paused_goal_keeps_generic_message(): void {
|
||||
try {
|
||||
OrderValidator::quote( array( 'amount' => '5.00' ), $this->goal( array( 'status' => 'paused' ) ), Settings::defaults(), new FeeCalculator( 349, 49 ), 1800000000 );
|
||||
$this->fail( 'expected refusal' );
|
||||
} catch ( ValidationException $e ) {
|
||||
$this->assertSame( 'This goal is not accepting donations.', $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_goal_open_for_active_flagged_goal(): void {
|
||||
$this->assertTrue( OrderValidator::goalIsOpen( $this->goal(), 1800000000 ) );
|
||||
$this->assertFalse( OrderValidator::goalIsOpen( $this->goal( array( 'status' => 'complete' ) ), 1800000000 ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Alerts\AlertMedia;
|
||||
use StreamGoals\Overlay\ActionsSource;
|
||||
use StreamGoals\Overlay\AlertMediaSource;
|
||||
use StreamGoals\Overlay\OverlayDataSource;
|
||||
use StreamGoals\Overlay\OverlayService;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\Overlay\RecentDonationsSource;
|
||||
|
||||
final class OverlayAlertMediaTest extends TestCase {
|
||||
|
||||
private function def( int $id, array $o = array() ): array {
|
||||
return $o + array( 'id' => $id, 'goal_id' => 0, 'trigger_type' => 'amount', 'min_minor' => 100, 'action_id' => 0, 'visual_id' => 10, 'visual_type' => 'image',
|
||||
'sound_id' => 12, 'volume' => 60, 'duration_ms' => 7000, 'message' => '', 'enabled' => 1, 'sort' => 0 );
|
||||
}
|
||||
|
||||
private function row( int $id, array $o = array() ): array {
|
||||
return $o + array( 'id' => $id, 'goal_id' => 7, 'base_minor' => 2500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0,
|
||||
'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
|
||||
}
|
||||
|
||||
private function files(): array {
|
||||
return array(
|
||||
10 => array( 'url' => 'https://cdn.test/a.gif', 'mime' => 'image/gif' ),
|
||||
11 => array( 'url' => 'https://cdn.test/v.mp4', 'mime' => 'video/mp4' ),
|
||||
12 => array( 'url' => 'https://cdn.test/s.mp3', 'mime' => 'audio/mpeg' ),
|
||||
13 => array( 'url' => 'https://cdn.test/x.svg', 'mime' => 'image/svg+xml' ),
|
||||
14 => array( 'url' => 'javascript:alert(1)', 'mime' => 'image/png' ),
|
||||
);
|
||||
}
|
||||
|
||||
private function build( array $def, array $row = array(), array $triggered = array() ): ?array {
|
||||
$files = $this->files();
|
||||
return AlertMedia::build( $row ?: $this->row( 1 ), 'Al', '$25.00', array( $def ), $triggered, static fn( int $id ): ?array => $files[ $id ] ?? null );
|
||||
}
|
||||
|
||||
public function test_shape_for_image_and_sound(): void {
|
||||
$m = $this->build( $this->def( 1, array( 'message' => '{name} gave {amount}' ) ) );
|
||||
$this->assertSame( array(
|
||||
'visual' => array( 'type' => 'image', 'url' => 'https://cdn.test/a.gif' ),
|
||||
'sound' => array( 'url' => 'https://cdn.test/s.mp3' ),
|
||||
'volume' => 60,
|
||||
'duration_ms' => 7000,
|
||||
'message' => 'Al gave $25.00',
|
||||
), $m );
|
||||
}
|
||||
|
||||
public function test_video_duration_is_capped_and_type_comes_from_mime(): void {
|
||||
$m = $this->build( $this->def( 1, array( 'visual_id' => 11, 'visual_type' => 'image', 'duration_ms' => 2000 ) ) );
|
||||
$this->assertSame( 'video', $m['visual']['type'] );
|
||||
$this->assertSame( 30000, $m['duration_ms'] );
|
||||
$this->assertNull( $m['message'] );
|
||||
}
|
||||
|
||||
public function test_invalid_media_dropped_silently(): void {
|
||||
$m = $this->build( $this->def( 1, array( 'visual_id' => 13, 'sound_id' => 99 ) ) );
|
||||
$this->assertNull( $m, 'nothing usable and no message: plain alert' );
|
||||
$m = $this->build( $this->def( 1, array( 'visual_id' => 13, 'sound_id' => 12 ) ) );
|
||||
$this->assertNull( $m['visual'] );
|
||||
$this->assertSame( 'https://cdn.test/s.mp3', $m['sound']['url'] );
|
||||
$m = $this->build( $this->def( 1, array( 'visual_id' => 14, 'sound_id' => 0, 'message' => 'hi' ) ) );
|
||||
$this->assertNull( $m['visual'], 'non-http url dropped' );
|
||||
$this->assertSame( 'hi', $m['message'] );
|
||||
$this->assertNull( $this->build( $this->def( 1, array( 'sound_id' => 10, 'visual_id' => 12 ) ) ), 'wrong kinds in wrong slots' );
|
||||
}
|
||||
|
||||
public function test_urls_come_only_from_callback_not_from_def_or_row(): void {
|
||||
$def = $this->def( 1, array( 'url' => 'https://evil.test/x.png', 'visual_url' => 'https://evil.test/y.png' ) );
|
||||
$row = $this->row( 1, array( 'media' => array( 'visual' => array( 'type' => 'image', 'url' => 'https://evil.test/z.png' ) ) ) );
|
||||
$json = json_encode( $this->build( $def, $row ) );
|
||||
$this->assertStringNotContainsString( 'evil.test', (string) $json );
|
||||
$this->assertStringContainsString( 'cdn.test\/a.gif', (string) $json );
|
||||
$boom = AlertMedia::build( $this->row( 1 ), 'Al', '$1', array( $this->def( 1 ) ), array(), static function ( int $id ): ?array { throw new \RuntimeException( 'db' ); } );
|
||||
$this->assertNull( $boom );
|
||||
}
|
||||
|
||||
public function test_reward_token_and_reward_priority(): void {
|
||||
$trig = array( array( 'action_id' => 5, 'amount_minor' => 500, 'title' => 'Eat bean' ), array( 'action_id' => 6, 'amount_minor' => 2500, 'title' => 'Pushups' ) );
|
||||
$defs = array( $this->def( 1, array( 'message' => 'amt {reward}' ) ), $this->def( 2, array( 'trigger_type' => 'reward', 'action_id' => 5, 'message' => 'rw {reward}' ) ) );
|
||||
$files = $this->files();
|
||||
$m = AlertMedia::build( $this->row( 1 ), 'Al', '$25.00', $defs, $trig, static fn( int $id ): ?array => $files[ $id ] ?? null );
|
||||
$this->assertSame( 'rw Eat bean', $m['message'] );
|
||||
$m = AlertMedia::build( $this->row( 1 ), 'Al', '$25.00', array( $defs[0] ), $trig, static fn( int $id ): ?array => $files[ $id ] ?? null );
|
||||
$this->assertSame( 'amt Pushups', $m['message'], 'amount def gets the highest triggered reward' );
|
||||
}
|
||||
|
||||
/** Service-level: one defs query, one triggered query, goal 0 for tests, anonymity/moderation intact. */
|
||||
private function svc( array $defs, array $db, array $triggered = array() ): array {
|
||||
$src = new class( $defs, $db, $triggered, $this->files() ) implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource {
|
||||
public int $defQueries = 0; public int $trigQueries = 0;
|
||||
public function __construct( public array $defs, private array $db, private array $trig, private array $files ) {}
|
||||
public function activeGoal(): ?array { return array( 'id' => 7, 'currency' => 'USD' ); }
|
||||
public function raisedMinor( array $goal ): int { return 0; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); }
|
||||
public function bonusesFor( array $ids ): array { return array(); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return array_values( array_filter( $this->db, fn( $d ) => $d['id'] > (int) $sinceId ) ); }
|
||||
public function recentDonations( int $limit ): array { return $this->db; }
|
||||
public function menuActions( int $goalId ): array { return array(); }
|
||||
public function actionsFor( array $ids ): array { return array(); }
|
||||
public function alertDefs(): array { ++$this->defQueries; return $this->defs; }
|
||||
public function triggeredActionsFor( array $ids ): array { ++$this->trigQueries; return $this->trig; }
|
||||
public function attachment( int $id ): ?array { return $this->files[ $id ] ?? null; }
|
||||
};
|
||||
return array( new OverlayService( $src ), $src );
|
||||
}
|
||||
|
||||
public function test_payload_carries_media_in_recent_and_since_modes_with_single_queries(): void {
|
||||
[ $svc, $src ] = $this->svc( array( $this->def( 1 ) ), array( $this->row( 1 ), $this->row( 2 ), $this->row( 3, array( 'goal_id' => 0 ) ) ) );
|
||||
$out = $svc->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( 'https://cdn.test/a.gif', $out['alerts'][0]['media']['visual']['url'] );
|
||||
$this->assertSame( 1, $src->defQueries );
|
||||
$this->assertSame( 1, $src->trigQueries );
|
||||
[ $svc2 ] = $this->svc( array( $this->def( 1 ) ), array( $this->row( 1 ), $this->row( 2 ) ) );
|
||||
$this->assertSame( 60, $svc2->payload( 'alerts', 1, 0, false )['alerts'][1]['media']['volume'] );
|
||||
}
|
||||
|
||||
public function test_goal_scoping_in_payload_and_test_donations(): void {
|
||||
$defs = array( $this->def( 1, array( 'goal_id' => 7 ) ) );
|
||||
[ $svc ] = $this->svc( $defs, array( $this->row( 1 ), $this->row( 2, array( 'goal_id' => 0 ) ), $this->row( 3, array( 'goal_id' => 9 ) ) ) );
|
||||
$a = $svc->payload( 'alerts', 1, null, true )['alerts'];
|
||||
$this->assertNotNull( $a[0]['media'] );
|
||||
$this->assertNull( $a[1]['media'], 'test donation (goal 0) does not use goal-7 defs' );
|
||||
$this->assertNull( $a[2]['media'] );
|
||||
}
|
||||
|
||||
public function test_no_defs_means_media_null_and_no_trigger_query(): void {
|
||||
[ $svc, $src ] = $this->svc( array(), array( $this->row( 1 ) ) );
|
||||
$this->assertNull( $svc->payload( 'alerts', 1, null, true )['alerts'][0]['media'] );
|
||||
$this->assertSame( 0, $src->trigQueries );
|
||||
}
|
||||
|
||||
public function test_moderation_and_anonymity_unchanged(): void {
|
||||
$rows = array( $this->row( 1, array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ), $this->row( 2, array( 'moderation' => 'pending' ) ) );
|
||||
[ $svc ] = $this->svc( array( $this->def( 1, array( 'message' => '{name}!' ) ) ), $rows );
|
||||
$a = $svc->payload( 'alerts', 1, null, true )['alerts'];
|
||||
$this->assertCount( 1, $a );
|
||||
$this->assertSame( 'Anonymous', $a[0]['name'] );
|
||||
$this->assertSame( 'Anonymous!', $a[0]['media']['message'] );
|
||||
$this->assertStringNotContainsString( 'Secret', (string) json_encode( $a ) );
|
||||
}
|
||||
|
||||
public function test_etag_changes_with_media_definitions_even_without_alerts(): void {
|
||||
[ $a ] = $this->svc( array( $this->def( 1 ) ), array() );
|
||||
[ $b ] = $this->svc( array( $this->def( 1, array( 'volume' => 10 ) ) ), array() );
|
||||
[ $none ] = $this->svc( array(), array() );
|
||||
$pa = $a->payload( 'alerts', 1, 0, false );
|
||||
$ea = Payloads::etag( $pa, $a->etagSalt( 'alerts' ) );
|
||||
$this->assertNotSame( $ea, Payloads::etag( $pa, $b->etagSalt( 'alerts' ) ) );
|
||||
$this->assertNotSame( $ea, Payloads::etag( $pa, $none->etagSalt( 'alerts' ) ) );
|
||||
$this->assertSame( Payloads::etag( $pa ), Payloads::etag( $pa, $none->etagSalt( 'alerts' ) ), 'no defs: unchanged etag' );
|
||||
$this->assertSame( '', $a->etagSalt( 'goal' ) );
|
||||
}
|
||||
|
||||
public function test_etag_changes_when_attachment_url_changes(): void {
|
||||
$p1 = array( 'alerts' => array( array( 'id' => 1, 'media' => array( 'visual' => array( 'url' => 'https://a/1' ) ) ) ) );
|
||||
$p2 = array( 'alerts' => array( array( 'id' => 1, 'media' => array( 'visual' => array( 'url' => 'https://a/2' ) ) ) ) );
|
||||
$this->assertNotSame( Payloads::etag( $p1 ), Payloads::etag( $p2 ) );
|
||||
}
|
||||
|
||||
public function test_payloads_alerts_calls_media_callback_with_public_name_only_for_shown_rows(): void {
|
||||
$seen = array();
|
||||
$cb = static function ( array $r, string $name, string $amount ) use ( &$seen ): ?array { $seen[] = array( $r['id'], $name, $amount ); return null; };
|
||||
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 );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user