Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c7f2dcffeb | ||
|
|
1e2ca96eed | ||
|
|
4cec93067c | ||
|
|
27646c1001 | ||
|
|
3bbd77b661 | ||
|
|
e4d9042aba | ||
|
|
4f92cfdade | ||
|
|
fa4feddd35 | ||
|
|
e22675f54b | ||
|
|
a259c0b0a1 | ||
|
|
19d399e8c7 | ||
|
|
4efdef72f6 |
No files matched your search
@@ -0,0 +1,71 @@
|
||||
# StreamGoals Donate
|
||||
|
||||
PayPal donations for WordPress, built for streamers: multiple donation goals, optional "cover the fees",
|
||||
and OBS overlays (goal bar, subathon timer, counter, donation alerts) that update live.
|
||||
|
||||
Requires WordPress 7.x, PHP 8.1+, and a **PayPal Business** account to take live payments (see below).
|
||||
|
||||
## Install
|
||||
1. Download `streamgoals-donate.zip` from the latest [release](../../releases).
|
||||
2. WordPress admin → Plugins → Add New → Upload Plugin → activate.
|
||||
3. Open **StreamGoals** in the admin menu. The setup wizard walks you through the rest.
|
||||
|
||||
## Which PayPal account?
|
||||
- **Testing:** nothing special. PayPal's Sandbox gives every developer account a sandbox business account
|
||||
(the seller) and a sandbox personal account (the buyer).
|
||||
- **Live payments:** PayPal's developer policy requires a **Business** account to go live. Upgrading a
|
||||
Personal account is free, and a personal name is fine (no company needed).
|
||||
- PayPal's User Agreement also expects accounts used mainly for business or donation-taking to be Business accounts;
|
||||
a Personal account used that way risks limits or closure. Read PayPal's current terms before going live.
|
||||
|
||||
## Connect PayPal (about 5 minutes)
|
||||
You need two values from PayPal: a **Client ID** and a **Secret**.
|
||||
|
||||
1. Go to <https://developer.paypal.com> and log in with your PayPal Business account.
|
||||
2. Open **Apps & Credentials**. Use the **Sandbox** toggle for testing, **Live** for real money.
|
||||
3. Click **Create App**, name it anything (e.g. "My Donations"), type **Merchant**.
|
||||
4. Copy the **Client ID** and **Secret** into the StreamGoals wizard (Step 1).
|
||||
5. Click **Test connection**. On success the plugin registers its webhook with PayPal automatically.
|
||||
|
||||
Start in **Sandbox**, make a test donation using a PayPal sandbox buyer account, then repeat the steps
|
||||
with the Live credentials and switch the mode to Live in Settings.
|
||||
|
||||
### Notes on fees and currency
|
||||
- "Cover the processing fees" adds an estimate based on the rates in Settings (default: US domestic,
|
||||
3.49% + $0.49). Your actual PayPal rate depends on your account, country and payment method.
|
||||
- Cross-border and currency-conversion fees are **not** included in the estimate, so a covered donation
|
||||
from another country can net slightly less than intended.
|
||||
- One currency per site. PayPal converts for donors paying from another currency.
|
||||
- Donations are not tax-deductible. Don't present them as such.
|
||||
|
||||
## Using it
|
||||
- **Donation page:** add the shortcode `[streamgoals_donate]` to a page (or `[streamgoals_donate goal="ID"]` to pin one goal).
|
||||
- **Goals:** StreamGoals → Goals. Create as many as you like; each can have its own rules.
|
||||
- **Rules (time and counters):** per goal, e.g. "+60 seconds per $1" (subathon timer), "+1 per $10" (counter),
|
||||
or a bonus event above a minimum amount. Amounts can be measured on the base donation or including fee cover.
|
||||
- **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.
|
||||
- **Test:** "Send test donation" on the Overlays screen shows an alert without touching real totals.
|
||||
|
||||
## Privacy and moderation
|
||||
- Donors choose a name or "Anonymous". For anonymous donors the **name is never stored**.
|
||||
- Optional message approval queue and a streamer-controlled profanity filter (whole-word, your own word list).
|
||||
|
||||
## Not supported
|
||||
- **Refunds and chargebacks are not tracked.** If you refund someone in PayPal, goal totals, timers and
|
||||
counters are not adjusted.
|
||||
|
||||
## Updates
|
||||
New versions appear in WordPress automatically (Dashboard > Updates and the Plugins screen), checked against
|
||||
this repository's releases. The repository is public, so no token is needed. (If you run a private fork, paste an
|
||||
access token with read access to releases in StreamGoals > Settings > Advanced > Plugin updates.) You can switch
|
||||
automatic updates on or off for this plugin on the Plugins screen, and use "Check for updates now" in
|
||||
StreamGoals > Settings > Advanced to look straight away.
|
||||
|
||||
## Development
|
||||
```
|
||||
composer install
|
||||
vendor/bin/phpunit
|
||||
```
|
||||
Architecture notes are in `docs/ARCHITECTURE.md`. Every push to `main` runs the tests and, if they pass,
|
||||
publishes a versioned zip release via Gitea Actions.
|
||||
@@ -0,0 +1,46 @@
|
||||
.sg-admin .sg-lead { font-size: 15px; max-width: 70ch; }
|
||||
.sg-admin .sg-card { background: #fff; border: 1px solid #c3c4c7; border-radius: 6px; padding: 8px 20px 16px; margin: 16px 0; max-width: 960px; }
|
||||
.sg-admin .sg-card h2 { margin-top: 12px; }
|
||||
.sg-admin .sg-inline { display: inline-block; margin: 0 4px 4px 0; }
|
||||
.sg-admin .sg-ok { color: #00700f; font-weight: 600; }
|
||||
.sg-admin .sg-warn { color: #8a4b00; font-weight: 600; }
|
||||
.sg-admin .sg-steps { max-width: 80ch; line-height: 1.6; }
|
||||
.sg-admin .sg-steps li { margin-bottom: 6px; }
|
||||
.sg-admin .sg-progress { display: flex; flex-wrap: wrap; gap: 8px; list-style: none; padding: 0; margin: 12px 0; counter-reset: sg; }
|
||||
.sg-admin .sg-progress li { counter-increment: sg; padding: 6px 14px; border-radius: 999px; background: #f0f0f1; color: #50575e; }
|
||||
.sg-admin .sg-progress li::before { content: counter(sg) ". "; }
|
||||
.sg-admin .sg-progress li.is-done { background: #d7f0dc; }
|
||||
.sg-admin .sg-progress li.is-current { background: #2271b1; color: #fff; font-weight: 600; }
|
||||
.sg-admin .sg-progress li.is-current a { color: #fff; }
|
||||
.sg-admin .sg-tabs { display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0 4px; }
|
||||
.sg-admin .sg-tab { border: 2px solid #c3c4c7; border-radius: 6px; padding: 8px 14px; cursor: pointer; background: #fff; }
|
||||
.sg-admin .sg-tab:has(input:checked) { border-color: #2271b1; background: #f0f6fc; }
|
||||
.sg-admin .sg-templates { display: grid; gap: 10px; margin: 10px 0; }
|
||||
.sg-admin .sg-template { border: 2px solid #c3c4c7; border-radius: 6px; padding: 10px 14px; cursor: pointer; display: block; }
|
||||
.sg-admin .sg-template:has(input:checked) { border-color: #2271b1; background: #f0f6fc; }
|
||||
.sg-admin .sg-template span { color: #50575e; margin-left: 24px; }
|
||||
.sg-admin .sg-copy { display: flex; gap: 8px; align-items: center; max-width: 720px; }
|
||||
.sg-admin .sg-copy input { flex: 1; min-width: 0; }
|
||||
.sg-admin .sg-overlay-card { border-top: 1px solid #dcdcde; padding: 4px 0 10px; }
|
||||
.sg-admin .sg-overlay-card:first-of-type { border-top: 0; }
|
||||
.sg-admin .sg-preview { overflow: auto; max-width: 100%; margin-top: 6px; border: 1px solid #c3c4c7; background: repeating-conic-gradient(#e6e6e6 0% 25%, #fafafa 0% 50%) 50% / 20px 20px; }
|
||||
.sg-admin .sg-preview iframe { border: 0; display: block; max-width: none; }
|
||||
.sg-admin .sg-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; }
|
||||
.sg-admin .sg-grid label { display: flex; flex-direction: column; gap: 4px; font-weight: 600; }
|
||||
.sg-admin .sg-grid input[type="color"] { padding: 0; height: 32px; width: 64px; }
|
||||
.sg-admin .sg-table td, .sg-admin .sg-table th { vertical-align: top; }
|
||||
.sg-admin .sg-actions { white-space: normal; }
|
||||
.sg-admin .sg-badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12px; background: #f0f0f1; }
|
||||
.sg-admin .sg-active { background: #d7f0dc; }
|
||||
.sg-admin .sg-paused, .sg-admin .sg-pending { background: #fcf0c3; }
|
||||
.sg-admin .sg-complete { background: #dbe7f7; }
|
||||
.sg-admin .sg-test { background: #f4d6f5; font-weight: 700; }
|
||||
.sg-admin .sg-rejected { background: #f7d5d5; }
|
||||
.sg-admin .sg-bar { height: 6px; background: #e0e0e0; border-radius: 3px; margin-top: 4px; max-width: 180px; overflow: hidden; }
|
||||
.sg-admin .sg-bar span { display: block; height: 100%; background: #2271b1; }
|
||||
.sg-admin tr.sg-off td { opacity: .55; }
|
||||
.sg-admin .sg-preview-list { font-size: 14px; list-style: disc; margin-left: 20px; }
|
||||
.sg-admin .sg-form-preview { color: #00700f; font-weight: 600; min-height: 1.4em; }
|
||||
.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; } }
|
||||
@@ -0,0 +1,59 @@
|
||||
/* StreamGoals admin: copy buttons and confirm prompts. No dependencies. */
|
||||
( function () {
|
||||
'use strict';
|
||||
|
||||
function flash( btn, text ) {
|
||||
var old = btn.getAttribute( 'data-label' ) || btn.textContent;
|
||||
btn.setAttribute( 'data-label', old );
|
||||
btn.textContent = text;
|
||||
window.setTimeout( function () { btn.textContent = old; }, 1500 );
|
||||
}
|
||||
|
||||
function copyText( text, btn, input ) {
|
||||
function fallback() {
|
||||
var el = input;
|
||||
var temp = null;
|
||||
if ( ! el ) {
|
||||
temp = el = document.createElement( 'textarea' );
|
||||
el.value = text;
|
||||
el.style.position = 'fixed';
|
||||
el.style.opacity = '0';
|
||||
document.body.appendChild( el );
|
||||
}
|
||||
el.select();
|
||||
var ok = false;
|
||||
try { ok = document.execCommand( 'copy' ); } catch ( e ) { ok = false; }
|
||||
if ( temp ) { document.body.removeChild( temp ); }
|
||||
flash( btn, ok ? 'Copied!' : 'Press Ctrl+C' );
|
||||
}
|
||||
if ( navigator.clipboard && window.isSecureContext ) {
|
||||
navigator.clipboard.writeText( text ).then( function () { flash( btn, 'Copied!' ); }, fallback );
|
||||
} else {
|
||||
fallback();
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener( 'click', function ( e ) {
|
||||
var btn = e.target.closest ? e.target.closest( '[data-sg-copy],[data-sg-copy-text]' ) : null;
|
||||
if ( ! btn ) { return; }
|
||||
e.preventDefault();
|
||||
if ( btn.hasAttribute( 'data-sg-copy-text' ) ) {
|
||||
copyText( btn.getAttribute( 'data-sg-copy-text' ), btn, null );
|
||||
return;
|
||||
}
|
||||
var input = btn.parentNode.querySelector( 'input' );
|
||||
if ( input ) { copyText( input.value, btn, input ); }
|
||||
} );
|
||||
|
||||
document.addEventListener( 'focusin', function ( e ) {
|
||||
if ( e.target.classList && e.target.classList.contains( 'sg-url' ) ) { e.target.select(); }
|
||||
} );
|
||||
|
||||
document.addEventListener( 'submit', function ( e ) {
|
||||
var form = e.target;
|
||||
if ( ! form.classList || ! form.classList.contains( 'sg-confirm' ) ) { return; }
|
||||
var src = e.submitter || form.querySelector( '[data-confirm]' );
|
||||
var msg = src && src.getAttribute( 'data-confirm' );
|
||||
if ( msg && ! window.confirm( msg ) ) { e.preventDefault(); }
|
||||
} );
|
||||
}() );
|
||||
@@ -0,0 +1,77 @@
|
||||
/* StreamGoals overlay style builder: keeps every overlay URL and preview in sync with the style form. */
|
||||
( function () {
|
||||
'use strict';
|
||||
var form = document.getElementById( 'sg-style' );
|
||||
if ( ! form ) { return; }
|
||||
var cards = Array.prototype.slice.call( document.querySelectorAll( '.sg-overlay-card' ) );
|
||||
var COLORS = [ 'color', 'accent', 'accent2', 'track', 'bg' ];
|
||||
var timer = null;
|
||||
|
||||
function params() {
|
||||
var q = [];
|
||||
function add( k, v ) { q.push( encodeURIComponent( k ) + '=' + encodeURIComponent( v ) ); }
|
||||
var theme = form.elements.theme.value;
|
||||
if ( theme && theme !== 'dark' ) { add( 'theme', theme ); }
|
||||
var font = form.elements.font.value;
|
||||
var customBox = form.querySelector( '.sg-custom-font' );
|
||||
if ( font === '__custom' ) {
|
||||
var f = ( form.elements.font_custom.value || '' ).trim();
|
||||
if ( /^[A-Za-z0-9][A-Za-z0-9 \-]{0,39}$/.test( f ) ) { add( 'font', f ); }
|
||||
if ( customBox ) { customBox.hidden = false; }
|
||||
} else {
|
||||
if ( customBox ) { customBox.hidden = true; }
|
||||
if ( font && font !== 'sans' ) { add( 'font', font ); }
|
||||
}
|
||||
var scale = parseFloat( form.elements.scale.value );
|
||||
if ( isFinite( scale ) && scale >= 0.5 && scale <= 3 && scale !== 1 ) { add( 'scale', String( Math.round( scale * 100 ) / 100 ) ); }
|
||||
COLORS.forEach( function ( k ) {
|
||||
if ( form.elements[ 'use_' + k ].checked ) { add( k, form.elements[ k ].value.replace( '#', '' ) ); }
|
||||
} );
|
||||
return q.join( '&' );
|
||||
}
|
||||
|
||||
function previewSrc( card ) {
|
||||
var base = card.getAttribute( 'data-base' );
|
||||
var sep = card.getAttribute( 'data-sep' );
|
||||
var q = params();
|
||||
return q ? base + sep + q : base;
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
cards.forEach( function ( card ) {
|
||||
var url = previewSrc( card );
|
||||
var input = card.querySelector( '.sg-url' );
|
||||
if ( input ) { input.value = url; }
|
||||
var wrap = card.querySelector( '.sg-preview' );
|
||||
var frame = wrap && wrap.querySelector( 'iframe' );
|
||||
if ( frame && ! wrap.hidden ) { frame.src = url; }
|
||||
} );
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
window.clearTimeout( timer );
|
||||
timer = window.setTimeout( refresh, 250 );
|
||||
}
|
||||
|
||||
form.addEventListener( 'input', schedule );
|
||||
form.addEventListener( 'change', schedule );
|
||||
|
||||
cards.forEach( function ( card ) {
|
||||
var btn = card.querySelector( '[data-sg-preview]' );
|
||||
if ( ! btn ) { return; }
|
||||
btn.addEventListener( 'click', function () {
|
||||
var wrap = card.querySelector( '.sg-preview' );
|
||||
var frame = wrap.querySelector( 'iframe' );
|
||||
if ( wrap.hidden ) {
|
||||
wrap.hidden = false;
|
||||
frame.src = previewSrc( card );
|
||||
btn.textContent = 'Hide preview';
|
||||
} else {
|
||||
wrap.hidden = true;
|
||||
frame.removeAttribute( 'src' );
|
||||
btn.textContent = 'Show live preview';
|
||||
}
|
||||
} );
|
||||
} );
|
||||
refresh();
|
||||
}() );
|
||||
@@ -0,0 +1,125 @@
|
||||
/* StreamGoals rules editor: show the right fields per type and preview what a donation would do. */
|
||||
( function () {
|
||||
'use strict';
|
||||
var dataEl = document.getElementById( 'sg-rules-data' );
|
||||
var form = document.querySelector( '.sg-rule-form' );
|
||||
var cfg = { currency: 'USD', exp: 2, rules: [] };
|
||||
try { if ( dataEl ) { cfg = JSON.parse( dataEl.textContent ); } } catch ( e ) { /* keep defaults */ }
|
||||
|
||||
/* Parse "1,000.50" into minor units using string maths only (no float rounding). Returns null if invalid. */
|
||||
function toMinor( raw ) {
|
||||
var s = String( raw == null ? '' : raw ).replace( /[,\s$€£¥]/g, '' );
|
||||
var m = /^(\d+)(?:\.(\d+))?$/.exec( s );
|
||||
if ( ! m ) { return null; }
|
||||
var frac = m[ 2 ] || '';
|
||||
if ( frac.length > cfg.exp ) { return null; }
|
||||
while ( frac.length < cfg.exp ) { frac += '0'; }
|
||||
var n = parseInt( m[ 1 ] + frac, 10 );
|
||||
return isFinite( n ) ? n : null;
|
||||
}
|
||||
|
||||
function money( minor ) {
|
||||
var s = String( minor );
|
||||
if ( cfg.exp === 0 ) { return cfg.currency + ' ' + s; }
|
||||
while ( s.length < 3 ) { s = '0' + s; }
|
||||
return cfg.currency + ' ' + s.slice( 0, -2 ) + '.' + s.slice( -2 );
|
||||
}
|
||||
|
||||
function duration( secs ) {
|
||||
var parts = [];
|
||||
[ [ 'day', 86400 ], [ 'hour', 3600 ], [ 'minute', 60 ], [ 'second', 1 ] ].forEach( function ( u ) {
|
||||
var n = Math.floor( secs / u[ 1 ] );
|
||||
secs -= n * u[ 1 ];
|
||||
if ( n > 0 ) { parts.push( n + ' ' + u[ 0 ] + ( n === 1 ? '' : 's' ) ); }
|
||||
} );
|
||||
return parts.length ? parts.join( ' ' ) : '0 seconds';
|
||||
}
|
||||
|
||||
/* Same maths as the PHP Rules classes (integer division, caps). */
|
||||
function effect( rule, amount ) {
|
||||
var c = rule.config || {};
|
||||
if ( rule.type === 'add_time' ) {
|
||||
if ( ! c.unit_minor ) { return null; }
|
||||
var d = Math.floor( amount * c.seconds_per_unit / c.unit_minor );
|
||||
if ( c.cap_seconds_per_donation != null ) { d = Math.min( d, c.cap_seconds_per_donation ); }
|
||||
var note = c.max_timer_seconds != null ? ' (the timer never goes above ' + duration( c.max_timer_seconds ) + ')' : '';
|
||||
return ( d > 0 ? 'Timer: +' + duration( d ) : 'Timer: no time added' ) + note;
|
||||
}
|
||||
if ( rule.type === 'counter' ) {
|
||||
if ( ! c.per_minor ) { return null; }
|
||||
return ( c.label || 'Counter' ) + ': +' + ( Math.floor( amount / c.per_minor ) * c.step );
|
||||
}
|
||||
if ( rule.type === 'bonus' ) {
|
||||
return 'Bonus "' + c.event + '" ' + ( amount >= c.min_minor ? 'triggers' : 'does not trigger' );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
var amountEl = document.getElementById( 'sg-preview-amount' );
|
||||
var out = document.getElementById( 'sg-preview-out' );
|
||||
function renderPreview() {
|
||||
if ( ! amountEl || ! out ) { return; }
|
||||
var amt = toMinor( amountEl.value );
|
||||
out.textContent = '';
|
||||
var lines = [];
|
||||
if ( amt === null ) {
|
||||
lines.push( 'Enter an amount like 25.00' );
|
||||
} else {
|
||||
lines.push( 'A ' + money( amt ) + ' donation:' );
|
||||
cfg.rules.forEach( function ( r ) { var l = effect( r, amt ); if ( l ) { lines.push( l ); } } );
|
||||
if ( ! cfg.rules.length ) { lines.push( 'No rules are on, so it only fills the goal bar.' ); }
|
||||
}
|
||||
lines.forEach( function ( l ) { var li = document.createElement( 'li' ); li.textContent = l; out.appendChild( li ); } );
|
||||
}
|
||||
if ( amountEl ) { amountEl.addEventListener( 'input', renderPreview ); renderPreview(); }
|
||||
|
||||
/* Type switch + preview of the rule being edited. */
|
||||
if ( ! form ) { return; }
|
||||
|
||||
var typeSel = document.getElementById( 'sg-rule-type' );
|
||||
var typeHidden = form.querySelector( 'input[name="type"]' );
|
||||
var formPrev = document.getElementById( 'sg-form-preview' );
|
||||
|
||||
function currentType() { return typeSel ? typeSel.value : ( typeHidden ? typeHidden.value : 'add_time' ); }
|
||||
function val( group, f ) {
|
||||
var el = group.querySelector( '[data-f="' + f + '"]' );
|
||||
if ( ! el ) { return ''; }
|
||||
return el.type === 'checkbox' ? el.checked : el.value;
|
||||
}
|
||||
function buildRule( type ) {
|
||||
var g = form.querySelector( '.sg-rule-group[data-type="' + type + '"]' );
|
||||
if ( ! g ) { return null; }
|
||||
var unit = toMinor( val( g, 'unit_amount' ) );
|
||||
if ( type === 'add_time' ) {
|
||||
var mult = { seconds: 1, minutes: 60, hours: 3600 }[ val( g, 'time_unit' ) ] || 60;
|
||||
var n = parseInt( val( g, 'time_amount' ), 10 );
|
||||
if ( ! unit || ! n ) { return null; }
|
||||
var cap = parseInt( val( g, 'cap_minutes' ), 10 );
|
||||
var clock = parseInt( val( g, 'max_timer_minutes' ), 10 );
|
||||
return { type: type, config: { seconds_per_unit: n * mult, unit_minor: unit, cap_seconds_per_donation: cap > 0 ? cap * 60 : null, max_timer_seconds: clock > 0 ? clock * 60 : null } };
|
||||
}
|
||||
if ( type === 'counter' ) {
|
||||
var step = parseInt( val( g, 'step' ), 10 );
|
||||
if ( ! unit || ! step ) { return null; }
|
||||
return { type: type, config: { step: step, per_minor: unit, label: val( g, 'label' ) } };
|
||||
}
|
||||
var min = toMinor( val( g, 'min_amount' ) );
|
||||
if ( ! min ) { return null; }
|
||||
return { type: type, config: { min_minor: min, event: val( g, 'event' ) || 'big_donation' } };
|
||||
}
|
||||
function update() {
|
||||
var type = currentType();
|
||||
Array.prototype.forEach.call( form.querySelectorAll( '.sg-rule-group' ), function ( g ) {
|
||||
g.hidden = g.getAttribute( 'data-type' ) !== type;
|
||||
} );
|
||||
if ( ! formPrev ) { return; }
|
||||
var amt = amountEl ? toMinor( amountEl.value ) : null;
|
||||
var rule = buildRule( type );
|
||||
var line = ( rule && amt !== null ) ? effect( rule, amt ) : null;
|
||||
formPrev.textContent = line ? 'With this rule, a ' + money( amt ) + ' donation gives: ' + line : '';
|
||||
}
|
||||
form.addEventListener( 'input', update );
|
||||
form.addEventListener( 'change', update );
|
||||
if ( amountEl ) { amountEl.addEventListener( 'input', update ); }
|
||||
update();
|
||||
}() );
|
||||
@@ -11,3 +11,9 @@
|
||||
.sg-donate .sg-msg.sg-error{color:#b32d2e}
|
||||
.sg-donate .sg-msg.sg-ok{color:#1a7f37}
|
||||
.sg-donate .sg-buttons[data-disabled=true]{opacity:.45;pointer-events:none}
|
||||
.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: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}
|
||||
+31
-8
@@ -41,7 +41,8 @@
|
||||
var s = document.createElement('script');
|
||||
s.id = 'sg-paypal-sdk';
|
||||
s.src = 'https://www.paypal.com/sdk/js?client-id=' + encodeURIComponent(C.clientId) +
|
||||
'¤cy=' + encodeURIComponent(currency) + '&intent=capture&components=buttons';
|
||||
'¤cy=' + encodeURIComponent(currency) + '&intent=capture&components=buttons' +
|
||||
((C.disableFunding && C.disableFunding.length) ? '&disable-funding=' + encodeURIComponent(C.disableFunding.join(',')) : '');
|
||||
s.onload = function () { window.paypal ? resolve(window.paypal) : reject(new Error(T.sdkError)); };
|
||||
s.onerror = function () { reject(new Error(T.sdkError)); };
|
||||
document.head.appendChild(s);
|
||||
@@ -54,10 +55,12 @@
|
||||
try { return new Intl.NumberFormat(undefined, { style: 'currency', currency: cur }).format(v); }
|
||||
catch (e) { return v.toFixed(exp) + ' ' + cur; }
|
||||
}
|
||||
// Preset buttons, minus any below the minimum donation (values are whole currency units, or minor units for zero-decimal).
|
||||
function presets(exp) {
|
||||
var base = exp === 0 ? [500, 1000, 2500, 5000] : [5, 10, 25, 50];
|
||||
return base;
|
||||
return base.filter(function (p) { return (exp === 0 ? p : p * 100) >= (C.minMinor || 0); });
|
||||
}
|
||||
function sprintf1(tpl, v) { return String(tpl || '%s').replace('%s', v); }
|
||||
|
||||
function init(root) {
|
||||
var pinned = parseInt(root.getAttribute('data-goal'), 10) || 0;
|
||||
@@ -68,7 +71,8 @@
|
||||
|
||||
var goalSel = el('select', { id: uid + '-goal' });
|
||||
goals.forEach(function (g) { goalSel.appendChild(el('option', { value: g.id, text: g.title + ' (' + g.currency + ')' })); });
|
||||
var amount = el('input', { type: 'text', inputmode: 'decimal', id: uid + '-amt', autocomplete: 'off', 'aria-describedby': uid + '-total' });
|
||||
var amount = el('input', { type: 'text', inputmode: 'decimal', id: uid + '-amt', autocomplete: 'off', placeholder: T.customPlaceholder || 'Other amount', 'aria-describedby': uid + '-hint ' + uid + '-total' });
|
||||
var hint = el('div', { 'class': 'sg-hint', id: uid + '-hint' });
|
||||
var presetBox = el('div', { 'class': 'sg-presets' });
|
||||
var name = el('input', { type: 'text', id: uid + '-name', maxlength: '100', autocomplete: 'nickname' });
|
||||
var anon = el('input', { type: 'checkbox', id: uid + '-anon' });
|
||||
@@ -79,7 +83,7 @@
|
||||
var buttons = el('div', { 'class': 'sg-buttons' });
|
||||
|
||||
if (goals.length > 1) { root.appendChild(row([el('label', { 'for': uid + '-goal', text: T.goal }), goalSel])); }
|
||||
root.appendChild(row([el('label', { 'for': uid + '-amt', text: T.amount }), presetBox, amount]));
|
||||
root.appendChild(row([el('label', { text: T.amount }), presetBox, el('label', { 'class': 'sg-sub', 'for': uid + '-amt', text: T.customAmount || 'Or enter your own amount' }), amount, hint]));
|
||||
var nameRow = row([el('label', { 'for': uid + '-name', text: T.name }), name]);
|
||||
var anonRow = row([el('label', { 'class': 'sg-inline', 'for': uid + '-anon' }, [anon, document.createTextNode(T.anonymous)])]);
|
||||
if (C.policy === 'force_anonymous') { anon.checked = true; anon.disabled = true; nameRow.hidden = true; }
|
||||
@@ -87,10 +91,24 @@
|
||||
root.appendChild(nameRow);
|
||||
root.appendChild(anonRow);
|
||||
root.appendChild(row([el('label', { 'for': uid + '-msg', text: T.message }), msg]));
|
||||
root.appendChild(row([el('label', { 'class': 'sg-inline', 'for': uid + '-cover' }, [cover, document.createTextNode(T.coverFees)])]));
|
||||
var tip = el('div', { 'class': 'sg-tip', id: uid + '-tip', role: 'note', text: T.coverInfo || '' });
|
||||
tip.hidden = true;
|
||||
var info = el('button', { type: 'button', 'class': 'sg-info', 'aria-label': T.coverInfoLabel || 'What does this mean?', 'aria-expanded': 'false', 'aria-controls': uid + '-tip', text: 'i' });
|
||||
var pinnedOpen = false;
|
||||
function showTip(open) { tip.hidden = !open; info.setAttribute('aria-expanded', String(open)); }
|
||||
// Click toggles a "pinned" state independent of hover (a tap fires hover first, so reading tip.hidden would undo itself).
|
||||
info.addEventListener('click', function () { pinnedOpen = !pinnedOpen; showTip(pinnedOpen); });
|
||||
info.addEventListener('mouseenter', function () { showTip(true); });
|
||||
info.addEventListener('mouseleave', function () { if (!pinnedOpen) { showTip(false); } });
|
||||
info.addEventListener('blur', function () { pinnedOpen = false; showTip(false); });
|
||||
info.addEventListener('keydown', function (e) { if (e.key === 'Escape') { pinnedOpen = false; showTip(false); } });
|
||||
root.appendChild(row([
|
||||
el('div', { 'class': 'sg-cover' }, [el('label', { 'class': 'sg-inline', 'for': uid + '-cover' }, [cover, document.createTextNode(T.coverFees)]), info]),
|
||||
tip
|
||||
]));
|
||||
root.appendChild(row([total]));
|
||||
root.appendChild(status); // messages sit above the PayPal buttons, next to the form fields
|
||||
root.appendChild(buttons);
|
||||
root.appendChild(status);
|
||||
|
||||
function say(text, cls) { status.textContent = text || ''; status.className = 'sg-msg' + (cls ? ' ' + cls : ''); }
|
||||
function amountStr() { return amount.value.trim().replace(',', '.'); }
|
||||
@@ -99,6 +117,7 @@
|
||||
|
||||
function buildPresets() {
|
||||
presetBox.textContent = '';
|
||||
hint.textContent = sprintf1(T.minHint, fmt(C.minMinor || 0, state.goal.exp, state.goal.currency));
|
||||
presets(state.goal.exp).forEach(function (p) {
|
||||
var b = el('button', { type: 'button', 'aria-pressed': 'false', text: fmt(state.goal.exp === 0 ? p : p * 100, state.goal.exp, state.goal.currency) });
|
||||
b.addEventListener('click', function () { amount.value = String(p); refresh(); });
|
||||
@@ -119,7 +138,11 @@
|
||||
state.quote = null;
|
||||
buttons.setAttribute('data-disabled', 'true');
|
||||
clearTimeout(timer);
|
||||
if (!amountStr()) { total.textContent = ''; return; }
|
||||
if (!amountStr()) { total.textContent = ''; say(''); return; }
|
||||
var typed = parseFloat(amountStr());
|
||||
if (isFinite(typed) && Math.round(typed * Math.pow(10, state.goal.exp)) < (C.minMinor || 0)) {
|
||||
total.textContent = ''; say(sprintf1(T.belowMin, fmt(C.minMinor, state.goal.exp, state.goal.currency)), 'sg-error'); return;
|
||||
}
|
||||
var mine = ++seq;
|
||||
timer = setTimeout(function () {
|
||||
var qs = 'goal_id=' + state.goal.id + '&amount=' + encodeURIComponent(amountStr()) + '&cover_fees=' + (cover.checked ? '1' : '0');
|
||||
@@ -149,7 +172,7 @@
|
||||
if (token !== state.renderToken) { return; }
|
||||
paypal.Buttons({
|
||||
onClick: function (d, actions) {
|
||||
if (!state.quote || (C.policy === 'require_name' && !name.value.trim())) { say(T.fixForm, 'sg-error'); return actions.reject(); }
|
||||
if (!state.quote || (C.policy === 'require_name' && !name.value.trim())) { if (!status.textContent) { say(T.fixForm, 'sg-error'); } return actions.reject(); }
|
||||
say('');
|
||||
},
|
||||
createOrder: function () {
|
||||
|
||||
@@ -27,7 +27,12 @@ body.sg-offline #sg-root{opacity:.6}
|
||||
.sg-alert-head{font-weight:800;font-size:1.2em}
|
||||
.sg-alert-head b{color:var(--sg-accent2)}
|
||||
.sg-alert-msg{margin-top:.3em;font-size:.85em;overflow-wrap:anywhere;max-height:5.2em;overflow:hidden}
|
||||
.sg-alert.sg-bonus{border-width:.14em;animation:sg-in .6s cubic-bezier(.22,1,.36,1) both,sg-glow 1.4s ease-in-out .6s infinite}
|
||||
.sg-alert.sg-bonus.sg-out{animation:sg-out .5s ease-in both}
|
||||
.sg-bonus-line{margin-top:.3em;display:inline-block;padding:.1em .6em;border-radius:999px;font-weight:900;font-size:.95em;letter-spacing:.06em;text-transform:uppercase;color:#fff;background:linear-gradient(90deg,var(--sg-accent),var(--sg-accent2));text-shadow:0 1px 3px rgba(0,0,0,.6);box-shadow:0 0 0 .08em rgba(0,0,0,.45)}
|
||||
.sg-bonus-line+.sg-bonus-line{margin-left:.4em}
|
||||
@keyframes sg-glow{0%,100%{box-shadow:0 0 .4em var(--sg-accent),0 0 .9em var(--sg-accent2)}50%{box-shadow:0 0 .9em var(--sg-accent),0 0 1.9em var(--sg-accent2)}}
|
||||
@keyframes sg-in{from{opacity:0;transform:translateY(40%) scale(.9)}to{opacity:1;transform:none}}
|
||||
@keyframes sg-out{to{opacity:0;transform:translateY(-30%) scale(.95)}}
|
||||
@keyframes sg-blink{50%{opacity:.4}}
|
||||
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out{animation:none}}
|
||||
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out,.sg-alert.sg-bonus,.sg-alert.sg-bonus.sg-out{animation:none}.sg-alert.sg-bonus{box-shadow:0 0 .8em var(--sg-accent2)}}
|
||||
@@ -108,6 +108,13 @@
|
||||
head.appendChild(document.createTextNode(' donated '));
|
||||
head.appendChild(el('b', null, a.amount_display));
|
||||
card.appendChild(head);
|
||||
var bonuses = Array.isArray(a.bonuses) ? a.bonuses : [];
|
||||
if (bonuses.length) {
|
||||
card.classList.add('sg-bonus');
|
||||
for (var j = 0; j < bonuses.length; j++) {
|
||||
card.appendChild(el('div', 'sg-bonus-line', 'BONUS: ' + String(bonuses[j]) + '!'));
|
||||
}
|
||||
}
|
||||
if (a.message) card.appendChild(el('div', 'sg-alert-msg', a.message));
|
||||
root.appendChild(card);
|
||||
setTimeout(function () {
|
||||
|
||||
@@ -37,9 +37,9 @@ Rules engine entry point (Agent 2 implements, Agent 1 calls after a capture is r
|
||||
Rules\Engine::applyDonation(Donation $d): void; // idempotent via sg_rule_events UNIQUE
|
||||
Rules\Engine::reverseDonation(Donation $d): void; // honors per-rule "reverse on refund"
|
||||
```
|
||||
Rule `config` examples:
|
||||
Rule `config` examples (`max_total_seconds` caps what one rule has added over time; `max_timer_seconds` caps how long the timer can ever get, null = uncapped):
|
||||
```json
|
||||
{"type":"add_time","seconds_per_unit":60,"unit_minor":100,"cap_seconds_per_donation":null,"max_total_seconds":null,"basis":"base"}
|
||||
{"type":"add_time","seconds_per_unit":60,"unit_minor":100,"cap_seconds_per_donation":null,"max_total_seconds":null,"max_timer_seconds":null,"basis":"base"}
|
||||
{"type":"counter","step":1,"per_minor":1000,"carry_over":true,"basis":"base","label":"Pies"}
|
||||
{"type":"bonus","min_minor":5000,"event":"big_donation"}
|
||||
```
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/**
|
||||
* Admin bootstrap: one top-level "StreamGoals" menu, assets, shared helpers (nonce/capability guard,
|
||||
* flash notices). Every screen requires manage_options; every admin-post handler goes through guard().
|
||||
*/
|
||||
final class Admin {
|
||||
|
||||
public const CAP = 'manage_options';
|
||||
public const HOME = 'streamgoals';
|
||||
|
||||
/** admin-post action => [class, method]. */
|
||||
private const HANDLERS = array(
|
||||
'sg_paypal_connect' => array( PayPalConnector::class, 'handle' ),
|
||||
'sg_wizard_goal' => array( SetupPage::class, 'handleGoal' ),
|
||||
'sg_wizard_page' => array( SetupPage::class, 'handlePage' ),
|
||||
'sg_goal_save' => array( GoalsPage::class, 'handleSave' ),
|
||||
'sg_goal_status' => array( GoalsPage::class, 'handleStatus' ),
|
||||
'sg_goal_delete' => array( GoalsPage::class, 'handleDelete' ),
|
||||
'sg_rule_save' => array( GoalsPage::class, 'handleRuleSave' ),
|
||||
'sg_rule_toggle' => array( GoalsPage::class, 'handleRuleToggle' ),
|
||||
'sg_rule_delete' => array( GoalsPage::class, 'handleRuleDelete' ),
|
||||
'sg_export_csv' => array( DonationsPage::class, 'handleExport' ),
|
||||
'sg_moderate' => array( DonationsPage::class, 'handleModerate' ),
|
||||
'sg_test_donation' => array( OverlaysPage::class, 'handleTestDonation' ),
|
||||
'sg_delete_tests' => array( OverlaysPage::class, 'handleDeleteTests' ),
|
||||
'sg_regen_token' => array( OverlaysPage::class, 'handleRegenerate' ),
|
||||
'sg_settings_save' => array( SettingsPage::class, 'handleSave' ),
|
||||
);
|
||||
|
||||
public static function register(): void {
|
||||
add_action( 'admin_menu', array( self::class, 'menu' ) );
|
||||
add_action( 'admin_init', array( self::class, 'maybe_flush_rewrites' ) );
|
||||
add_action( 'admin_enqueue_scripts', array( self::class, 'assets' ) );
|
||||
foreach ( self::HANDLERS as $action => $cb ) {
|
||||
add_action( 'admin_post_' . $action, $cb );
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ menu */
|
||||
|
||||
public static function menu(): void {
|
||||
$connected = PayPalConnector::isConnected();
|
||||
add_menu_page( 'StreamGoals', 'StreamGoals', self::CAP, self::HOME, array( self::class, 'page_home' ), 'dashicons-heart', 58 );
|
||||
add_submenu_page( self::HOME, $connected ? 'Goals' : 'Setup', $connected ? 'Goals' : 'Setup', self::CAP, self::HOME, array( self::class, 'page_home' ) );
|
||||
if ( $connected ) {
|
||||
add_submenu_page( self::HOME, 'Setup guide', 'Setup guide', self::CAP, 'streamgoals-setup', array( SetupPage::class, 'render' ) );
|
||||
}
|
||||
add_submenu_page( self::HOME, 'Donations', 'Donations', self::CAP, 'streamgoals-donations', array( DonationsPage::class, 'render' ) );
|
||||
$pending = Store::pendingModerationCount();
|
||||
if ( Settings::get( 'moderate_messages' ) || $pending > 0 ) {
|
||||
$badge = $pending > 0 ? ' <span class="awaiting-mod">' . (int) $pending . '</span>' : '';
|
||||
add_submenu_page( self::HOME, 'Moderation', 'Moderation' . $badge, self::CAP, 'streamgoals-moderation', array( DonationsPage::class, 'renderModeration' ) );
|
||||
}
|
||||
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' ) );
|
||||
}
|
||||
|
||||
/** First screen: the setup wizard until PayPal is connected, then the goals list. */
|
||||
public static function page_home(): void {
|
||||
if ( PayPalConnector::isConnected() ) {
|
||||
GoalsPage::render();
|
||||
} else {
|
||||
SetupPage::render();
|
||||
}
|
||||
}
|
||||
|
||||
/** Overlay rewrite rules (registered by Overlay\Router on init) need a one-off flush. */
|
||||
public static function maybe_flush_rewrites(): void {
|
||||
if ( current_user_can( self::CAP ) && class_exists( \StreamGoals\Overlay\Router::class ) && \StreamGoals\Overlay\Router::flush_rules_needed() ) {
|
||||
flush_rewrite_rules( false );
|
||||
\StreamGoals\Overlay\Router::mark_flushed();
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- assets */
|
||||
|
||||
public static function assets( string $hook ): void {
|
||||
$page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
if ( 0 !== strpos( $page, 'streamgoals' ) ) {
|
||||
return;
|
||||
}
|
||||
wp_enqueue_style( 'streamgoals-admin', STREAMGOALS_URL . 'assets/admin/admin.css', array(), STREAMGOALS_VERSION );
|
||||
wp_enqueue_script( 'streamgoals-admin', STREAMGOALS_URL . 'assets/admin/admin.js', array(), STREAMGOALS_VERSION, true );
|
||||
if ( self::HOME === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-rules', STREAMGOALS_URL . 'assets/admin/rules.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
if ( 'streamgoals-overlays' === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-overlays', STREAMGOALS_URL . 'assets/admin/overlays.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- helpers */
|
||||
|
||||
/** Capability + nonce check for every admin-post handler. Dies on failure. */
|
||||
public static function guard( string $action ): void {
|
||||
if ( ! current_user_can( self::CAP ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to do that.', 'streamgoals-donate' ), 403 );
|
||||
}
|
||||
check_admin_referer( $action );
|
||||
}
|
||||
|
||||
/** Echo an opening <form> posting to admin-post.php with the nonce for $action. */
|
||||
public static function form( string $action, array $hidden = array(), string $class = '' ): void {
|
||||
echo '<form method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '"' . ( '' !== $class ? ' class="' . esc_attr( $class ) . '"' : '' ) . '>';
|
||||
echo '<input type="hidden" name="action" value="' . esc_attr( $action ) . '">';
|
||||
wp_nonce_field( $action );
|
||||
foreach ( $hidden as $k => $v ) {
|
||||
echo '<input type="hidden" name="' . esc_attr( (string) $k ) . '" value="' . esc_attr( (string) $v ) . '">';
|
||||
}
|
||||
}
|
||||
|
||||
public static function url( string $page = self::HOME, array $args = array() ): string {
|
||||
return add_query_arg( array_merge( array( 'page' => $page ), $args ), admin_url( 'admin.php' ) );
|
||||
}
|
||||
|
||||
/** Redirect back with a one-time notice shown on the next screen load. */
|
||||
public static function redirect( string $url, string $type, string $message ): void {
|
||||
set_transient( 'sg_notice_' . get_current_user_id(), array( 'type' => $type, 'msg' => $message ), 120 );
|
||||
wp_safe_redirect( $url );
|
||||
exit;
|
||||
}
|
||||
|
||||
public static function notices(): void {
|
||||
$key = 'sg_notice_' . get_current_user_id();
|
||||
$n = get_transient( $key );
|
||||
if ( is_array( $n ) && isset( $n['msg'] ) ) {
|
||||
delete_transient( $key );
|
||||
$cls = in_array( $n['type'] ?? '', array( 'success', 'error', 'warning', 'info' ), true ) ? $n['type'] : 'info';
|
||||
echo '<div class="notice notice-' . esc_attr( $cls ) . ' is-dismissible"><p>' . esc_html( (string) $n['msg'] ) . '</p></div>';
|
||||
}
|
||||
}
|
||||
|
||||
public static function currency(): string {
|
||||
return Format::currency( get_option( 'sg_currency', 'USD' ) );
|
||||
}
|
||||
|
||||
/** Start a screen: capability check, wrapper and flash notices. */
|
||||
public static function open( string $title ): void {
|
||||
if ( ! current_user_can( self::CAP ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to view this page.', 'streamgoals-donate' ), 403 );
|
||||
}
|
||||
echo '<div class="wrap sg-admin"><h1>' . esc_html( $title ) . '</h1>';
|
||||
self::notices();
|
||||
if ( PayPalConnector::isConnected() && '' === (string) Settings::get( 'paypal_webhook_id', '' ) ) {
|
||||
echo '<div class="notice notice-warning"><p>' . esc_html( 'PayPal is connected, but the webhook is not set up yet, so refunds/reversals will not be noticed. Open Settings and press "Save and test connection" to register it.' ) . '</p></div>';
|
||||
}
|
||||
}
|
||||
|
||||
public static function close(): void {
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
/** Safe int from $_GET. */
|
||||
public static function get_int( string $key ): int {
|
||||
return isset( $_GET[ $key ] ) ? absint( wp_unslash( $_GET[ $key ] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
}
|
||||
|
||||
public static function get_str( string $key ): string {
|
||||
return isset( $_GET[ $key ] ) && is_scalar( $_GET[ $key ] ) ? sanitize_key( wp_unslash( $_GET[ $key ] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
}
|
||||
|
||||
/** Safe string from $_POST (already nonce-checked by guard()). */
|
||||
public static function post_str( string $key, int $max = 200 ): string {
|
||||
return isset( $_POST[ $key ] ) && is_scalar( $_POST[ $key ] ) ? Input::text( wp_unslash( $_POST[ $key ] ), $max ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
}
|
||||
|
||||
public static function post_raw(): array {
|
||||
return is_array( $_POST ) ? wp_unslash( $_POST ) : array(); // phpcs:ignore WordPress.Security.NonceVerification
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
/** CSV helpers. Guards against spreadsheet formula injection (=, +, -, @, tab, CR prefixes). */
|
||||
final class Csv {
|
||||
|
||||
public static function cell( mixed $v ): string {
|
||||
$s = is_scalar( $v ) || null === $v ? (string) $v : '';
|
||||
if ( '' !== $s && str_contains( "=+-@\t\r", $s[0] ) ) {
|
||||
return "'" . $s;
|
||||
}
|
||||
return $s;
|
||||
}
|
||||
|
||||
/** @return string[] */
|
||||
public static function row( array $cells ): array {
|
||||
return array_map( array( self::class, 'cell' ), array_values( $cells ) );
|
||||
}
|
||||
|
||||
/** Render one RFC-4180 line (no WordPress needed; used for tests and streaming). */
|
||||
public static function line( array $cells ): string {
|
||||
$out = array();
|
||||
foreach ( self::row( $cells ) as $c ) {
|
||||
$out[] = '"' . str_replace( '"', '""', $c ) . '"';
|
||||
}
|
||||
return implode( ',', $out ) . "\r\n";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/** Donations table (search, filter, pagination), CSV export, and the message moderation queue. */
|
||||
final class DonationsPage {
|
||||
|
||||
private const PER_PAGE = 25;
|
||||
|
||||
private static function fmtDate( string $utc ): string {
|
||||
return get_date_from_gmt( $utc, 'Y-m-d H:i' );
|
||||
}
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'Donations' );
|
||||
$status = Admin::get_str( 'status' );
|
||||
$tests = 'hide' === Admin::get_str( 'tests' ) ? 'hide' : '';
|
||||
$search = isset( $_GET['s'] ) && is_scalar( $_GET['s'] ) ? Input::text( wp_unslash( $_GET['s'] ), 100 ) : ''; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
$page = max( 1, Admin::get_int( 'paged' ) );
|
||||
$res = Store::searchDonations( array( 'status' => $status, 'search' => $search, 'tests' => $tests ), $page, self::PER_PAGE );
|
||||
|
||||
echo '<form method="get" class="sg-filter"><input type="hidden" name="page" value="streamgoals-donations">';
|
||||
echo '<select name="status" aria-label="Status"><option value="">All statuses</option>';
|
||||
foreach ( array( 'completed', 'pending' ) as $s ) {
|
||||
echo '<option value="' . esc_attr( $s ) . '"' . selected( $status, $s, false ) . '>' . esc_html( ucfirst( $s ) ) . '</option>';
|
||||
}
|
||||
echo '</select> <label><input type="checkbox" name="tests" value="hide"' . checked( $tests, 'hide', false ) . '> Hide test donations</label> ';
|
||||
echo '<input type="search" name="s" value="' . esc_attr( $search ) . '" placeholder="Search name, message or PayPal ID"> <button class="button">Filter</button> ';
|
||||
echo '</form>';
|
||||
Admin::form( 'sg_export_csv', array(), 'sg-inline' );
|
||||
echo '<button class="button">Export CSV (all real donations)</button></form>';
|
||||
|
||||
echo '<p class="description">Donors who chose to be anonymous are shown as "Anonymous". Their name is never stored. Test donations are marked TEST and left out of the CSV and your totals.</p>';
|
||||
|
||||
if ( ! $res['rows'] ) {
|
||||
echo '<div class="sg-card"><p>No donations found.</p></div>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
$goals = array();
|
||||
foreach ( Store::goals()->all() as $g ) {
|
||||
$goals[ (int) $g['id'] ] = (string) $g['title'];
|
||||
}
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Date</th><th>Donor</th><th>Amount</th><th>Fee</th><th>Total paid</th><th>Goal</th><th>Status</th><th>Message</th></tr></thead><tbody>';
|
||||
foreach ( $res['rows'] as $r ) {
|
||||
$cur = Format::currency( $r['currency'] );
|
||||
$test = Format::isTest( $r );
|
||||
echo '<tr><td>' . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '</td>';
|
||||
echo '<td>' . esc_html( Format::donorName( $r ) ) . ( $test ? ' <span class="sg-badge sg-test">TEST</span>' : '' ) . '</td>';
|
||||
echo '<td>' . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td><td>' . esc_html( Format::money( (int) $r['fee_minor'], $cur ) ) . '</td><td>' . esc_html( Format::money( (int) $r['total_minor'], $cur ) ) . '</td>';
|
||||
echo '<td>' . esc_html( $test ? '(test)' : ( $goals[ (int) $r['goal_id'] ] ?? '#' . (int) $r['goal_id'] ) ) . '</td>';
|
||||
echo '<td>' . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' <span class="sg-badge sg-' . esc_attr( (string) $r['moderation'] ) . '">message ' . esc_html( (string) $r['moderation'] ) . '</span>' ) . '</td>';
|
||||
echo '<td>' . esc_html( (string) $r['message'] ) . '</td></tr>';
|
||||
}
|
||||
echo '</tbody></table>';
|
||||
$pages = (int) ceil( $res['total'] / self::PER_PAGE );
|
||||
if ( $pages > 1 ) {
|
||||
echo '<div class="tablenav"><div class="tablenav-pages">' . wp_kses_post( (string) paginate_links( array(
|
||||
'base' => add_query_arg( 'paged', '%#%' ),
|
||||
'format' => '',
|
||||
'current' => $page,
|
||||
'total' => $pages,
|
||||
'prev_text' => '«',
|
||||
'next_text' => '»',
|
||||
) ) ) . '</div></div>';
|
||||
}
|
||||
echo '<p class="description">' . (int) $res['total'] . ' donation(s).</p>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
public static function renderModeration(): void {
|
||||
Admin::open( 'Message moderation' );
|
||||
if ( ! Settings::get( 'moderate_messages' ) ) {
|
||||
echo '<div class="notice notice-info inline"><p>Message moderation is currently off in Settings, so new messages are shown without review. Anything still waiting below was submitted while it was on.</p></div>';
|
||||
}
|
||||
echo '<p class="description">Approved messages can appear in alerts. Rejected messages are hidden. The donation itself still counts towards your goal either way.</p>';
|
||||
$res = Store::searchDonations( array( 'status' => 'completed', 'moderation' => 'pending' ), 1, 100 );
|
||||
if ( ! $res['rows'] ) {
|
||||
echo '<div class="sg-card"><p>Nothing waiting for review.</p></div>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Date</th><th>Donor</th><th>Amount</th><th>Message</th><th>Decision</th></tr></thead><tbody>';
|
||||
foreach ( $res['rows'] as $r ) {
|
||||
$cur = Format::currency( $r['currency'] );
|
||||
echo '<tr><td>' . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '</td><td>' . esc_html( Format::donorName( $r ) ) . '</td>';
|
||||
echo '<td>' . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td><td>' . esc_html( (string) $r['message'] ) . '</td><td class="sg-actions">';
|
||||
foreach ( array( 'approved' => 'Approve', 'rejected' => 'Reject' ) as $to => $lbl ) {
|
||||
Admin::form( 'sg_moderate', array( 'donation_id' => (int) $r['id'], 'decision' => $to ), 'sg-inline' );
|
||||
echo '<button class="button' . ( 'approved' === $to ? ' button-primary' : '' ) . '">' . esc_html( $lbl ) . '</button></form> ';
|
||||
}
|
||||
echo '</td></tr>';
|
||||
}
|
||||
echo '</tbody></table>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
public static function handleModerate(): void {
|
||||
Admin::guard( 'sg_moderate' );
|
||||
$post = Admin::post_raw();
|
||||
$id = isset( $post['donation_id'] ) ? absint( $post['donation_id'] ) : 0;
|
||||
$to = isset( $post['decision'] ) && is_string( $post['decision'] ) ? $post['decision'] : '';
|
||||
$ok = $id && Store::setModeration( $id, $to );
|
||||
Admin::redirect( Admin::url( 'streamgoals-moderation' ), $ok ? 'success' : 'error', $ok ? ( 'approved' === $to ? 'Message approved.' : 'Message rejected.' ) : 'That message could not be updated (it may already be reviewed).' );
|
||||
}
|
||||
|
||||
public static function handleExport(): void {
|
||||
Admin::guard( 'sg_export_csv' );
|
||||
$goals = array();
|
||||
foreach ( Store::goals()->all() as $g ) {
|
||||
$goals[ (int) $g['id'] ] = (string) $g['title'];
|
||||
}
|
||||
nocache_headers();
|
||||
header( 'Content-Type: text/csv; charset=utf-8' );
|
||||
header( 'Content-Disposition: attachment; filename="streamgoals-donations-' . gmdate( 'Y-m-d' ) . '.csv"' );
|
||||
header( 'X-Content-Type-Options: nosniff' );
|
||||
echo "\xEF\xBB\xBF"; // UTF-8 BOM so Excel reads accents correctly
|
||||
echo Csv::line( array( 'ID', 'Date (UTC)', 'Goal', 'Donor', 'Amount', 'Fee covered', 'Total paid', 'Currency', 'Status', 'Message status', 'Message', 'PayPal order', 'PayPal capture' ) ); // phpcs:ignore WordPress.Security.EscapeOutput -- CSV, not HTML
|
||||
$after = 0;
|
||||
do {
|
||||
$rows = Store::exportBatch( $after, 500 );
|
||||
foreach ( $rows as $r ) {
|
||||
$after = (int) $r['id'];
|
||||
$cur = Format::currency( $r['currency'] );
|
||||
echo Csv::line( array( // phpcs:ignore WordPress.Security.EscapeOutput
|
||||
$r['id'],
|
||||
$r['created_at'],
|
||||
$goals[ (int) $r['goal_id'] ] ?? '',
|
||||
Format::donorName( $r ),
|
||||
Format::decimal( (int) $r['base_minor'], $cur ),
|
||||
Format::decimal( (int) $r['fee_minor'], $cur ),
|
||||
Format::decimal( (int) $r['total_minor'], $cur ),
|
||||
$cur,
|
||||
$r['status'],
|
||||
$r['moderation'],
|
||||
$r['message'],
|
||||
$r['paypal_order_id'],
|
||||
$r['paypal_capture_id'],
|
||||
) );
|
||||
}
|
||||
} while ( count( $rows ) === 500 );
|
||||
exit;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
|
||||
/** Pure display helpers. */
|
||||
final class Format {
|
||||
|
||||
/** Test donations are inserted with goal_id 0 and a paypal_order_id starting with this prefix. */
|
||||
public const TEST_PREFIX = 'TEST-';
|
||||
|
||||
/** PayPal-supported currencies (subset). */
|
||||
public const CURRENCIES = array(
|
||||
'USD' => 'US Dollar', 'EUR' => 'Euro', 'GBP' => 'British Pound', 'CAD' => 'Canadian Dollar', 'AUD' => 'Australian Dollar',
|
||||
'NZD' => 'New Zealand Dollar', 'CHF' => 'Swiss Franc', 'SEK' => 'Swedish Krona', 'NOK' => 'Norwegian Krone', 'DKK' => 'Danish Krone',
|
||||
'PLN' => 'Polish Zloty', 'CZK' => 'Czech Koruna', 'HUF' => 'Hungarian Forint', 'JPY' => 'Japanese Yen', 'SGD' => 'Singapore Dollar',
|
||||
'HKD' => 'Hong Kong Dollar', 'MXN' => 'Mexican Peso', 'BRL' => 'Brazilian Real', 'PHP' => 'Philippine Peso', 'TWD' => 'New Taiwan Dollar',
|
||||
'THB' => 'Thai Baht', 'ILS' => 'Israeli Shekel', 'MYR' => 'Malaysian Ringgit', 'CNY' => 'Chinese Yuan',
|
||||
);
|
||||
|
||||
public static function currency( mixed $c ): string {
|
||||
$c = is_string( $c ) ? strtoupper( trim( $c ) ) : '';
|
||||
return isset( self::CURRENCIES[ $c ] ) ? $c : 'USD';
|
||||
}
|
||||
|
||||
public static function money( int $minor, string $currency ): string {
|
||||
return Payloads::money( $minor, $currency );
|
||||
}
|
||||
|
||||
/** Plain decimal for form inputs, e.g. 1050 USD -> "10.50". */
|
||||
public static function decimal( int $minor, string $currency ): string {
|
||||
return ( new \StreamGoals\Core\Money( max( 0, $minor ), $currency ) )->toDecimalString();
|
||||
}
|
||||
|
||||
public static function duration( int $seconds ): string {
|
||||
$seconds = max( 0, $seconds );
|
||||
if ( 0 === $seconds ) {
|
||||
return '0 seconds';
|
||||
}
|
||||
$parts = array();
|
||||
foreach ( array( 'day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1 ) as $name => $size ) {
|
||||
$n = intdiv( $seconds, $size );
|
||||
$seconds %= $size;
|
||||
if ( $n > 0 ) {
|
||||
$parts[] = $n . ' ' . $name . ( 1 === $n ? '' : 's' );
|
||||
}
|
||||
}
|
||||
return implode( ' ', $parts );
|
||||
}
|
||||
|
||||
public static function isTest( array $row ): bool {
|
||||
return str_starts_with( (string) ( $row['paypal_order_id'] ?? '' ), self::TEST_PREFIX );
|
||||
}
|
||||
|
||||
/** The real name is shown only for non-anonymous donors. Anonymous names are not stored at all. */
|
||||
public static function donorName( array $row ): string {
|
||||
if ( ! empty( $row['is_anonymous'] ) || '' === trim( (string) ( $row['donor_name'] ?? '' ) ) ) {
|
||||
return 'Anonymous';
|
||||
}
|
||||
return (string) $row['donor_name'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Money;
|
||||
|
||||
/** Goals list/create/edit/status/delete, plus the per-goal rules editor. */
|
||||
final class GoalsPage {
|
||||
|
||||
private const STATUSES = array( 'active' => 'Active', 'paused' => 'Paused', 'complete' => 'Complete' );
|
||||
|
||||
public static function render(): void {
|
||||
$view = Admin::get_str( 'view' );
|
||||
$id = Admin::get_int( 'goal' );
|
||||
if ( in_array( $view, array( 'new', 'edit' ), true ) ) {
|
||||
self::renderForm( 'edit' === $view ? $id : 0 );
|
||||
} elseif ( 'rules' === $view && $id ) {
|
||||
self::renderRules( $id );
|
||||
} else {
|
||||
self::renderList();
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ list */
|
||||
|
||||
private static function renderList(): void {
|
||||
Admin::open( 'Goals' );
|
||||
echo '<p><a class="page-title-action" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'new' ) ) ) . '">Add new goal</a></p>';
|
||||
echo '<p class="description">Overlays and the donation form use your newest <strong>active</strong> goal(s). Pause a goal to stop accepting donations; mark it complete when you are done. A goal that has donations cannot be deleted (complete it instead), so your records stay intact.</p>';
|
||||
$goals = Store::goals()->all();
|
||||
if ( ! $goals ) {
|
||||
echo '<div class="sg-card"><p>No goals yet. <a href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'new' ) ) ) . '">Create your first goal</a> or run the <a href="' . esc_url( SetupPage::url( 2 ) ) . '">setup guide</a>.</p></div>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Goal</th><th>Status</th><th>Raised</th><th>Dates</th><th>Actions</th></tr></thead><tbody>';
|
||||
foreach ( $goals as $g ) {
|
||||
$gid = (int) $g['id'];
|
||||
$cur = Format::currency( $g['currency'] );
|
||||
$raised = Store::goals()->raised_minor( $gid );
|
||||
$target = (int) $g['target_minor'];
|
||||
$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( 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> ';
|
||||
foreach ( array( 'active' => array( 'paused', 'Pause' ), 'paused' => array( 'active', 'Resume' ), 'complete' => array( 'active', 'Reopen' ) ) as $from => [ $to, $lbl ] ) {
|
||||
if ( $g['status'] === $from ) {
|
||||
Admin::form( 'sg_goal_status', array( 'goal_id' => $gid, 'status' => $to ), 'sg-inline' );
|
||||
echo '<button class="button">' . esc_html( $lbl ) . '</button></form> ';
|
||||
}
|
||||
}
|
||||
if ( 'complete' !== $g['status'] ) {
|
||||
Admin::form( 'sg_goal_status', array( 'goal_id' => $gid, 'status' => 'complete' ), 'sg-inline' );
|
||||
echo '<button class="button">Mark complete</button></form> ';
|
||||
}
|
||||
Admin::form( 'sg_goal_delete', array( 'goal_id' => $gid ), 'sg-inline sg-confirm' );
|
||||
echo '<button class="button button-link-delete" data-confirm="Delete this goal and its rules? This cannot be undone.">Delete</button></form>';
|
||||
echo '</td></tr>';
|
||||
}
|
||||
echo '</tbody></table>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
private static function dateLabel( ?string $utc, string $prefix ): string {
|
||||
return $utc ? $prefix . ': ' . get_date_from_gmt( $utc, 'Y-m-d H:i' ) : $prefix . ': no date';
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ form */
|
||||
|
||||
private static function renderForm( int $id ): void {
|
||||
$g = $id ? Store::goals()->find( $id ) : null;
|
||||
if ( $id && ! $g ) {
|
||||
Admin::open( 'Goal not found' );
|
||||
echo '<p><a href="' . esc_url( Admin::url() ) . '">Back to goals</a></p>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
$cur = $g ? Format::currency( $g['currency'] ) : Admin::currency();
|
||||
Admin::open( $g ? 'Edit goal' : 'New goal' );
|
||||
Admin::form( 'sg_goal_save', array( 'goal_id' => $id ) );
|
||||
echo '<table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sg_title">Title</label></th><td><input type="text" required maxlength="190" id="sg_title" name="title" class="regular-text" value="' . esc_attr( (string) ( $g['title'] ?? '' ) ) . '"></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" required inputmode="decimal" id="sg_target" name="target" class="small-text" value="' . esc_attr( $g ? Format::decimal( (int) $g['target_minor'], $cur ) : '' ) . '"></td></tr>';
|
||||
echo '<tr><th scope="row">Currency</th><td><strong>' . esc_html( $cur ) . '</strong> <span class="description">One currency is used across the whole site. Change it in <a href="' . esc_url( Admin::url( 'streamgoals-settings' ) ) . '">Settings</a> (applies to new goals only).</span></td></tr>';
|
||||
$fmt = static fn( ?string $utc ): string => $utc ? get_date_from_gmt( $utc, 'Y-m-d\TH:i' ) : '';
|
||||
echo '<tr><th scope="row"><label for="sg_start">Starts</label></th><td><input type="datetime-local" id="sg_start" name="starts_at" value="' . esc_attr( $fmt( $g['starts_at'] ?? null ) ) . '"> <span class="description">Optional. Your site time zone. Empty = starts immediately.</span></td></tr>';
|
||||
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 '</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();
|
||||
}
|
||||
|
||||
/** 'Y-m-d\TH:i' in the site time zone -> UTC 'Y-m-d H:i:s', or null when empty/invalid. */
|
||||
private static function toUtc( string $local ): ?string {
|
||||
if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/', $local ) ) {
|
||||
return null;
|
||||
}
|
||||
$utc = get_gmt_from_date( str_replace( 'T', ' ', $local ) . ':00' );
|
||||
return $utc ?: null;
|
||||
}
|
||||
|
||||
public static function handleSave(): void {
|
||||
Admin::guard( 'sg_goal_save' );
|
||||
$post = Admin::post_raw();
|
||||
$id = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
|
||||
$back = Admin::url( Admin::HOME, $id ? array( 'view' => 'edit', 'goal' => $id ) : array( 'view' => 'new' ) );
|
||||
$old = $id ? Store::goals()->find( $id ) : null;
|
||||
if ( $id && ! $old ) {
|
||||
Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' );
|
||||
}
|
||||
$cur = $old ? Format::currency( $old['currency'] ) : Admin::currency();
|
||||
$title = Input::text( $post['title'] ?? '', 190 );
|
||||
$tgt = Input::amountToMinor( $post['target'] ?? '', $cur );
|
||||
if ( '' === $title ) {
|
||||
Admin::redirect( $back, 'error', 'Please give the goal a title.' );
|
||||
}
|
||||
if ( null === $tgt || $tgt <= 0 ) {
|
||||
Admin::redirect( $back, 'error', 'Please enter a target greater than zero, for example 250.00.' );
|
||||
}
|
||||
$startRaw = Input::text( $post['starts_at'] ?? '', 20 );
|
||||
$endRaw = Input::text( $post['ends_at'] ?? '', 20 );
|
||||
$start = '' === $startRaw ? null : self::toUtc( $startRaw );
|
||||
$end = '' === $endRaw ? null : self::toUtc( $endRaw );
|
||||
if ( ( '' !== $startRaw && null === $start ) || ( '' !== $endRaw && null === $end ) ) {
|
||||
Admin::redirect( $back, 'error', 'That date is not valid.' );
|
||||
}
|
||||
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 );
|
||||
if ( $id ) {
|
||||
Store::goals()->update( $id, $data );
|
||||
} else {
|
||||
$data['currency'] = $cur;
|
||||
$data['status'] = 'active';
|
||||
$id = Store::goals()->create( $data );
|
||||
if ( $id <= 0 ) {
|
||||
Admin::redirect( $back, 'error', 'The goal could not be saved.' );
|
||||
}
|
||||
Admin::redirect( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $id ) ), 'success', 'Goal created. Add rules below if you want a timer or counter.' );
|
||||
}
|
||||
Admin::redirect( Admin::url(), 'success', 'Goal saved.' );
|
||||
}
|
||||
|
||||
public static function handleStatus(): void {
|
||||
Admin::guard( 'sg_goal_status' );
|
||||
$post = Admin::post_raw();
|
||||
$id = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
|
||||
$status = isset( $post['status'] ) && is_string( $post['status'] ) ? $post['status'] : '';
|
||||
if ( ! $id || ! isset( self::STATUSES[ $status ] ) || ! Store::goals()->find( $id ) ) {
|
||||
Admin::redirect( Admin::url(), 'error', 'Could not change that goal.' );
|
||||
}
|
||||
Store::goals()->update( $id, array( 'status' => $status ) );
|
||||
Admin::redirect( Admin::url(), 'success', 'Goal is now ' . strtolower( self::STATUSES[ $status ] ) . '.' );
|
||||
}
|
||||
|
||||
public static function handleDelete(): void {
|
||||
Admin::guard( 'sg_goal_delete' );
|
||||
$id = isset( $_POST['goal_id'] ) ? absint( wp_unslash( $_POST['goal_id'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification
|
||||
if ( ! $id || ! Store::goals()->find( $id ) ) {
|
||||
Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' );
|
||||
}
|
||||
if ( ! Store::deleteGoal( $id ) ) {
|
||||
Admin::redirect( Admin::url(), 'error', 'This goal has donations, so it cannot be deleted. Mark it complete instead.' );
|
||||
}
|
||||
Admin::redirect( Admin::url(), 'success', 'Goal deleted.' );
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- rules */
|
||||
|
||||
private static function renderRules( int $goalId ): void {
|
||||
$g = Store::goals()->find( $goalId );
|
||||
if ( ! $g ) {
|
||||
Admin::open( 'Goal not found' );
|
||||
echo '<p><a href="' . esc_url( Admin::url() ) . '">Back to goals</a></p>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
$cur = Format::currency( $g['currency'] );
|
||||
$rules = Store::rules( $goalId );
|
||||
Admin::open( 'Rules for "' . (string) $g['title'] . '"' );
|
||||
echo '<p><a href="' . esc_url( Admin::url() ) . '">← Back to goals</a></p>';
|
||||
echo '<p class="sg-lead">Rules decide what each donation does besides filling the progress bar: add time to a subathon timer, bump a counter, or fire a bonus alert.</p>';
|
||||
|
||||
$editId = Admin::get_int( 'rule' );
|
||||
$editRule = $editId ? Store::rule( $editId, $goalId ) : null;
|
||||
|
||||
echo '<div class="sg-card"><h2>Current rules</h2>';
|
||||
if ( ! $rules ) {
|
||||
echo '<p>No rules yet. The goal bar works without any rules.</p>';
|
||||
} else {
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Rule</th><th>What it does</th><th>Actions</th></tr></thead><tbody>';
|
||||
foreach ( $rules as $r ) {
|
||||
$rid = (int) $r['id'];
|
||||
echo '<tr class="' . ( $r['enabled'] ? '' : 'sg-off' ) . '"><td>' . esc_html( RuleConfig::TYPES[ $r['type'] ] ?? (string) $r['type'] ) . ( $r['enabled'] ? '' : ' <em>(off)</em>' ) . '</td>';
|
||||
try {
|
||||
$summary = RuleConfig::summary( (string) $r['type'], $r['config'], $cur );
|
||||
} catch ( \Throwable $e ) {
|
||||
// One unreadable rule must not take down the whole screen; say what is wrong so it can be fixed or deleted.
|
||||
$summary = 'Could not read this rule (' . $e->getMessage() . '). You can delete it and add it again.';
|
||||
}
|
||||
echo '<td>' . esc_html( $summary ) . '</td><td class="sg-actions">';
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId, 'rule' => $rid ) ) ) . '#sg-rule-form">Edit</a> ';
|
||||
Admin::form( 'sg_rule_toggle', array( 'goal_id' => $goalId, 'rule_id' => $rid, 'enabled' => $r['enabled'] ? 0 : 1 ), 'sg-inline' );
|
||||
echo '<button class="button">' . ( $r['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
|
||||
Admin::form( 'sg_rule_delete', array( 'goal_id' => $goalId, 'rule_id' => $rid ), 'sg-inline sg-confirm' );
|
||||
echo '<button class="button button-link-delete" data-confirm="Delete this rule?">Delete</button></form></td></tr>';
|
||||
}
|
||||
echo '</tbody></table>';
|
||||
}
|
||||
echo '</div>';
|
||||
|
||||
// Live preview of saved, enabled rules.
|
||||
$data = array(
|
||||
'currency' => $cur,
|
||||
'exp' => Money::exponent( $cur ),
|
||||
'rules' => array_values( array_map( static fn( $r ) => array( 'type' => $r['type'], 'config' => $r['config'] ), array_filter( $rules, static fn( $r ) => (bool) $r['enabled'] ) ) ),
|
||||
);
|
||||
echo '<div class="sg-card"><h2>What would a donation do?</h2><label>Donation amount (' . esc_html( $cur ) . ') <input type="text" id="sg-preview-amount" class="small-text" inputmode="decimal" value="' . esc_attr( 0 === $data['exp'] ? '2500' : '25.00' ) . '"></label>';
|
||||
echo '<ul id="sg-preview-out" class="sg-preview-list" aria-live="polite"></ul>';
|
||||
echo '<p class="description">Based on your enabled rules, for a single donation on its own. Carry-over from earlier donations and total limits are not included.</p>';
|
||||
echo '<script type="application/json" id="sg-rules-data">' . wp_json_encode( $data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . '</script></div>';
|
||||
|
||||
self::renderRuleForm( $goalId, $cur, $editRule );
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
private static function renderRuleForm( int $goalId, string $cur, ?array $edit ): void {
|
||||
$type = $edit ? (string) $edit['type'] : 'add_time';
|
||||
$vals = $edit ? RuleConfig::toForm( $type, $edit['config'], $cur ) : array();
|
||||
$v = static fn( string $t, string $k, string $d = '' ): string => esc_attr( (string) ( $type === $t && isset( $vals[ $k ] ) ? $vals[ $k ] : $d ) );
|
||||
$basisOpts = static function ( string $t ) use ( $type, $vals ): string {
|
||||
$cur = $type === $t ? ( $vals['basis'] ?? 'base' ) : 'base';
|
||||
return '<select name="rule[' . $t . '][basis]"><option value="base"' . selected( $cur, 'base', false ) . '>The amount the donor chose (recommended)</option><option value="total"' . selected( $cur, 'total', false ) . '>The amount including covered fees</option></select>';
|
||||
};
|
||||
echo '<div class="sg-card" id="sg-rule-form"><h2>' . ( $edit ? 'Edit rule' : 'Add a rule' ) . '</h2>';
|
||||
Admin::form( 'sg_rule_save', array( 'goal_id' => $goalId, 'rule_id' => $edit ? (int) $edit['id'] : 0 ), 'sg-rule-form' );
|
||||
if ( $edit ) {
|
||||
echo '<input type="hidden" name="type" value="' . esc_attr( $type ) . '"><p><strong>' . esc_html( RuleConfig::TYPES[ $type ] ?? $type ) . '</strong></p>';
|
||||
} else {
|
||||
echo '<p><label>Type <select name="type" id="sg-rule-type">';
|
||||
foreach ( RuleConfig::TYPES as $k => $l ) {
|
||||
echo '<option value="' . esc_attr( $k ) . '">' . esc_html( $l ) . '</option>';
|
||||
}
|
||||
echo '</select></label></p>';
|
||||
}
|
||||
// add_time
|
||||
echo '<div class="sg-rule-group" data-type="add_time"' . ( 'add_time' === $type ? '' : ' hidden' ) . '><p>Add <input type="number" min="1" name="rule[add_time][time_amount]" class="small-text" data-f="time_amount" value="' . $v( 'add_time', 'time_amount', '1' ) . '">';
|
||||
echo ' <select name="rule[add_time][time_unit]" data-f="time_unit">';
|
||||
foreach ( array( 'seconds', 'minutes', 'hours' ) as $u ) {
|
||||
echo '<option value="' . esc_attr( $u ) . '"' . selected( 'add_time' === $type ? ( $vals['time_unit'] ?? 'minutes' ) : 'minutes', $u, false ) . '>' . esc_html( $u ) . '</option>';
|
||||
}
|
||||
echo '</select> to the timer for every ' . esc_html( $cur ) . ' <input type="text" inputmode="decimal" name="rule[add_time][unit_amount]" class="small-text" data-f="unit_amount" value="' . $v( 'add_time', 'unit_amount', 0 === Money::exponent( $cur ) ? '100' : '1.00' ) . '"> donated.</p>';
|
||||
echo '<details' . ( ( 'add_time' === $type && ( ( $vals['cap_minutes'] ?? '' ) !== '' || ( $vals['max_total_minutes'] ?? '' ) !== '' || ( $vals['max_timer_minutes'] ?? '' ) !== '' ) ) ? ' open' : '' ) . '><summary>Limits (optional)</summary>';
|
||||
echo '<p><label>Most minutes one donation can add <input type="number" min="1" class="small-text" name="rule[add_time][cap_minutes]" data-f="cap_minutes" value="' . $v( 'add_time', 'cap_minutes' ) . '"></label></p>';
|
||||
echo '<p><label>Most minutes this rule can add in total <input type="number" min="1" class="small-text" name="rule[add_time][max_total_minutes]" data-f="max_total_minutes" value="' . $v( 'add_time', 'max_total_minutes' ) . '"></label></p>';
|
||||
echo '<p><label>Longest the timer can ever get (minutes) <input type="number" min="1" class="small-text" name="rule[add_time][max_timer_minutes]" data-f="max_timer_minutes" value="' . $v( 'add_time', 'max_timer_minutes' ) . '"></label> <span class="description">Leave empty for no limit. For example, 1440 means the clock never shows more than 24 hours.</span></p>';
|
||||
echo '<p><label>Count ' . $basisOpts( 'add_time' ) . '</label></p></details></div>'; // phpcs:ignore WordPress.Security.EscapeOutput -- built from escaped parts
|
||||
// counter
|
||||
echo '<div class="sg-rule-group" data-type="counter"' . ( 'counter' === $type ? '' : ' hidden' ) . '><p>Add <input type="number" min="1" class="small-text" name="rule[counter][step]" data-f="step" value="' . $v( 'counter', 'step', '1' ) . '"> to the counter for every ' . esc_html( $cur ) . ' <input type="text" inputmode="decimal" class="small-text" name="rule[counter][unit_amount]" data-f="unit_amount" value="' . $v( 'counter', 'unit_amount', 0 === Money::exponent( $cur ) ? '1000' : '10.00' ) . '"> donated.</p>';
|
||||
echo '<p><label>Counter name (shown on the overlay) <input type="text" maxlength="40" name="rule[counter][label]" data-f="label" placeholder="Pies thrown" value="' . $v( 'counter', 'label' ) . '"></label></p>';
|
||||
echo '<p><label><input type="checkbox" name="rule[counter][carry_over]" value="1" data-f="carry_over"' . checked( 'counter' === $type ? ! empty( $vals['carry_over'] ) : true, true, false ) . '> Carry leftovers to the next donation (so two $5 donations count as one $10)</label></p>';
|
||||
echo '<details><summary>Advanced</summary><p><label>Count ' . $basisOpts( 'counter' ) . '</label></p></details></div>'; // phpcs:ignore WordPress.Security.EscapeOutput
|
||||
// bonus
|
||||
echo '<div class="sg-rule-group" data-type="bonus"' . ( 'bonus' === $type ? '' : ' hidden' ) . '><p>Trigger a bonus when a single donation is at least ' . esc_html( $cur ) . ' <input type="text" inputmode="decimal" class="small-text" name="rule[bonus][min_amount]" data-f="min_amount" value="' . $v( 'bonus', 'min_amount', 0 === Money::exponent( $cur ) ? '5000' : '50.00' ) . '">.</p>';
|
||||
echo '<p><label>Bonus name <input type="text" maxlength="40" name="rule[bonus][event]" data-f="event" value="' . $v( 'bonus', 'event', 'big_donation' ) . '"></label> <span class="description">Letters, numbers, _ and - only.</span></p>';
|
||||
echo '<details><summary>Advanced</summary><p><label>Count ' . $basisOpts( 'bonus' ) . '</label></p></details></div>'; // phpcs:ignore WordPress.Security.EscapeOutput
|
||||
echo '<p class="sg-form-preview" id="sg-form-preview" aria-live="polite"></p>';
|
||||
echo '<p><button class="button button-primary">' . ( $edit ? 'Save rule' : 'Add rule' ) . '</button>';
|
||||
if ( $edit ) {
|
||||
echo ' <a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId ) ) ) . '">Cancel</a>';
|
||||
}
|
||||
echo '</p></form></div>';
|
||||
}
|
||||
|
||||
public static function handleRuleSave(): void {
|
||||
Admin::guard( 'sg_rule_save' );
|
||||
$post = Admin::post_raw();
|
||||
$goalId = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
|
||||
$ruleId = isset( $post['rule_id'] ) ? absint( $post['rule_id'] ) : 0;
|
||||
$g = $goalId ? Store::goals()->find( $goalId ) : null;
|
||||
$back = Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId ) );
|
||||
if ( ! $g ) {
|
||||
Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' );
|
||||
}
|
||||
$type = isset( $post['type'] ) && is_string( $post['type'] ) ? $post['type'] : '';
|
||||
if ( ! isset( RuleConfig::TYPES[ $type ] ) ) {
|
||||
Admin::redirect( $back, 'error', 'Please choose a rule type.' );
|
||||
}
|
||||
$existing = null;
|
||||
if ( $ruleId ) {
|
||||
$existing = Store::rule( $ruleId, $goalId );
|
||||
if ( ! $existing || $existing['type'] !== $type ) {
|
||||
Admin::redirect( $back, 'error', 'That rule no longer exists.' );
|
||||
}
|
||||
}
|
||||
$input = isset( $post['rule'][ $type ] ) && is_array( $post['rule'][ $type ] ) ? $post['rule'][ $type ] : array();
|
||||
$res = RuleConfig::sanitize( $type, $input, Format::currency( $g['currency'] ) );
|
||||
if ( null === $res['config'] ) {
|
||||
Admin::redirect( $back . ( $ruleId ? '&rule=' . $ruleId : '' ), 'error', implode( ' ', $res['errors'] ) );
|
||||
}
|
||||
Store::saveRule( $goalId, $type, $res['config'], $existing ? $ruleId : null );
|
||||
Admin::redirect( $back, 'success', 'Rule saved: ' . RuleConfig::summary( $type, $res['config'], Format::currency( $g['currency'] ) ) . '.' );
|
||||
}
|
||||
|
||||
public static function handleRuleToggle(): void {
|
||||
Admin::guard( 'sg_rule_toggle' );
|
||||
$post = Admin::post_raw();
|
||||
$gid = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
|
||||
Store::setRuleEnabled( isset( $post['rule_id'] ) ? absint( $post['rule_id'] ) : 0, $gid, ! empty( $post['enabled'] ) );
|
||||
Admin::redirect( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ), 'success', 'Rule updated.' );
|
||||
}
|
||||
|
||||
public static function handleRuleDelete(): void {
|
||||
Admin::guard( 'sg_rule_delete' );
|
||||
$post = Admin::post_raw();
|
||||
$gid = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
|
||||
Store::deleteRule( isset( $post['rule_id'] ) ? absint( $post['rule_id'] ) : 0, $gid );
|
||||
Admin::redirect( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ), 'success', 'Rule deleted.' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Money;
|
||||
|
||||
/** Pure (WordPress-free) input parsing/sanitizing helpers for the admin screens. */
|
||||
final class Input {
|
||||
|
||||
/** Parse "$1,000.50" / "10" / "10.5" into minor units, or null when invalid. */
|
||||
public static function amountToMinor( mixed $raw, string $currency ): ?int {
|
||||
if ( ! is_scalar( $raw ) ) {
|
||||
return null;
|
||||
}
|
||||
$s = str_replace( array( ',', ' ', "\u{00A0}" ), '', trim( (string) $raw ) );
|
||||
$s = ltrim( $s, '$€£¥' );
|
||||
if ( '' === $s ) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$minor = Money::fromDecimalString( $s, $currency )->minor;
|
||||
} catch ( \InvalidArgumentException ) {
|
||||
return null;
|
||||
}
|
||||
return $minor > 99999999999 ? null : $minor;
|
||||
}
|
||||
|
||||
/** "3.49" (percent) -> 349 basis points; null when invalid or outside 0..30%. */
|
||||
public static function percentToBps( mixed $raw ): ?int {
|
||||
if ( ! is_scalar( $raw ) ) {
|
||||
return null;
|
||||
}
|
||||
$s = rtrim( trim( str_replace( ',', '.', (string) $raw ) ), '%' );
|
||||
if ( ! preg_match( '/^\d{1,2}(\.\d{1,2})?$/', $s ) ) {
|
||||
return null;
|
||||
}
|
||||
[ $w, $f ] = array_pad( explode( '.', $s, 2 ), 2, '' );
|
||||
$bps = (int) $w * 100 + (int) str_pad( $f, 2, '0' );
|
||||
return $bps <= 3000 ? $bps : null;
|
||||
}
|
||||
|
||||
/** Whole number within [min,max], else null. Empty string -> null. */
|
||||
public static function int( mixed $raw, int $min, int $max ): ?int {
|
||||
if ( ! is_scalar( $raw ) || ! preg_match( '/^\s*\d{1,12}\s*$/', (string) $raw ) ) {
|
||||
return null;
|
||||
}
|
||||
$n = (int) trim( (string) $raw );
|
||||
return ( $n >= $min && $n <= $max ) ? $n : null;
|
||||
}
|
||||
|
||||
/** Normalise a "one word per line" textarea: trimmed, lowercase, deduplicated, bounded. */
|
||||
public static function words( string $text ): string {
|
||||
$out = array();
|
||||
foreach ( preg_split( '/\r\n|\r|\n|,/', $text ) ?: array() as $w ) {
|
||||
$w = preg_replace( '/[\x00-\x1F\x7F<>]/u', '', trim( $w ) ) ?? '';
|
||||
$w = function_exists( 'mb_strtolower' ) ? mb_strtolower( $w ) : strtolower( $w );
|
||||
if ( '' === $w || ( function_exists( 'mb_strlen' ) ? mb_strlen( $w ) : strlen( $w ) ) > 40 ) {
|
||||
continue;
|
||||
}
|
||||
$out[ $w ] = true;
|
||||
if ( count( $out ) >= 500 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return implode( "\n", array_keys( $out ) );
|
||||
}
|
||||
|
||||
/** Event name slug: [a-z0-9_-], max 40, falling back to $default. */
|
||||
public static function slug( mixed $raw, string $default = 'big_donation' ): string {
|
||||
$s = is_scalar( $raw ) ? strtolower( trim( (string) $raw ) ) : '';
|
||||
$s = preg_replace( '/[^a-z0-9_-]+/', '_', $s ) ?? '';
|
||||
$s = substr( trim( $s, '_-' ), 0, 40 );
|
||||
return '' === $s ? $default : $s;
|
||||
}
|
||||
|
||||
/** Plain single-line text with control chars and tags removed, bounded in length. */
|
||||
public static function text( mixed $raw, int $max ): string {
|
||||
$s = is_scalar( $raw ) ? strip_tags( (string) $raw ) : '';
|
||||
$s = preg_replace( '/[\x00-\x1F\x7F]/u', '', $s ) ?? '';
|
||||
$s = trim( $s );
|
||||
return function_exists( 'mb_substr' ) ? mb_substr( $s, 0, $max ) : substr( $s, 0, $max );
|
||||
}
|
||||
|
||||
/** Mask for showing that a secret exists without revealing it. */
|
||||
public static function maskSecret( string $secret ): string {
|
||||
return '' === $secret ? '' : str_repeat( "\u{2022}", 12 );
|
||||
}
|
||||
|
||||
/** True when the submitted value is the untouched placeholder or empty (=> keep the stored secret). */
|
||||
public static function secretUnchanged( string $submitted ): bool {
|
||||
$t = trim( $submitted );
|
||||
return '' === $t || 1 === preg_match( '/^[\x{2022}*]+$/u', $t );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Style;
|
||||
use StreamGoals\Rest\OverlayController;
|
||||
|
||||
/** Overlay URLs, style builder, live preview, token regeneration, and test donations. */
|
||||
final class OverlaysPage {
|
||||
|
||||
public const WIDGETS = array(
|
||||
'goal' => array( 'Goal bar', 800, 120, 'Progress bar towards your active goal.' ),
|
||||
'timer' => array( 'Subathon timer', 400, 120, 'Countdown that grows with donations (needs an "Add time" rule).' ),
|
||||
'counter' => array( 'Counter', 400, 120, 'A running count (needs a "Counter" rule).' ),
|
||||
'alerts' => array( 'Donation alerts', 600, 300, 'Pop-up alert for each new donation.' ),
|
||||
);
|
||||
|
||||
/** @return array{url:string,base:string,sep:string} */
|
||||
public static function widgetUrl( string $widget ): array {
|
||||
$token = OverlayController::token();
|
||||
if ( get_option( 'permalink_structure' ) ) {
|
||||
$base = home_url( '/streamgoals-overlay/' . rawurlencode( $token ) . '/' . rawurlencode( $widget ) . '/' );
|
||||
return array( 'url' => $base, 'base' => $base, 'sep' => '?' );
|
||||
}
|
||||
$base = add_query_arg( array( 'sg_overlay_token' => $token, 'sg_overlay_widget' => $widget ), home_url( '/' ) );
|
||||
return array( 'url' => $base, 'base' => $base, 'sep' => '&' );
|
||||
}
|
||||
|
||||
/** Used by the wizard and this screen: one copy-able link per widget. */
|
||||
public static function urlList( bool $withPreview = false ): void {
|
||||
foreach ( self::WIDGETS as $w => [ $label, $width, $height, $desc ] ) {
|
||||
$u = self::widgetUrl( $w );
|
||||
echo '<div class="sg-overlay-card" data-widget="' . esc_attr( $w ) . '" data-base="' . esc_attr( $u['base'] ) . '" data-sep="' . esc_attr( $u['sep'] ) . '" data-w="' . (int) $width . '" data-h="' . (int) $height . '">';
|
||||
echo '<h3>' . esc_html( $label ) . '</h3><p class="description">' . esc_html( $desc ) . ' OBS size: <strong>' . (int) $width . ' x ' . (int) $height . '</strong></p>';
|
||||
echo '<div class="sg-copy"><input type="text" readonly class="large-text code sg-url" value="' . esc_attr( $u['url'] ) . '" aria-label="' . esc_attr( $label . ' overlay URL' ) . '"> <button type="button" class="button" data-sg-copy>Copy</button></div>';
|
||||
if ( $withPreview ) {
|
||||
echo '<p><button type="button" class="button" data-sg-preview>Show live preview</button></p>';
|
||||
echo '<div class="sg-preview" hidden><iframe title="' . esc_attr( $label . ' preview' ) . '" loading="lazy" style="width:' . (int) $width . 'px;height:' . (int) $height . 'px"></iframe></div>';
|
||||
}
|
||||
echo '</div>';
|
||||
}
|
||||
if ( ! get_option( 'permalink_structure' ) ) {
|
||||
echo '<p class="description">Your site uses "Plain" permalinks, so the links use the longer form. They work the same.</p>';
|
||||
}
|
||||
}
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'Overlays' );
|
||||
$fonts = array( 'sans' => 'Clean sans-serif', 'serif' => 'Serif', 'mono' => 'Monospace', 'rounded' => 'Rounded', 'condensed' => 'Condensed' );
|
||||
echo '<p class="sg-lead">Paste these links into OBS as Browser Sources. Use the style builder to change how they look: all links update as you go.</p>';
|
||||
echo '<div class="sg-card"><h2>Style</h2><form id="sg-style" onsubmit="return false"><div class="sg-grid">';
|
||||
echo '<label>Theme<select name="theme">';
|
||||
foreach ( Style::THEMES as $t ) {
|
||||
echo '<option value="' . esc_attr( $t ) . '">' . esc_html( ucfirst( $t ) ) . '</option>';
|
||||
}
|
||||
echo '</select></label>';
|
||||
echo '<label>Font<select name="font">';
|
||||
foreach ( $fonts as $k => $l ) {
|
||||
echo '<option value="' . esc_attr( $k ) . '">' . esc_html( $l ) . '</option>';
|
||||
}
|
||||
echo '<option value="__custom">A font installed on my PC...</option></select></label>';
|
||||
echo '<label class="sg-custom-font" hidden>Font name<input type="text" name="font_custom" maxlength="40" placeholder="Bebas Neue"></label>';
|
||||
echo '<label>Size (50% - 300%)<input type="number" name="scale" min="0.5" max="3" step="0.1" value="1"></label>';
|
||||
foreach ( array( 'color' => 'Text color', 'accent' => 'Accent color', 'accent2' => 'Second accent', 'track' => 'Bar background', 'bg' => 'Panel background' ) as $k => $l ) {
|
||||
echo '<label class="sg-color">' . esc_html( $l ) . '<span><input type="checkbox" name="use_' . esc_attr( $k ) . '" aria-label="Use custom ' . esc_attr( $l ) . '"> <input type="color" name="' . esc_attr( $k ) . '" value="#ffffff"></span></label>';
|
||||
}
|
||||
echo '</div><p class="description">Tick a box to override that color; unticked colors come from the theme.</p></form></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Links</h2>';
|
||||
self::urlList( true );
|
||||
echo '</div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Send a test donation</h2>';
|
||||
echo '<p>Shows a fake donation on the <strong>Donation alerts</strong> overlay so you can check your OBS setup. Open the alerts preview above (or have OBS running) first, then press the button; the alert appears within a few seconds.</p>';
|
||||
echo '<p class="description"><strong>How tests are kept out of your numbers:</strong> test donations are not attached to any goal, so they never count towards raised totals, timers or counters. They are excluded from the CSV export, and marked <em>TEST</em> in the Donations list. Test donations are kept in the database until you delete them below.</p>';
|
||||
Admin::form( 'sg_test_donation', array(), 'sg-inline' );
|
||||
echo '<label>Amount (' . esc_html( Admin::currency() ) . ') <input type="text" name="amount" class="small-text" value="' . esc_attr( 0 === \StreamGoals\Core\Money::exponent( Admin::currency() ) ? '500' : '5.00' ) . '"></label> ';
|
||||
echo '<button type="submit" class="button button-primary">Send test donation</button></form> ';
|
||||
Admin::form( 'sg_delete_tests', array(), 'sg-inline' );
|
||||
echo '<button type="submit" class="button">Delete all test donations</button></form></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Security</h2><p>The links contain a secret token. If a link was shown on stream or shared by mistake, make new links. The old ones stop working immediately and you will need to paste the new ones into OBS.</p>';
|
||||
Admin::form( 'sg_regen_token', array(), 'sg-confirm' );
|
||||
echo '<button type="submit" class="button button-secondary" data-confirm="Make new overlay links? Your current links will stop working and you must update OBS.">Regenerate token</button></form></div>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
public static function handleTestDonation(): void {
|
||||
Admin::guard( 'sg_test_donation' );
|
||||
$cur = Admin::currency();
|
||||
$amt = Input::amountToMinor( Admin::post_str( 'amount', 30 ), $cur );
|
||||
if ( null === $amt || $amt <= 0 || $amt > 99999999 ) {
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'error', 'Please enter a valid test amount, for example 5.00.' );
|
||||
}
|
||||
$id = Store::insertTestDonation( $amt, $cur );
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), $id ? 'success' : 'error', $id ? 'Test donation sent. Watch your alerts overlay.' : 'The test donation could not be saved.' );
|
||||
}
|
||||
|
||||
public static function handleDeleteTests(): void {
|
||||
Admin::guard( 'sg_delete_tests' );
|
||||
$n = Store::deleteTestDonations();
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', $n . ' test donation(s) deleted.' );
|
||||
}
|
||||
|
||||
public static function handleRegenerate(): void {
|
||||
Admin::guard( 'sg_regen_token' );
|
||||
Settings::update( array( 'overlay_token' => bin2hex( random_bytes( 16 ) ) ) );
|
||||
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', 'New overlay links created. Update them in OBS.' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\PayPal\Client;
|
||||
use StreamGoals\PayPal\PayPalException;
|
||||
use StreamGoals\PayPal\WpCache;
|
||||
use StreamGoals\PayPal\WpTransport;
|
||||
|
||||
/** Saves PayPal credentials, tests them, and registers the webhook. Secrets are never echoed or logged. */
|
||||
final class PayPalConnector {
|
||||
|
||||
private const VERIFIED = 'sg_paypal_verified';
|
||||
|
||||
public static function fingerprint( array $s ): string {
|
||||
return hash_hmac( 'sha256', $s['paypal_mode'] . '|' . $s['paypal_client_id'] . '|' . $s['paypal_client_secret'], function_exists( 'wp_salt' ) ? wp_salt( 'auth' ) : 'sg' );
|
||||
}
|
||||
|
||||
/** True once Test connection succeeded for the credentials currently saved. */
|
||||
public static function isConnected(): bool {
|
||||
$s = Settings::all();
|
||||
return '' !== $s['paypal_client_id'] && '' !== $s['paypal_client_secret']
|
||||
&& hash_equals( (string) get_option( self::VERIFIED, '' ), self::fingerprint( $s ) );
|
||||
}
|
||||
|
||||
public static function webhookUrl(): string {
|
||||
return rest_url( 'streamgoals/v1/webhook' );
|
||||
}
|
||||
|
||||
/** Fields rendered by both the wizard and the Settings screen. */
|
||||
public static function fields(): void {
|
||||
$s = Settings::all();
|
||||
$mode = 'live' === $s['paypal_mode'] ? 'live' : 'sandbox';
|
||||
?>
|
||||
<div class="sg-tabs" role="tablist">
|
||||
<label class="sg-tab"><input type="radio" name="paypal_mode" value="sandbox" <?php checked( $mode, 'sandbox' ); ?>> <strong>Sandbox</strong> <span>(practice mode, fake money)</span></label>
|
||||
<label class="sg-tab"><input type="radio" name="paypal_mode" value="live" <?php checked( $mode, 'live' ); ?>> <strong>Live</strong> <span>(real money)</span></label>
|
||||
</div>
|
||||
<p class="description">Start with Sandbox to try everything for free. When you are ready, create a Live app the same way and switch here. Sandbox and Live use <em>different</em> Client IDs and Secrets.</p>
|
||||
<table class="form-table" role="presentation">
|
||||
<tr>
|
||||
<th scope="row"><label for="sg_client_id">Client ID</label></th>
|
||||
<td><input type="text" id="sg_client_id" name="paypal_client_id" class="regular-text code" autocomplete="off" spellcheck="false" value="<?php echo esc_attr( (string) $s['paypal_client_id'] ); ?>"></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th scope="row"><label for="sg_secret">Secret</label></th>
|
||||
<td>
|
||||
<input type="password" id="sg_secret" name="paypal_client_secret" class="regular-text code" autocomplete="new-password" spellcheck="false"
|
||||
value="" placeholder="<?php echo esc_attr( '' !== $s['paypal_client_secret'] ? Input::maskSecret( (string) $s['paypal_client_secret'] ) : 'Paste your Secret here' ); ?>">
|
||||
<p class="description"><?php echo '' !== $s['paypal_client_secret'] ? 'A Secret is saved. Leave this empty to keep it, or paste a new one to replace it.' : 'The Secret stays on your server and is never shown again.'; ?></p>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<?php
|
||||
}
|
||||
|
||||
public static function instructions(): void {
|
||||
?>
|
||||
<ol class="sg-steps">
|
||||
<li>To take <em>real</em> payments PayPal requires a <strong>PayPal Business</strong> account (free; your own name is fine). Practising in Sandbox needs no business account. <a href="https://www.paypal.com/business" target="_blank" rel="noopener noreferrer">Create one</a> or upgrade your existing account in PayPal settings.</li>
|
||||
<li>Open <a href="https://developer.paypal.com/dashboard/applications" target="_blank" rel="noopener noreferrer">developer.paypal.com/dashboard/applications</a> and log in with that Business account.</li>
|
||||
<li>At the top, pick <strong>Sandbox</strong> (to practise) or <strong>Live</strong> (real money) and click <strong>Create App</strong>.</li>
|
||||
<li>Give it any name (for example "My stream"), keep the type <strong>Merchant</strong>, and click <strong>Create App</strong>.</li>
|
||||
<li>On the next page, copy the <strong>Client ID</strong>. Under <strong>Secret key 1</strong> click <strong>Show</strong> and copy the <strong>Secret</strong>.</li>
|
||||
<li>Choose the same mode below (Sandbox or Live), paste both values, and press the button. We will check them and set up payment notifications (the webhook) for you.</li>
|
||||
</ol>
|
||||
<p class="description">Webhook note: PayPal can only send notifications to a public <strong>https://</strong> website. On a local test site the webhook step will fail, which is fine for trying things out.</p>
|
||||
<?php
|
||||
}
|
||||
|
||||
/** admin-post: save credentials, test, register webhook. */
|
||||
public static function handle(): void {
|
||||
Admin::guard( 'sg_paypal_connect' );
|
||||
$from = Admin::post_str( 'return', 20 );
|
||||
// Computed lazily: the wizard lives at a different menu slug depending on whether PayPal is connected.
|
||||
$to = static fn( int $step ): string => 'settings' === $from ? Admin::url( 'streamgoals-settings' ) : SetupPage::url( $step );
|
||||
|
||||
$old = Settings::all();
|
||||
$post = Admin::post_raw();
|
||||
$mode = ( $post['paypal_mode'] ?? '' ) === 'live' ? 'live' : 'sandbox';
|
||||
$cid = Input::text( $post['paypal_client_id'] ?? '', 200 );
|
||||
$sec = Input::secretUnchanged( (string) ( $post['paypal_client_secret'] ?? '' ) ) ? (string) $old['paypal_client_secret'] : Input::text( $post['paypal_client_secret'], 300 );
|
||||
|
||||
if ( '' === $cid || '' === $sec ) {
|
||||
Admin::redirect( $to( 1 ), 'error', 'Please enter both the Client ID and the Secret from your PayPal app.' );
|
||||
}
|
||||
$changed = $mode !== $old['paypal_mode'] || $cid !== $old['paypal_client_id'] || $sec !== $old['paypal_client_secret'];
|
||||
$update = array( 'paypal_mode' => $mode, 'paypal_client_id' => $cid, 'paypal_client_secret' => $sec );
|
||||
if ( $changed ) {
|
||||
$update['paypal_webhook_id'] = ''; // a webhook belongs to one specific app/mode
|
||||
delete_option( self::VERIFIED );
|
||||
}
|
||||
Settings::update( $update );
|
||||
|
||||
$client = new Client( new WpTransport(), new WpCache(), $mode, $cid, $sec );
|
||||
$err = $client->testConnection();
|
||||
if ( null !== $err ) {
|
||||
Admin::redirect( $to( 1 ), 'error', 'Connection failed. ' . self::scrub( $err, $sec ) . ' Double-check that you copied the right values and that the mode (Sandbox/Live) matches the app.' );
|
||||
}
|
||||
update_option( self::VERIFIED, self::fingerprint( Settings::all() ), false );
|
||||
|
||||
$msg = 'Connected to PayPal (' . ( 'live' === $mode ? 'Live' : 'Sandbox' ) . ').';
|
||||
$type = 'success';
|
||||
if ( '' === (string) Settings::get( 'paypal_webhook_id', '' ) ) {
|
||||
try {
|
||||
$id = $client->createWebhook( self::webhookUrl() );
|
||||
Settings::update( array( 'paypal_webhook_id' => $id ) );
|
||||
$msg .= ' Payment notifications (webhook) were set up automatically.';
|
||||
} catch ( PayPalException $e ) {
|
||||
$type = 'warning';
|
||||
$msg .= ' However, the webhook could not be registered automatically: ' . self::scrub( $e->getMessage(), $sec )
|
||||
. ' Webhooks need a public https:// site, and a webhook for this address may already exist in your PayPal app (delete it there and try again).';
|
||||
}
|
||||
}
|
||||
Admin::redirect( $to( 2 ), $type, $msg );
|
||||
}
|
||||
|
||||
/** Defensive: make sure an error text can never contain the secret or client id. */
|
||||
public static function scrub( string $text, string $secret ): string {
|
||||
$text = '' !== $secret ? str_replace( $secret, '[hidden]', $text ) : $text;
|
||||
return Input::text( $text, 400 );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Rules\AddTimeRule;
|
||||
use StreamGoals\Rules\BonusRule;
|
||||
use StreamGoals\Rules\CounterRule;
|
||||
use StreamGoals\Rules\Donation;
|
||||
|
||||
/**
|
||||
* Pure rule-config logic: turns friendly form input into the exact config keys the Rules classes read,
|
||||
* produces human summaries and "what would a donation do" previews. No WordPress dependency.
|
||||
*/
|
||||
final class RuleConfig {
|
||||
|
||||
public const TYPES = array(
|
||||
'add_time' => 'Add time to the timer',
|
||||
'counter' => 'Counter',
|
||||
'bonus' => 'Big-donation bonus alert',
|
||||
);
|
||||
|
||||
private const UNIT_SECONDS = array( 'seconds' => 1, 'minutes' => 60, 'hours' => 3600 );
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $in Raw (already wp_unslash'ed) form fields.
|
||||
* @return array{config:?array,errors:string[]}
|
||||
*/
|
||||
public static function sanitize( string $type, array $in, string $currency ): array {
|
||||
$errors = array();
|
||||
$basis = ( $in['basis'] ?? 'base' ) === 'total' ? 'total' : 'base';
|
||||
$unit = Input::amountToMinor( $in['unit_amount'] ?? '', $currency );
|
||||
|
||||
switch ( $type ) {
|
||||
case 'add_time':
|
||||
$mult = self::UNIT_SECONDS[ (string) ( $in['time_unit'] ?? 'minutes' ) ] ?? null;
|
||||
$n = Input::int( $in['time_amount'] ?? '', 1, 1000000 );
|
||||
if ( null === $mult ) {
|
||||
$errors[] = 'Choose seconds, minutes or hours.';
|
||||
}
|
||||
if ( null === $n ) {
|
||||
$errors[] = 'Enter how much time to add (a whole number, 1 or more).';
|
||||
}
|
||||
if ( null === $unit || $unit <= 0 ) {
|
||||
$errors[] = 'Enter the donation amount that earns that time (for example 1.00).';
|
||||
}
|
||||
$cap = self::optionalMinutes( $in['cap_minutes'] ?? '', 'The per-donation limit', $errors );
|
||||
$max = self::optionalMinutes( $in['max_total_minutes'] ?? '', 'The total limit', $errors );
|
||||
$clk = self::optionalMinutes( $in['max_timer_minutes'] ?? '', 'The longest the timer can get', $errors );
|
||||
if ( $errors ) {
|
||||
return array( 'config' => null, 'errors' => $errors );
|
||||
}
|
||||
$secs = $n * $mult;
|
||||
if ( $secs > 31536000 ) {
|
||||
return array( 'config' => null, 'errors' => array( 'That is too much time per unit (more than a year).' ) );
|
||||
}
|
||||
return array(
|
||||
'config' => array(
|
||||
'seconds_per_unit' => $secs,
|
||||
'unit_minor' => $unit,
|
||||
'cap_seconds_per_donation' => $cap,
|
||||
'max_total_seconds' => $max,
|
||||
'max_timer_seconds' => $clk,
|
||||
'basis' => $basis,
|
||||
),
|
||||
'errors' => array(),
|
||||
);
|
||||
|
||||
case 'counter':
|
||||
$step = Input::int( $in['step'] ?? '', 1, 1000000 );
|
||||
if ( null === $step ) {
|
||||
$errors[] = 'Enter how much the counter goes up each time (a whole number, 1 or more).';
|
||||
}
|
||||
if ( null === $unit || $unit <= 0 ) {
|
||||
$errors[] = 'Enter the donation amount that earns each step (for example 10.00).';
|
||||
}
|
||||
if ( $errors ) {
|
||||
return array( 'config' => null, 'errors' => $errors );
|
||||
}
|
||||
return array(
|
||||
'config' => array(
|
||||
'step' => $step,
|
||||
'per_minor' => $unit,
|
||||
'carry_over' => ! empty( $in['carry_over'] ),
|
||||
'basis' => $basis,
|
||||
'label' => Input::text( $in['label'] ?? '', 40 ),
|
||||
),
|
||||
'errors' => array(),
|
||||
);
|
||||
|
||||
case 'bonus':
|
||||
$min = Input::amountToMinor( $in['min_amount'] ?? '', $currency );
|
||||
if ( null === $min || $min <= 0 ) {
|
||||
$errors[] = 'Enter the smallest single donation that triggers the bonus (for example 50.00).';
|
||||
return array( 'config' => null, 'errors' => $errors );
|
||||
}
|
||||
return array(
|
||||
'config' => array(
|
||||
'min_minor' => $min,
|
||||
'event' => Input::slug( $in['event'] ?? '' ),
|
||||
'basis' => $basis,
|
||||
),
|
||||
'errors' => array(),
|
||||
);
|
||||
}
|
||||
return array( 'config' => null, 'errors' => array( 'Unknown rule type.' ) );
|
||||
}
|
||||
|
||||
private static function optionalMinutes( mixed $raw, string $what, array &$errors ): ?int {
|
||||
if ( ! is_scalar( $raw ) || '' === trim( (string) $raw ) ) {
|
||||
return null;
|
||||
}
|
||||
$m = Input::int( $raw, 1, 525600 );
|
||||
if ( null === $m ) {
|
||||
$errors[] = $what . ' must be a whole number of minutes (or leave it empty for no limit).';
|
||||
return null;
|
||||
}
|
||||
return $m * 60;
|
||||
}
|
||||
|
||||
/** Human-readable one-liner, e.g. "Adds 1 minute for every $1.00". */
|
||||
public static function summary( string $type, array $c, string $currency ): string {
|
||||
$basisNote = 'total' === ( $c['basis'] ?? 'base' ) ? ' (including fees the donor covers)' : '';
|
||||
switch ( $type ) {
|
||||
case 'add_time':
|
||||
$s = 'Adds ' . Format::duration( (int) ( $c['seconds_per_unit'] ?? 0 ) ) . ' for every ' . Format::money( (int) ( $c['unit_minor'] ?? 0 ), $currency ) . $basisNote;
|
||||
if ( isset( $c['cap_seconds_per_donation'] ) ) {
|
||||
$s .= ', at most ' . Format::duration( (int) $c['cap_seconds_per_donation'] ) . ' per donation';
|
||||
}
|
||||
if ( isset( $c['max_total_seconds'] ) ) {
|
||||
$s .= ', ' . Format::duration( (int) $c['max_total_seconds'] ) . ' in total';
|
||||
}
|
||||
if ( isset( $c['max_timer_seconds'] ) ) {
|
||||
$s .= ', up to ' . Format::duration( (int) $c['max_timer_seconds'] ) . ' on the clock';
|
||||
}
|
||||
return $s;
|
||||
case 'counter':
|
||||
$label = (string) ( $c['label'] ?? '' );
|
||||
$s = 'Adds ' . (int) ( $c['step'] ?? 1 ) . ( '' !== $label ? ' to "' . $label . '"' : ' to the counter' )
|
||||
. ' for every ' . Format::money( (int) ( $c['per_minor'] ?? 0 ), $currency ) . $basisNote;
|
||||
return $s . ( ! empty( $c['carry_over'] ) ? ' (leftover amounts carry over to the next donation)' : ' (leftover amounts are not carried over)' );
|
||||
case 'bonus':
|
||||
return 'Triggers the "' . (string) ( $c['event'] ?? 'bonus' ) . '" bonus for any single donation of '
|
||||
. Format::money( (int) ( $c['min_minor'] ?? 0 ), $currency ) . ' or more' . $basisNote;
|
||||
}
|
||||
return 'Unknown rule';
|
||||
}
|
||||
|
||||
/**
|
||||
* What would a donation of $baseMinor (plus optional covered fee) do against these rules,
|
||||
* assuming a fresh state (no carry-over, no accumulated caps)?
|
||||
*
|
||||
* @param array<int,array{type:string,config:array}> $rules
|
||||
* @return string[]
|
||||
*/
|
||||
public static function preview( array $rules, int $baseMinor, string $currency, int $feeMinor = 0 ): array {
|
||||
$d = new Donation( 0, 0, $baseMinor, $feeMinor, $baseMinor + $feeMinor, $currency );
|
||||
$lines = array();
|
||||
foreach ( $rules as $r ) {
|
||||
$type = (string) ( $r['type'] ?? '' );
|
||||
$cfg = (array) ( $r['config'] ?? array() );
|
||||
try {
|
||||
if ( 'add_time' === $type ) {
|
||||
$res = AddTimeRule::fromConfig( $cfg )->apply( $d, 0, 0, 0 );
|
||||
$lines[] = $res['delta'] > 0 ? 'Timer: +' . Format::duration( $res['delta'] ) : 'Timer: no time added';
|
||||
if ( isset( $cfg['max_timer_seconds'] ) ) {
|
||||
$lines[ count( $lines ) - 1 ] .= ' (the timer never goes above ' . Format::duration( (int) $cfg['max_timer_seconds'] ) . ')';
|
||||
}
|
||||
} elseif ( 'counter' === $type ) {
|
||||
$res = CounterRule::fromConfig( $cfg )->apply( $d, 0, 0 );
|
||||
$lbl = (string) ( $cfg['label'] ?? '' );
|
||||
$lines[] = ( '' !== $lbl ? $lbl : 'Counter' ) . ': +' . $res['delta'];
|
||||
} elseif ( 'bonus' === $type ) {
|
||||
$b = BonusRule::fromConfig( $cfg );
|
||||
$lines[] = $b->apply( $d ) ? 'Bonus "' . $b->event . '" triggers' : 'Bonus "' . $b->event . '" does not trigger';
|
||||
}
|
||||
} catch ( \InvalidArgumentException ) {
|
||||
$lines[] = 'A rule is misconfigured and will be skipped.';
|
||||
}
|
||||
}
|
||||
return $lines;
|
||||
}
|
||||
|
||||
/** Reverse of sanitize(): config -> editable form values. */
|
||||
public static function toForm( string $type, array $c, string $currency ): array {
|
||||
$f = array( 'basis' => 'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base' );
|
||||
if ( 'add_time' === $type ) {
|
||||
$s = (int) ( $c['seconds_per_unit'] ?? 60 );
|
||||
[ $f['time_amount'], $f['time_unit'] ] = 0 === $s % 3600 && $s > 0 ? array( $s / 3600, 'hours' ) : ( 0 === $s % 60 && $s > 0 ? array( $s / 60, 'minutes' ) : array( $s, 'seconds' ) );
|
||||
$f['unit_amount'] = Format::decimal( (int) ( $c['unit_minor'] ?? 100 ), $currency );
|
||||
$f['cap_minutes'] = isset( $c['cap_seconds_per_donation'] ) ? (string) intdiv( (int) $c['cap_seconds_per_donation'], 60 ) : '';
|
||||
$f['max_total_minutes'] = isset( $c['max_total_seconds'] ) ? (string) intdiv( (int) $c['max_total_seconds'], 60 ) : '';
|
||||
$f['max_timer_minutes'] = isset( $c['max_timer_seconds'] ) ? (string) intdiv( (int) $c['max_timer_seconds'], 60 ) : '';
|
||||
} elseif ( 'counter' === $type ) {
|
||||
$f['step'] = (int) ( $c['step'] ?? 1 );
|
||||
$f['unit_amount'] = Format::decimal( (int) ( $c['per_minor'] ?? 1000 ), $currency );
|
||||
$f['carry_over'] = ! empty( $c['carry_over'] );
|
||||
$f['label'] = (string) ( $c['label'] ?? '' );
|
||||
} else {
|
||||
$f['min_amount'] = Format::decimal( (int) ( $c['min_minor'] ?? 5000 ), $currency );
|
||||
$f['event'] = (string) ( $c['event'] ?? 'big_donation' );
|
||||
}
|
||||
return $f;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/** Settings: PayPal credentials (own form), fees, anonymity, moderation, profanity, limits, currency. */
|
||||
final class SettingsPage {
|
||||
|
||||
private const POLICIES = array(
|
||||
'allow' => 'Donors choose: they can give a name or stay anonymous',
|
||||
'require_name' => 'Donors must give a name',
|
||||
'force_anonymous' => 'Everyone is anonymous (no names are collected or stored)',
|
||||
);
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'StreamGoals settings' );
|
||||
$s = Settings::all();
|
||||
$cur = Admin::currency();
|
||||
|
||||
echo '<div class="sg-card"><h2>PayPal connection</h2>';
|
||||
echo PayPalConnector::isConnected() ? '<p class="sg-ok">Connected (' . esc_html( 'live' === $s['paypal_mode'] ? 'Live' : 'Sandbox' ) . ').</p>' : '<p class="sg-warn">Not connected yet. Follow the steps in the <a href="' . esc_url( SetupPage::url( 1 ) ) . '">setup guide</a>.</p>';
|
||||
Admin::form( 'sg_paypal_connect', array( 'return' => 'settings' ) );
|
||||
PayPalConnector::fields();
|
||||
echo '<p class="description">Webhook address (registered automatically): <code>' . esc_html( PayPalConnector::webhookUrl() ) . '</code><br>Webhook status: ' . ( '' !== (string) $s['paypal_webhook_id'] ? 'registered' : 'not registered' ) . '</p>';
|
||||
echo '<p><button class="button button-primary">Save and test connection</button></p></form></div>';
|
||||
|
||||
Admin::form( 'sg_settings_save' );
|
||||
echo '<div class="sg-card"><h2>Donations</h2><table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sg_cur">Currency</label></th><td><select id="sg_cur" name="currency">';
|
||||
foreach ( Format::CURRENCIES as $c => $name ) {
|
||||
echo '<option value="' . esc_attr( $c ) . '"' . selected( $cur, $c, false ) . '>' . esc_html( $c . ' - ' . $name ) . '</option>';
|
||||
}
|
||||
echo '</select><p class="description">One currency for the whole site. It applies to goals you create from now on; existing goals keep their currency. Check the fixed fee below after changing it.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_min">Minimum donation (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_min" name="min_donation" class="small-text" inputmode="decimal" value="' . esc_attr( Format::decimal( \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ), $cur ) ) . '"> <span class="description">At least ' . esc_html( Format::money( \StreamGoals\Core\Settings::HARD_MIN_MINOR, $cur ) ) . '. Visitors cannot donate less than this.</span></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_len">Longest message</label></th><td><input type="number" id="sg_len" name="message_max_length" min="0" max="500" class="small-text" value="' . (int) $s['message_max_length'] . '"> characters <span class="description">(0 to 500; 0 = no messages)</span></td></tr>';
|
||||
echo '<tr><th scope="row">Names</th><td><fieldset>';
|
||||
foreach ( self::POLICIES as $k => $l ) {
|
||||
echo '<label><input type="radio" name="anonymity_policy" value="' . esc_attr( $k ) . '"' . checked( $s['anonymity_policy'], $k, false ) . '> ' . esc_html( $l ) . '</label><br>';
|
||||
}
|
||||
echo '</fieldset><p class="description">Anonymous donors\' names are never saved.</p></td></tr></table></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Messages</h2><table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row">Moderation</th><td><label><input type="checkbox" name="moderate_messages" value="1"' . checked( ! empty( $s['moderate_messages'] ), true, false ) . '> Hold messages for my approval before they can be shown in alerts</label></td></tr>';
|
||||
echo '<tr><th scope="row">Profanity filter</th><td><label><input type="checkbox" name="profanity_filter" value="1"' . checked( ! empty( $s['profanity_filter'] ), true, false ) . '> Filter bad language in messages and names</label><br>';
|
||||
echo '<label><input type="checkbox" name="profanity_use_builtin" value="1"' . checked( ! empty( $s['profanity_use_builtin'] ), true, false ) . '> Use the built-in word list</label>';
|
||||
echo '<p><label for="sg_words">Your own words to block (one per line)</label><br><textarea id="sg_words" name="profanity_words" rows="6" class="large-text code">' . esc_textarea( (string) $s['profanity_words'] ) . '</textarea></p></td></tr></table></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Checkout buttons</h2><table class="form-table" role="presentation"><tr><th scope="row">Payment options</th><td>';
|
||||
echo '<label><input type="checkbox" name="funding_card" value="1"' . checked( ! empty( $s['funding_card'] ), true, false ) . '> Show "Debit or Credit Card" (donors without a PayPal account)</label><br>';
|
||||
echo '<label><input type="checkbox" name="funding_paylater" value="1"' . checked( ! empty( $s['funding_paylater'] ), true, false ) . '> Show "Pay Later" (donors pay in instalments; you are still paid in full)</label>';
|
||||
echo '<p class="description">The PayPal button is always shown. Which extra buttons appear can also depend on the donor\'s country.</p></td></tr></table></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Advanced</h2><table class="form-table" role="presentation"><tr><th scope="row"><label for="sg_ip">Visitor IP address</label></th><td><select id="sg_ip" name="visitor_ip_header">';
|
||||
foreach ( \StreamGoals\Core\ClientIp::MODES as $k => $l ) {
|
||||
echo '<option value="' . esc_attr( $k ) . '"' . selected( (string) $s['visitor_ip_header'], $k, false ) . '>' . esc_html( $l ) . '</option>';
|
||||
}
|
||||
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). If your site is behind Cloudflare or another proxy, choose it here so each visitor is counted separately; otherwise everyone looks like the same visitor and a busy moment, like a raid, could block donations. Only choose a proxy option if <em>all</em> traffic to your site really goes through it.</p>';
|
||||
self::ipDiagnostics( (string) $s['visitor_ip_header'] );
|
||||
echo '</td></tr></table></div>';
|
||||
|
||||
$rel = \StreamGoals\Update\Updater::latest();
|
||||
echo '<div class="sg-card"><h2>Plugin updates</h2><table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row">Installed version</th><td><code>' . esc_html( STREAMGOALS_VERSION ) . '</code></td></tr>';
|
||||
echo '<tr><th scope="row">Latest release</th><td>' . ( $rel ? '<code>' . esc_html( $rel['version'] ) . '</code>' . ( \StreamGoals\Update\ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ? ' (update available)' : ' (up to date)' ) : 'Not found yet (or the check failed).' ) . ' <button type="submit" form="sg_update_check_form" class="button">Check for updates now</button></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_utoken">Access token (only needed while the update repository is private)</label></th><td><input type="password" id="sg_utoken" name="update_token" class="regular-text code" autocomplete="new-password" spellcheck="false" value="" placeholder="' . esc_attr( '' !== (string) $s['update_token'] ? Input::maskSecret( (string) $s['update_token'] ) : 'Paste a read-only token' ) . '">';
|
||||
echo '<p class="description">' . ( '' !== (string) $s['update_token'] ? 'A token is saved. Leave this empty to keep it, or paste a new one to replace it.' : 'Not needed once the repository is public.' ) . '</p></td></tr></table></div>';
|
||||
|
||||
echo '<div class="sg-card"><h2>PayPal fee estimate</h2>';
|
||||
echo '<p>When a donor chooses "cover the fees", the form adds the estimated PayPal fee so you receive the amount they intended. The defaults (<strong>3.49% + $0.49</strong>) are <strong>US domestic estimates</strong>. Fees for international (cross-border) payments and currency conversion are higher and are <strong>not</strong> included, so you may receive slightly less than expected in those cases. Check PayPal\'s current fee page for your country and adjust.</p>';
|
||||
echo '<table class="form-table" role="presentation"><tr><th scope="row"><label for="sg_pct">Percentage fee</label></th><td><input type="text" id="sg_pct" name="fee_percent" class="small-text" inputmode="decimal" value="' . esc_attr( number_format( (int) $s['fee_percent_bps'] / 100, 2, '.', '' ) ) . '"> %</td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_fix">Fixed fee (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_fix" name="fee_fixed" class="small-text" inputmode="decimal" value="' . esc_attr( Format::decimal( (int) $s['fee_fixed_minor'], $cur ) ) . '"></td></tr></table></div>';
|
||||
echo '<p><button class="button button-primary button-hero">Save settings</button></p></form>';
|
||||
echo '<form id="sg_update_check_form" method="post" action="' . esc_url( admin_url( 'admin-post.php' ) ) . '"><input type="hidden" name="action" value="' . esc_attr( \StreamGoals\Update\Updater::ACTION_CHECK ) . '">';
|
||||
wp_nonce_field( \StreamGoals\Update\Updater::ACTION_CHECK );
|
||||
echo '</form>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
/** Shows the owner what their server passes to the plugin right now, to help pick the right option. */
|
||||
private static function ipDiagnostics( string $mode ): void {
|
||||
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
|
||||
$server = array();
|
||||
foreach ( $keys as $k => $_ ) {
|
||||
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
|
||||
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
|
||||
}
|
||||
}
|
||||
echo '<details class="sg-ipdiag"><summary>What does my server see right now?</summary><table class="widefat striped" style="max-width:36rem"><tbody>';
|
||||
foreach ( $keys as $k => $label ) {
|
||||
echo '<tr><td>' . esc_html( $label ) . '</td><td><code>' . ( isset( $server[ $k ] ) ? esc_html( $server[ $k ] ) : '(not sent)' ) . '</code></td></tr>';
|
||||
}
|
||||
echo '<tr><td><strong>Visitor address used with the saved option</strong></td><td><code>' . esc_html( \StreamGoals\Core\ClientIp::resolve( $server, $mode ) ) . '</code></td></tr>';
|
||||
echo '</tbody></table><p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
|
||||
}
|
||||
|
||||
public static function handleSave(): void {
|
||||
Admin::guard( 'sg_settings_save' );
|
||||
$post = Admin::post_raw();
|
||||
$back = Admin::url( 'streamgoals-settings' );
|
||||
$errors = array();
|
||||
$cur = Format::currency( $post['currency'] ?? 'USD' );
|
||||
$upd = array();
|
||||
|
||||
$min = Input::amountToMinor( $post['min_donation'] ?? '', $cur );
|
||||
if ( null === $min || $min < \StreamGoals\Core\Settings::HARD_MIN_MINOR ) {
|
||||
$errors[] = 'Minimum donation must be at least ' . Format::money( \StreamGoals\Core\Settings::HARD_MIN_MINOR, $cur ) . '. PayPal\'s fixed fee makes smaller donations lose money.';
|
||||
} else {
|
||||
$upd['min_donation_minor'] = $min;
|
||||
}
|
||||
$len = Input::int( $post['message_max_length'] ?? '', 0, 500 );
|
||||
if ( null === $len ) {
|
||||
$errors[] = 'Longest message must be a number from 0 to 500.';
|
||||
} else {
|
||||
$upd['message_max_length'] = $len;
|
||||
}
|
||||
$pct = Input::percentToBps( $post['fee_percent'] ?? '' );
|
||||
if ( null === $pct ) {
|
||||
$errors[] = 'Percentage fee must be between 0 and 30 (for example 3.49).';
|
||||
} else {
|
||||
$upd['fee_percent_bps'] = $pct;
|
||||
}
|
||||
$fix = Input::amountToMinor( $post['fee_fixed'] ?? '', $cur );
|
||||
if ( null === $fix || $fix > 10000 ) {
|
||||
$errors[] = 'Fixed fee must be a small amount (for example 0.49).';
|
||||
} else {
|
||||
$upd['fee_fixed_minor'] = $fix;
|
||||
}
|
||||
$pol = isset( $post['anonymity_policy'] ) && is_string( $post['anonymity_policy'] ) ? $post['anonymity_policy'] : '';
|
||||
if ( ! isset( self::POLICIES[ $pol ] ) ) {
|
||||
$errors[] = 'Please choose a names option.';
|
||||
} else {
|
||||
$upd['anonymity_policy'] = $pol;
|
||||
}
|
||||
$ipMode = isset( $post['visitor_ip_header'] ) && is_string( $post['visitor_ip_header'] ) ? $post['visitor_ip_header'] : '';
|
||||
if ( ! array_key_exists( $ipMode, \StreamGoals\Core\ClientIp::MODES ) ) {
|
||||
$errors[] = 'Please choose a visitor IP option.';
|
||||
} else {
|
||||
$upd['visitor_ip_header'] = $ipMode;
|
||||
}
|
||||
$tok = $post['update_token'] ?? '';
|
||||
if ( ! Input::secretUnchanged( is_string( $tok ) ? $tok : '' ) ) {
|
||||
$upd['update_token'] = Input::text( $tok, 300 );
|
||||
}
|
||||
$upd['funding_card'] = ! empty( $post['funding_card'] );
|
||||
$upd['funding_paylater'] = ! empty( $post['funding_paylater'] );
|
||||
$upd['moderate_messages'] = ! empty( $post['moderate_messages'] );
|
||||
$upd['profanity_filter'] = ! empty( $post['profanity_filter'] );
|
||||
$upd['profanity_use_builtin'] = ! empty( $post['profanity_use_builtin'] );
|
||||
$upd['profanity_words'] = Input::words( isset( $post['profanity_words'] ) && is_string( $post['profanity_words'] ) ? $post['profanity_words'] : '' );
|
||||
|
||||
Settings::update( $upd );
|
||||
update_option( 'sg_currency', $cur, false ); // Settings has no currency key, so it lives in its own option.
|
||||
|
||||
if ( $errors ) {
|
||||
Admin::redirect( $back, 'warning', 'Some settings were not saved: ' . implode( ' ', $errors ) . ' Everything else was saved.' );
|
||||
}
|
||||
Admin::redirect( $back, 'success', 'Settings saved.' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
/** The 4-step setup wizard: PayPal, first goal, donation page, overlays. */
|
||||
final class SetupPage {
|
||||
|
||||
private const STEPS = array( 1 => 'PayPal', 2 => 'First goal', 3 => 'Donation page', 4 => 'Overlays' );
|
||||
|
||||
public static function url( int $step = 1 ): string {
|
||||
$page = PayPalConnector::isConnected() ? 'streamgoals-setup' : Admin::HOME;
|
||||
return Admin::url( $page, array( 'step' => $step ) );
|
||||
}
|
||||
|
||||
public static function render(): void {
|
||||
Admin::open( 'StreamGoals setup' );
|
||||
$connected = PayPalConnector::isConnected();
|
||||
$step = Admin::get_int( 'step' );
|
||||
$step = isset( self::STEPS[ $step ] ) ? $step : 1;
|
||||
if ( ! $connected ) {
|
||||
$step = 1; // nothing else works before PayPal is connected
|
||||
}
|
||||
echo '<p class="sg-lead">Welcome! Four quick steps and you are ready to collect donations on stream.</p>';
|
||||
echo '<ol class="sg-progress">';
|
||||
foreach ( self::STEPS as $n => $label ) {
|
||||
$cls = $n === $step ? 'is-current' : ( $n < $step || ( $connected && $n > 1 ) ? 'is-done' : '' );
|
||||
echo '<li class="' . esc_attr( $cls ) . '">' . ( $connected ? '<a href="' . esc_url( self::url( $n ) ) . '">' : '' ) . esc_html( $label ) . ( $connected ? '</a>' : '' ) . '</li>';
|
||||
}
|
||||
echo '</ol><div class="sg-card">';
|
||||
match ( $step ) {
|
||||
2 => self::step2(),
|
||||
3 => self::step3(),
|
||||
4 => self::step4(),
|
||||
default => self::step1( $connected ),
|
||||
};
|
||||
echo '</div>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
private static function step1( bool $connected ): void {
|
||||
echo '<h2>Step 1: Connect PayPal</h2>';
|
||||
if ( $connected ) {
|
||||
echo '<p class="sg-ok">PayPal is connected. You can continue, or paste new credentials below to change them.</p>';
|
||||
echo '<p><a class="button button-primary" href="' . esc_url( self::url( 2 ) ) . '">Continue to step 2</a></p>';
|
||||
}
|
||||
PayPalConnector::instructions();
|
||||
Admin::form( 'sg_paypal_connect', array( 'return' => 'setup' ) );
|
||||
PayPalConnector::fields();
|
||||
echo '<p><button type="submit" class="button button-primary button-hero">Test connection</button></p></form>';
|
||||
}
|
||||
|
||||
private static function step2(): void {
|
||||
$cur = Admin::currency();
|
||||
echo '<h2>Step 2: Create your first goal</h2><p>Pick a starting point. You can change everything later on the Goals screen.</p>';
|
||||
Admin::form( 'sg_wizard_goal' );
|
||||
echo '<div class="sg-templates">';
|
||||
$first = true;
|
||||
foreach ( Templates::LABELS as $key => [ $label, $desc ] ) {
|
||||
echo '<label class="sg-template"><input type="radio" name="template" value="' . esc_attr( $key ) . '"' . checked( $first, true, false ) . '> <strong>' . esc_html( $label ) . '</strong><br><span>' . esc_html( $desc ) . '</span></label>';
|
||||
$first = false;
|
||||
}
|
||||
echo '</div><table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sg_title">Goal name</label></th><td><input type="text" id="sg_title" name="title" class="regular-text" maxlength="190" placeholder="New gaming PC"></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_target" name="target" class="small-text" inputmode="decimal" value="' . esc_attr( 0 === \StreamGoals\Core\Money::exponent( $cur ) ? '10000' : '100.00' ) . '"> <span class="description">How much you want to raise.</span></td></tr></table>';
|
||||
echo '<p><button type="submit" class="button button-primary button-hero">Create goal</button></p></form>';
|
||||
}
|
||||
|
||||
private static function step3(): void {
|
||||
echo '<h2>Step 3: Add a donation page</h2>';
|
||||
$id = (int) get_option( 'sg_donate_page_id', 0 );
|
||||
$post = $id ? get_post( $id ) : null;
|
||||
if ( $post && 'trash' !== $post->post_status ) {
|
||||
echo '<p class="sg-ok">Your donation page exists: <a href="' . esc_url( (string) get_permalink( $post ) ) . '" target="_blank" rel="noopener noreferrer">' . esc_html( get_the_title( $post ) ) . '</a> (<a href="' . esc_url( (string) get_edit_post_link( $post->ID, 'raw' ) ) . '">edit</a>).</p>';
|
||||
} else {
|
||||
echo '<p>Viewers donate through a page on your site. We can create it for you now. It simply contains this shortcode:</p>';
|
||||
}
|
||||
echo '<p><code>[streamgoals_donate]</code> <button type="button" class="button" data-sg-copy-text="[streamgoals_donate]">Copy</button></p>';
|
||||
echo '<p class="description">You can paste that shortcode into any page or post. To show only one goal use <code>[streamgoals_donate goal="ID"]</code>.</p>';
|
||||
if ( ! $post || 'trash' === $post->post_status ) {
|
||||
Admin::form( 'sg_wizard_page', array( 'mode' => 'create' ), 'sg-inline' );
|
||||
echo '<button type="submit" class="button button-primary button-hero">Create my Donate page</button></form> ';
|
||||
}
|
||||
Admin::form( 'sg_wizard_page', array( 'mode' => 'skip' ), 'sg-inline' );
|
||||
echo '<button type="submit" class="button">' . ( $post && 'trash' !== $post->post_status ? 'Continue' : 'Skip, I will add it myself' ) . '</button></form>';
|
||||
}
|
||||
|
||||
private static function step4(): void {
|
||||
echo '<h2>Step 4: Add the overlays to OBS</h2>';
|
||||
echo '<p>Overlays are small web pages OBS shows on top of your stream. Each one has its own link. <strong>Keep these links private</strong>: anyone with a link can see your live overlay (not your donor details or money info).</p>';
|
||||
OverlaysPage::urlList();
|
||||
echo '<h3>How to add one in OBS</h3><ol class="sg-steps">';
|
||||
echo '<li>In OBS, under <strong>Sources</strong> click <strong>+</strong> and choose <strong>Browser</strong>.</li>';
|
||||
echo '<li>Name it (for example "Goal bar") and click OK.</li>';
|
||||
echo '<li>Paste the link into the <strong>URL</strong> box. Do <em>not</em> tick "Local file".</li>';
|
||||
echo '<li>Set <strong>Width</strong> and <strong>Height</strong> to the recommended size shown next to the link. Leave the custom CSS box as it is.</li>';
|
||||
echo '<li>Click OK, then move and resize it on your canvas. The background is transparent automatically.</li>';
|
||||
echo '<li>Want different colors or fonts? Open the <a href="' . esc_url( Admin::url( 'streamgoals-overlays' ) ) . '">Overlays screen</a>, which builds the link for you and lets you send a test donation.</li></ol>';
|
||||
echo '<p><a class="button button-primary button-hero" href="' . esc_url( Admin::url( Admin::HOME ) ) . '">Finish setup</a></p>';
|
||||
}
|
||||
|
||||
public static function handleGoal(): void {
|
||||
Admin::guard( 'sg_wizard_goal' );
|
||||
$cur = Admin::currency();
|
||||
$key = Admin::post_str( 'template', 20 );
|
||||
$tgt = Input::amountToMinor( Admin::post_str( 'target', 30 ), $cur );
|
||||
if ( ! Templates::exists( $key ) ) {
|
||||
Admin::redirect( self::url( 2 ), 'error', 'Please choose a goal template.' );
|
||||
}
|
||||
if ( null === $tgt || $tgt <= 0 ) {
|
||||
Admin::redirect( self::url( 2 ), 'error', 'Please enter a target amount greater than zero, for example 100.00.' );
|
||||
}
|
||||
$built = Templates::build( $key, $cur, $tgt, Admin::post_str( 'title', 190 ) );
|
||||
$built['goal']['starts_at'] = null;
|
||||
$built['goal']['ends_at'] = null;
|
||||
$id = Store::goals()->create( $built['goal'] );
|
||||
if ( $id <= 0 ) {
|
||||
Admin::redirect( self::url( 2 ), 'error', 'The goal could not be saved. Please try again.' );
|
||||
}
|
||||
foreach ( $built['rules'] as $r ) {
|
||||
Store::saveRule( $id, $r['type'], $r['config'] );
|
||||
}
|
||||
update_option( 'sg_wizard_goal_id', $id, false );
|
||||
Admin::redirect( self::url( 3 ), 'success', 'Goal created.' );
|
||||
}
|
||||
|
||||
public static function handlePage(): void {
|
||||
Admin::guard( 'sg_wizard_page' );
|
||||
if ( 'create' === Admin::post_str( 'mode', 10 ) ) {
|
||||
if ( ! current_user_can( 'publish_pages' ) ) {
|
||||
wp_die( esc_html__( 'You do not have permission to do that.', 'streamgoals-donate' ), 403 );
|
||||
}
|
||||
$id = wp_insert_post( array(
|
||||
'post_type' => 'page',
|
||||
'post_status' => 'publish',
|
||||
'post_title' => 'Donate',
|
||||
'post_content' => '[streamgoals_donate]',
|
||||
), true );
|
||||
if ( is_wp_error( $id ) ) {
|
||||
Admin::redirect( self::url( 3 ), 'error', 'The page could not be created. You can add the shortcode to any page yourself.' );
|
||||
}
|
||||
update_option( 'sg_donate_page_id', (int) $id, false );
|
||||
Admin::redirect( self::url( 4 ), 'success', 'Donate page created and published.' );
|
||||
}
|
||||
Admin::redirect( self::url( 4 ), 'info', 'Skipped. Remember to add [streamgoals_donate] to a page.' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\DonationRepository;
|
||||
use StreamGoals\Core\GoalRepository;
|
||||
|
||||
/** $wpdb access used only by the admin screens. Requires live WordPress. */
|
||||
final class Store {
|
||||
|
||||
private static function t( string $name ): string {
|
||||
global $wpdb;
|
||||
return $wpdb->prefix . 'sg_' . $name;
|
||||
}
|
||||
|
||||
public static function goals(): GoalRepository {
|
||||
return new GoalRepository();
|
||||
}
|
||||
|
||||
public static function donations(): DonationRepository {
|
||||
return new DonationRepository();
|
||||
}
|
||||
|
||||
/** @return array[] all rules (enabled or not) with decoded config. */
|
||||
public static function rules( int $goalId ): array {
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'rules' ) . ' WHERE goal_id = %d ORDER BY sort ASC, id ASC', $goalId ), ARRAY_A );
|
||||
$rows = (array) $rows;
|
||||
// Iterate $rows itself by reference: `foreach ( (array) $rows as &$r )` would modify a temporary copy and discard the decoding.
|
||||
foreach ( $rows as &$r ) {
|
||||
$cfg = json_decode( (string) $r['config'], true );
|
||||
$r['config'] = is_array( $cfg ) ? $cfg : array();
|
||||
}
|
||||
unset( $r );
|
||||
return $rows;
|
||||
}
|
||||
|
||||
public static function rule( int $ruleId, int $goalId ): ?array {
|
||||
foreach ( self::rules( $goalId ) as $r ) {
|
||||
if ( (int) $r['id'] === $ruleId ) {
|
||||
return $r;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static function saveRule( int $goalId, string $type, array $config, ?int $ruleId = null ): void {
|
||||
global $wpdb;
|
||||
$json = wp_json_encode( $config );
|
||||
if ( null === $ruleId ) {
|
||||
$sort = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COALESCE(MAX(sort),0)+1 FROM ' . self::t( 'rules' ) . ' WHERE goal_id = %d', $goalId ) );
|
||||
$wpdb->insert( self::t( 'rules' ), array( 'goal_id' => $goalId, 'type' => $type, 'config' => $json, 'enabled' => 1, 'sort' => $sort ), array( '%d', '%s', '%s', '%d', '%d' ) );
|
||||
} else {
|
||||
$wpdb->update( self::t( 'rules' ), array( 'config' => $json ), array( 'id' => $ruleId, 'goal_id' => $goalId ), array( '%s' ), array( '%d', '%d' ) );
|
||||
}
|
||||
}
|
||||
|
||||
public static function setRuleEnabled( int $ruleId, int $goalId, bool $on ): void {
|
||||
global $wpdb;
|
||||
$wpdb->update( self::t( 'rules' ), array( 'enabled' => $on ? 1 : 0 ), array( 'id' => $ruleId, 'goal_id' => $goalId ), array( '%d' ), array( '%d', '%d' ) );
|
||||
}
|
||||
|
||||
/** Deleting a rule keeps its event history rows out of the way (they are only idempotency markers). */
|
||||
public static function deleteRule( int $ruleId, int $goalId ): void {
|
||||
global $wpdb;
|
||||
if ( ! self::rule( $ruleId, $goalId ) ) {
|
||||
return;
|
||||
}
|
||||
$wpdb->delete( self::t( 'rules' ), array( 'id' => $ruleId, 'goal_id' => $goalId ), array( '%d', '%d' ) );
|
||||
$wpdb->delete( self::t( 'rule_events' ), array( 'rule_id' => $ruleId ), array( '%d' ) );
|
||||
$wpdb->query( $wpdb->prepare( 'DELETE FROM ' . self::t( 'state' ) . ' WHERE goal_id = %d AND skey LIKE %s', $goalId, '%:' . $ruleId ) );
|
||||
}
|
||||
|
||||
public static function donationCountForGoal( int $goalId ): int {
|
||||
global $wpdb;
|
||||
return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM ' . self::t( 'donations' ) . ' WHERE goal_id = %d', $goalId ) );
|
||||
}
|
||||
|
||||
/** Only possible when the goal has no donations (otherwise donations would be orphaned). */
|
||||
public static function deleteGoal( int $goalId ): bool {
|
||||
global $wpdb;
|
||||
if ( self::donationCountForGoal( $goalId ) > 0 ) {
|
||||
return false;
|
||||
}
|
||||
foreach ( self::rules( $goalId ) as $r ) {
|
||||
self::deleteRule( (int) $r['id'], $goalId );
|
||||
}
|
||||
$wpdb->delete( self::t( 'state' ), array( 'goal_id' => $goalId ), array( '%d' ) );
|
||||
return self::goals()->delete( $goalId );
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{status?:string,search?:string,tests?:string,moderation?:string} $f
|
||||
* @return array{rows:array[],total:int}
|
||||
*/
|
||||
public static function searchDonations( array $f, int $page, int $perPage ): array {
|
||||
global $wpdb;
|
||||
[ $where, $args ] = self::donationWhere( $f );
|
||||
$t = self::t( 'donations' );
|
||||
$total = (int) $wpdb->get_var( $args ? $wpdb->prepare( "SELECT COUNT(*) FROM {$t} WHERE {$where}", ...$args ) : "SELECT COUNT(*) FROM {$t} WHERE {$where}" );
|
||||
$a2 = array_merge( $args, array( $perPage, max( 0, ( $page - 1 ) * $perPage ) ) );
|
||||
$rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$t} WHERE {$where} ORDER BY id DESC LIMIT %d OFFSET %d", ...$a2 ), ARRAY_A );
|
||||
return array( 'rows' => (array) $rows, 'total' => $total );
|
||||
}
|
||||
|
||||
/** @return array{0:string,1:array} */
|
||||
private static function donationWhere( array $f ): array {
|
||||
global $wpdb;
|
||||
$w = array( '1=1' );
|
||||
$args = array();
|
||||
$st = $f['status'] ?? '';
|
||||
if ( in_array( $st, array( 'pending', 'completed' ), true ) ) {
|
||||
$w[] = 'status = %s';
|
||||
$args[] = $st;
|
||||
}
|
||||
if ( in_array( $f['moderation'] ?? '', array( 'pending', 'approved', 'rejected' ), true ) ) {
|
||||
$w[] = 'moderation = %s';
|
||||
$args[] = $f['moderation'];
|
||||
}
|
||||
if ( 'hide' === ( $f['tests'] ?? '' ) ) {
|
||||
$w[] = 'paypal_order_id NOT LIKE %s';
|
||||
$args[] = $wpdb->esc_like( Format::TEST_PREFIX ) . '%';
|
||||
}
|
||||
$s = trim( (string) ( $f['search'] ?? '' ) );
|
||||
if ( '' !== $s ) {
|
||||
$like = '%' . $wpdb->esc_like( $s ) . '%';
|
||||
// Names of anonymous donors are never stored, and are never searchable.
|
||||
$w[] = '( ( is_anonymous = 0 AND donor_name LIKE %s ) OR message LIKE %s OR paypal_order_id LIKE %s OR paypal_capture_id LIKE %s )';
|
||||
array_push( $args, $like, $like, $like, $like );
|
||||
}
|
||||
return array( implode( ' AND ', $w ), $args );
|
||||
}
|
||||
|
||||
/** Real donations only (test donations excluded). Streams in batches to bound memory. */
|
||||
public static function exportBatch( int $afterId, int $limit ): array {
|
||||
global $wpdb;
|
||||
return (array) $wpdb->get_results(
|
||||
$wpdb->prepare(
|
||||
'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id > %d AND paypal_order_id NOT LIKE %s AND goal_id > 0 ORDER BY id ASC LIMIT %d',
|
||||
$afterId,
|
||||
$wpdb->esc_like( Format::TEST_PREFIX ) . '%',
|
||||
$limit
|
||||
),
|
||||
ARRAY_A
|
||||
);
|
||||
}
|
||||
|
||||
public static function pendingModerationCount(): int {
|
||||
global $wpdb;
|
||||
return (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . self::t( 'donations' ) . " WHERE status = 'completed' AND moderation = 'pending'" );
|
||||
}
|
||||
|
||||
public static function setModeration( int $id, string $to ): bool {
|
||||
global $wpdb;
|
||||
if ( ! in_array( $to, array( 'approved', 'rejected' ), true ) ) {
|
||||
return false;
|
||||
}
|
||||
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET moderation = %s WHERE id = %d AND moderation = 'pending'", $to, $id ) );
|
||||
return 1 === $n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Test donations: goal_id = 0 (so every per-goal SUM and the rules engine ignore them),
|
||||
* paypal_order_id/capture id start with TEST-, and the message is flagged. Excluded from CSV.
|
||||
*/
|
||||
public static function insertTestDonation( int $amountMinor, string $currency ): ?int {
|
||||
return self::donations()->insert( array(
|
||||
'goal_id' => 0,
|
||||
'paypal_order_id' => Format::TEST_PREFIX . bin2hex( random_bytes( 6 ) ),
|
||||
'paypal_capture_id' => Format::TEST_PREFIX . bin2hex( random_bytes( 8 ) ),
|
||||
'base_minor' => $amountMinor,
|
||||
'fee_minor' => 0,
|
||||
'total_minor' => $amountMinor,
|
||||
'currency' => $currency,
|
||||
'donor_name' => 'Test Donor',
|
||||
'is_anonymous' => 0,
|
||||
'message' => '[TEST] This is a test alert from StreamGoals.',
|
||||
'status' => 'completed',
|
||||
'moderation' => 'approved',
|
||||
) );
|
||||
}
|
||||
|
||||
public static function deleteTestDonations(): int {
|
||||
global $wpdb;
|
||||
return (int) $wpdb->query( $wpdb->prepare( 'DELETE FROM ' . self::t( 'donations' ) . ' WHERE goal_id = 0 AND paypal_order_id LIKE %s', $wpdb->esc_like( Format::TEST_PREFIX ) . '%' ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Money;
|
||||
|
||||
/** Pure goal templates used by the setup wizard. */
|
||||
final class Templates {
|
||||
|
||||
public const LABELS = array(
|
||||
'simple' => array( 'Simple goal', 'A progress bar towards a fundraising target. Nothing else.' ),
|
||||
'subathon' => array( 'Subathon timer: +1 min per $1', 'A countdown that gets longer with every donation (1 minute added for every $1).' ),
|
||||
'counter' => array( 'Counter: +1 per $10', 'A counter that goes up by 1 for every $10 donated (for example "pies thrown").' ),
|
||||
);
|
||||
|
||||
public static function exists( string $key ): bool {
|
||||
return isset( self::LABELS[ $key ] );
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{goal:array,rules:array<int,array{type:string,config:array}>}
|
||||
*/
|
||||
public static function build( string $key, string $currency, int $targetMinor, string $title = '' ): array {
|
||||
$one = 10 ** Money::exponent( $currency ); // one whole currency unit, in minor units
|
||||
$name = '' !== trim( $title ) ? trim( $title ) : ( 'subathon' === $key ? 'Subathon' : ( 'counter' === $key ? 'Donation counter' : 'My first goal' ) );
|
||||
$goal = array( 'title' => $name, 'target_minor' => $targetMinor, 'currency' => $currency, 'status' => 'active', 'counts_fees' => 0 );
|
||||
$rules = array();
|
||||
if ( 'subathon' === $key ) {
|
||||
$rules[] = array( 'type' => 'add_time', 'config' => array(
|
||||
'seconds_per_unit' => 60, 'unit_minor' => $one, 'cap_seconds_per_donation' => null, 'max_total_seconds' => null, 'max_timer_seconds' => null, 'basis' => 'base',
|
||||
) );
|
||||
} elseif ( 'counter' === $key ) {
|
||||
$rules[] = array( 'type' => 'counter', 'config' => array(
|
||||
'step' => 1, 'per_minor' => 10 * $one, 'carry_over' => true, 'basis' => 'base', 'label' => 'Count',
|
||||
) );
|
||||
}
|
||||
return array( 'goal' => $goal, 'rules' => $rules );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/**
|
||||
* Works out the visitor's IP for rate limiting. Pure (takes the $_SERVER values as an array) so it is unit-testable.
|
||||
*
|
||||
* Behind a CDN or reverse proxy, PHP's REMOTE_ADDR is the proxy's address, so every visitor would share one rate
|
||||
* limit. The owner can name the header their proxy sets. A header is ONLY trusted when the owner selected it, and
|
||||
* only if it holds a valid IP address; otherwise we fall back to REMOTE_ADDR.
|
||||
*/
|
||||
final class ClientIp {
|
||||
|
||||
public const MODE_DIRECT = ''; // no proxy: use REMOTE_ADDR
|
||||
public const MODE_CLOUDFLARE = 'cloudflare'; // CF-Connecting-IP
|
||||
public const MODE_REAL_IP = 'real_ip'; // X-Real-IP (nginx and many hosts)
|
||||
public const MODE_FORWARDED = 'forwarded'; // last address in X-Forwarded-For (exactly one proxy in front)
|
||||
|
||||
public const MODES = array(
|
||||
self::MODE_DIRECT => 'Not behind a proxy or CDN (most sites)',
|
||||
self::MODE_CLOUDFLARE => 'Cloudflare (CF-Connecting-IP)',
|
||||
self::MODE_REAL_IP => 'X-Real-IP header',
|
||||
self::MODE_FORWARDED => 'X-Forwarded-For header (one proxy in front)',
|
||||
);
|
||||
|
||||
/** @param array<string,mixed> $server $_SERVER-style values (already unslashed). */
|
||||
public static function resolve( array $server, string $mode = self::MODE_DIRECT ): string {
|
||||
$remote = self::valid( $server['REMOTE_ADDR'] ?? null );
|
||||
$fromHeader = null;
|
||||
switch ( $mode ) {
|
||||
case self::MODE_CLOUDFLARE:
|
||||
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
|
||||
break;
|
||||
case self::MODE_REAL_IP:
|
||||
$fromHeader = self::valid( $server['HTTP_X_REAL_IP'] ?? null );
|
||||
break;
|
||||
case self::MODE_FORWARDED:
|
||||
$raw = $server['HTTP_X_FORWARDED_FOR'] ?? null;
|
||||
if ( is_string( $raw ) && '' !== trim( $raw ) ) {
|
||||
$parts = array_map( 'trim', explode( ',', $raw ) );
|
||||
$fromHeader = self::valid( end( $parts ) ); // the entry our proxy appended; earlier ones are client-supplied
|
||||
}
|
||||
break;
|
||||
}
|
||||
return $fromHeader ?? $remote ?? 'unknown';
|
||||
}
|
||||
|
||||
private static function valid( mixed $v ): ?string {
|
||||
if ( ! is_string( $v ) ) {
|
||||
return null;
|
||||
}
|
||||
$v = trim( $v );
|
||||
return false !== filter_var( $v, FILTER_VALIDATE_IP ) ? $v : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/**
|
||||
* Daily housekeeping: removes checkouts that were started but never paid.
|
||||
*
|
||||
* Only rows that never received a PayPal capture id are purged, and only after a week, so a slow payment
|
||||
* that PayPal finalizes later through the webhook is never discarded.
|
||||
*/
|
||||
final class Maintenance {
|
||||
|
||||
public const HOOK = 'sg_purge_abandoned';
|
||||
public const MAX_AGE_DAYS = 7;
|
||||
|
||||
public static function register(): void {
|
||||
add_action( self::HOOK, array( self::class, 'purge_abandoned' ) );
|
||||
if ( ! wp_next_scheduled( self::HOOK ) ) {
|
||||
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::HOOK );
|
||||
}
|
||||
}
|
||||
|
||||
public static function unschedule(): void {
|
||||
wp_clear_scheduled_hook( self::HOOK );
|
||||
}
|
||||
|
||||
/** @return int Number of rows removed. */
|
||||
public static function purge_abandoned(): int {
|
||||
global $wpdb;
|
||||
$table = $wpdb->prefix . 'sg_donations';
|
||||
$cutoff = gmdate( 'Y-m-d H:i:s', time() - self::MAX_AGE_DAYS * DAY_IN_SECONDS );
|
||||
$n = $wpdb->query(
|
||||
$wpdb->prepare(
|
||||
"DELETE FROM {$table} WHERE status = 'pending' AND (paypal_capture_id IS NULL OR paypal_capture_id = '') AND goal_id > 0 AND created_at < %s", // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
|
||||
$cutoff
|
||||
)
|
||||
);
|
||||
return (int) $n;
|
||||
}
|
||||
}
|
||||
@@ -14,10 +14,12 @@ final class Plugin {
|
||||
\StreamGoals\Rest\WebhookController::class,
|
||||
\StreamGoals\Rest\OverlayController::class,
|
||||
\StreamGoals\Admin\Admin::class,
|
||||
\StreamGoals\Update\Updater::class,
|
||||
);
|
||||
|
||||
public static function boot(): void {
|
||||
Installer::maybe_upgrade();
|
||||
Maintenance::register();
|
||||
foreach ( self::MODULES as $module ) {
|
||||
if ( class_exists( $module ) && method_exists( $module, 'register' ) ) {
|
||||
$module::register();
|
||||
|
||||
@@ -8,6 +8,17 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class Settings {
|
||||
|
||||
/**
|
||||
* Absolute minimum donation in minor units (1.00 of the currency). PayPal's fixed per-transaction fee
|
||||
* makes smaller donations a net loss for the streamer, so the configured minimum can never go below this.
|
||||
*/
|
||||
public const HARD_MIN_MINOR = 100;
|
||||
|
||||
/** The minimum that is actually enforced: the configured value, but never below the hard floor. */
|
||||
public static function effectiveMin( int $configured ): int {
|
||||
return max( self::HARD_MIN_MINOR, $configured );
|
||||
}
|
||||
|
||||
public static function defaults(): array {
|
||||
return array(
|
||||
'paypal_mode' => 'sandbox', // sandbox | live
|
||||
@@ -24,6 +35,10 @@ final class Settings {
|
||||
'message_max_length' => 200,
|
||||
'min_donation_minor' => 100,
|
||||
'overlay_token' => '',
|
||||
'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp)
|
||||
'funding_paylater' => false, // show PayPal "Pay Later" button
|
||||
'update_token' => '', // optional Gitea read token (only while the update repo is private)
|
||||
'funding_card' => true, // show the Debit/Credit Card button
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -28,4 +28,13 @@ interface OverlayDataSource {
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function donations( ?int $sinceId, int $limit ): array;
|
||||
|
||||
/**
|
||||
* Bonus event names that fired (and were not reversed) per donation, in firing order. One lookup
|
||||
* for the whole page. Raw stored strings; Payloads sanitizes them. Donations without bonuses may be omitted.
|
||||
*
|
||||
* @param int[] $donationIds
|
||||
* @return array<int,string[]> donation id => event names
|
||||
*/
|
||||
public function bonusesFor( array $donationIds ): array;
|
||||
}
|
||||
@@ -26,7 +26,13 @@ final class OverlayService {
|
||||
$c = $gid ? $this->source->counter( $gid ) : array( 'label' => '', 'value' => 0 );
|
||||
return Payloads::counter( $c['label'], $c['value'] );
|
||||
case 'alerts':
|
||||
return Payloads::alerts( $this->source->donations( $since, 20 ), $since );
|
||||
$rows = $this->source->donations( $since, 20 );
|
||||
$ids = array_values( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), $rows ) ) );
|
||||
$bonuses = ( null !== $since && $ids ) ? $this->source->bonusesFor( $ids ) : array();
|
||||
foreach ( $rows as $i => $r ) {
|
||||
$rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
}
|
||||
return Payloads::alerts( $rows, $since );
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -107,6 +107,7 @@ final class Payloads {
|
||||
'amount_display' => self::money( (int) $r['base_minor'], $cur ),
|
||||
'currency' => $cur,
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
|
||||
);
|
||||
}
|
||||
$alerts = array_slice( $alerts, 0, max( 1, $limit ) );
|
||||
@@ -116,6 +117,35 @@ final class Payloads {
|
||||
return array( 'alerts' => $alerts, 'last_id' => $lastId );
|
||||
}
|
||||
|
||||
/**
|
||||
* Display-safe bonus labels. Stored events should be [A-Za-z0-9_-] only; anything else is stripped
|
||||
* anyway, then humanized ("big_donation" -> "Big donation"). Empty/duplicate results are dropped.
|
||||
*
|
||||
* @param mixed $events
|
||||
* @return string[]
|
||||
*/
|
||||
public static function bonuses( mixed $events ): array {
|
||||
$out = array();
|
||||
foreach ( is_array( $events ) ? $events : array() as $e ) {
|
||||
if ( ! is_string( $e ) ) {
|
||||
continue;
|
||||
}
|
||||
$clean = substr( (string) preg_replace( '/[^A-Za-z0-9_-]/', '', $e ), 0, 40 );
|
||||
$label = trim( (string) preg_replace( '/[_-]+/', ' ', $clean ) );
|
||||
if ( '' === $label ) {
|
||||
continue;
|
||||
}
|
||||
$label = ucfirst( strtolower( $label ) );
|
||||
if ( ! in_array( $label, $out, true ) ) {
|
||||
$out[] = $label;
|
||||
}
|
||||
if ( count( $out ) >= 5 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Strong ETag over the payload, ignoring the volatile server_now so unchanged data yields 304s. */
|
||||
public static function etag( array $payload ): string {
|
||||
unset( $payload['server_now'] );
|
||||
|
||||
@@ -62,6 +62,31 @@ final class WpdbDataSource implements OverlayDataSource {
|
||||
return array( 'label' => $label, 'value' => $total );
|
||||
}
|
||||
|
||||
public function bonusesFor( array $donationIds ): array {
|
||||
global $wpdb;
|
||||
$ids = array_values( array_unique( array_filter( array_map( 'intval', $donationIds ), static fn( $i ) => $i > 0 ) ) );
|
||||
if ( ! $ids ) {
|
||||
return array();
|
||||
}
|
||||
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT e.donation_id, r.config FROM {$this->t('rule_events')} e
|
||||
INNER JOIN {$this->t('rules')} r ON r.id = e.rule_id
|
||||
WHERE r.type = 'bonus' AND e.reversed = 0 AND e.delta > 0 AND e.donation_id IN ($in)
|
||||
ORDER BY e.id ASC",
|
||||
$ids
|
||||
), ARRAY_A );
|
||||
$out = array();
|
||||
foreach ( (array) $rows as $row ) {
|
||||
$cfg = json_decode( (string) $row['config'], true );
|
||||
$ev = is_array( $cfg ) && isset( $cfg['event'] ) && is_string( $cfg['event'] ) ? $cfg['event'] : '';
|
||||
if ( '' !== $ev ) {
|
||||
$out[ (int) $row['donation_id'] ][] = $ev;
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function donations( ?int $sinceId, int $limit ): array {
|
||||
global $wpdb;
|
||||
$cols = 'id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
|
||||
|
||||
@@ -94,9 +94,9 @@ final class OrderValidator {
|
||||
} catch ( \InvalidArgumentException $e ) {
|
||||
throw new ValidationException( 'invalid_amount', 'Please enter a valid amount.' );
|
||||
}
|
||||
$min = (int) ( $settings['min_donation_minor'] ?? 0 );
|
||||
$min = \StreamGoals\Core\Settings::effectiveMin( (int) ( $settings['min_donation_minor'] ?? 0 ) );
|
||||
if ( $base <= 0 || $base < $min ) {
|
||||
throw new ValidationException( 'amount_too_small', 'The amount is below the minimum donation.' );
|
||||
throw new ValidationException( 'amount_too_small', 'The minimum donation is ' . ( new Money( $min, $currency ) )->toDecimalString() . ' ' . $currency . '.' );
|
||||
}
|
||||
if ( $base > 99999999 ) { // sanity cap (~$999,999.99)
|
||||
throw new ValidationException( 'amount_too_large', 'The amount is too large.' );
|
||||
|
||||
@@ -177,8 +177,9 @@ final class DonateController {
|
||||
'restUrl' => esc_url_raw( rest_url( self::NS ) ),
|
||||
'clientId' => (string) $s['paypal_client_id'],
|
||||
'policy' => (string) $s['anonymity_policy'],
|
||||
'minMinor' => (int) $s['min_donation_minor'],
|
||||
'minMinor' => \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ),
|
||||
'messageMax' => min( 500, (int) $s['message_max_length'] ),
|
||||
'disableFunding' => array_values( array_filter( array( empty( $s['funding_paylater'] ) ? 'paylater' : '', empty( $s['funding_card'] ) ? 'card' : '' ) ) ),
|
||||
'goals' => $goals,
|
||||
'i18n' => array(
|
||||
'goal' => __( 'Goal', 'streamgoals-donate' ),
|
||||
@@ -193,6 +194,14 @@ final class DonateController {
|
||||
'error' => __( 'Something went wrong. Please try again.', 'streamgoals-donate' ),
|
||||
'sdkError' => __( 'Could not load PayPal.', 'streamgoals-donate' ),
|
||||
'fixForm' => __( 'Please fix the form before paying.', 'streamgoals-donate' ),
|
||||
'customAmount' => __( 'Or enter your own amount', 'streamgoals-donate' ),
|
||||
'customPlaceholder' => __( 'Other amount', 'streamgoals-donate' ),
|
||||
/* translators: %s: formatted minimum amount, e.g. $1.00 */
|
||||
'minHint' => __( 'Minimum donation: %s', 'streamgoals-donate' ),
|
||||
/* translators: %s: formatted minimum amount, e.g. $1.00 */
|
||||
'belowMin' => __( 'The minimum donation is %s.', 'streamgoals-donate' ),
|
||||
'coverInfoLabel' => __( 'What does this mean?', 'streamgoals-donate' ),
|
||||
'coverInfo' => __( 'PayPal takes a small fee from every donation. Tick this box to add that fee to your total, so the full amount you chose reaches the streamer. It is optional.', 'streamgoals-donate' ),
|
||||
),
|
||||
);
|
||||
wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsDonate=' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' );
|
||||
@@ -223,7 +232,13 @@ final class DonateController {
|
||||
}
|
||||
|
||||
private static function limit( string $bucket, int $max, int $window ): ?\WP_Error {
|
||||
$ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown';
|
||||
$server = array();
|
||||
foreach ( array( 'REMOTE_ADDR', 'HTTP_CF_CONNECTING_IP', 'HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR' ) as $k ) {
|
||||
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
|
||||
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
|
||||
}
|
||||
}
|
||||
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', '' ) );
|
||||
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@ namespace StreamGoals\Rules;
|
||||
/**
|
||||
* Adds seconds to a goal timer. Proportional: seconds = floor(amount * seconds_per_unit / unit_minor).
|
||||
* cap_seconds_per_donation limits one donation; max_total_seconds limits the cumulative seconds
|
||||
* this rule may ever add (net of reversals). The timer is an absolute ends_at timestamp.
|
||||
* this rule may ever add (net of reversals). maxTimer caps the remaining time on the clock (ends_at - now);
|
||||
* null = uncapped. A timer already above the cap is never shortened, it just gets 0 added. The timer is an absolute ends_at timestamp.
|
||||
*/
|
||||
final class AddTimeRule {
|
||||
|
||||
@@ -15,9 +16,10 @@ final class AddTimeRule {
|
||||
public readonly int $unitMinor,
|
||||
public readonly ?int $capPerDonation = null,
|
||||
public readonly ?int $maxTotal = null,
|
||||
public readonly string $basis = 'base'
|
||||
public readonly string $basis = 'base',
|
||||
public readonly ?int $maxTimer = null
|
||||
) {
|
||||
if ( $unitMinor <= 0 || $secondsPerUnit < 0 ) {
|
||||
if ( $unitMinor <= 0 || $secondsPerUnit < 0 || ( null !== $maxTimer && $maxTimer < 1 ) ) {
|
||||
throw new \InvalidArgumentException( 'Invalid add_time config.' );
|
||||
}
|
||||
}
|
||||
@@ -28,7 +30,8 @@ final class AddTimeRule {
|
||||
(int) ( $c['unit_minor'] ?? 0 ),
|
||||
isset( $c['cap_seconds_per_donation'] ) ? (int) $c['cap_seconds_per_donation'] : null,
|
||||
isset( $c['max_total_seconds'] ) ? (int) $c['max_total_seconds'] : null,
|
||||
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base'
|
||||
'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base',
|
||||
isset( $c['max_timer_seconds'] ) ? (int) $c['max_timer_seconds'] : null
|
||||
);
|
||||
}
|
||||
|
||||
@@ -41,14 +44,18 @@ final class AddTimeRule {
|
||||
if ( null !== $this->maxTotal ) {
|
||||
$delta = min( $delta, max( 0, $this->maxTotal - $addedTotal ) );
|
||||
}
|
||||
// Expired (or never started) timers restart from now.
|
||||
$start = max( $endsAt, $now );
|
||||
if ( null !== $this->maxTimer ) {
|
||||
$delta = min( $delta, max( 0, $this->maxTimer - ( $start - $now ) ) );
|
||||
}
|
||||
$delta = max( 0, $delta );
|
||||
if ( 0 === $delta ) {
|
||||
return array( 'delta' => 0, 'ends_at' => $endsAt, 'added_total' => $addedTotal );
|
||||
}
|
||||
// Expired (or never started) timers restart from now.
|
||||
return array(
|
||||
'delta' => $delta,
|
||||
'ends_at' => max( $endsAt, $now ) + $delta,
|
||||
'ends_at' => $start + $delta,
|
||||
'added_total' => $addedTotal + $delta,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,20 @@ final class Engine {
|
||||
|
||||
/** Production wiring: $wpdb-backed stores. */
|
||||
public static function default(): self {
|
||||
return new self( new WpRuleStore(), new WpEventStore(), new \StreamGoals\Core\StateStore() );
|
||||
$onBonus = static function ( string $event, RuleDef $rule, Donation $d, bool $reversed ): void {
|
||||
if ( function_exists( 'do_action' ) ) {
|
||||
/**
|
||||
* Fires when a big-donation bonus rule triggers (or is reversed by a refund).
|
||||
*
|
||||
* @param string $event Rule's event name.
|
||||
* @param int $donationId Donation id.
|
||||
* @param int $ruleId Rule id.
|
||||
* @param bool $reversed True when the bonus was undone.
|
||||
*/
|
||||
do_action( 'streamgoals_bonus', $event, $d->id, $rule->id, $reversed );
|
||||
}
|
||||
};
|
||||
return new self( new WpRuleStore(), new WpEventStore(), new \StreamGoals\Core\StateStore(), null, $onBonus );
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Update;
|
||||
|
||||
/**
|
||||
* Pure (WordPress-free) parsing of a Gitea release payload.
|
||||
*/
|
||||
final class ReleaseParser {
|
||||
|
||||
public const ASSET_NAME = 'streamgoals-donate.zip';
|
||||
|
||||
private const DATE_TAG = '/^\d{4}\.\d{2}\.\d{2}-\d{4}$/';
|
||||
private const SEMVER = '/^\d+\.\d+\.\d+$/';
|
||||
|
||||
/**
|
||||
* @param array $release Decoded Gitea release JSON.
|
||||
* @param string $host The only host a package URL may point to (e.g. repo.anhonesthost.net).
|
||||
* @return array{version:string,package:string,url:string,notes:string,published:string}|null
|
||||
*/
|
||||
public static function parse( array $release, string $host ): ?array {
|
||||
if ( ! empty( $release['draft'] ) || ! empty( $release['prerelease'] ) ) {
|
||||
return null;
|
||||
}
|
||||
$version = self::normalizeVersion( $release['tag_name'] ?? null );
|
||||
if ( null === $version ) {
|
||||
return null;
|
||||
}
|
||||
$assets = isset( $release['assets'] ) && is_array( $release['assets'] ) ? $release['assets'] : array();
|
||||
$package = self::pickPackage( $assets, $host );
|
||||
if ( null === $package ) {
|
||||
return null;
|
||||
}
|
||||
$url = $release['html_url'] ?? '';
|
||||
return array(
|
||||
'version' => $version,
|
||||
'package' => $package,
|
||||
'url' => is_string( $url ) && self::isAllowedUrl( $url, $host ) ? $url : '',
|
||||
'notes' => is_string( $release['body'] ?? null ) ? $release['body'] : '',
|
||||
'published' => is_string( $release['published_at'] ?? null ) ? $release['published_at'] : '',
|
||||
);
|
||||
}
|
||||
|
||||
public static function normalizeVersion( mixed $tag ): ?string {
|
||||
if ( ! is_string( $tag ) ) {
|
||||
return null;
|
||||
}
|
||||
$t = trim( $tag );
|
||||
if ( '' !== $t && ( 'v' === $t[0] || 'V' === $t[0] ) ) {
|
||||
$t = substr( $t, 1 );
|
||||
}
|
||||
return 1 === preg_match( self::DATE_TAG, $t ) || 1 === preg_match( self::SEMVER, $t ) ? $t : null;
|
||||
}
|
||||
|
||||
public static function isNewer( string $remote, string $current ): bool {
|
||||
$r = self::normalizeVersion( $remote );
|
||||
if ( null === $r ) {
|
||||
return false;
|
||||
}
|
||||
return version_compare( $r, ltrim( $current, 'vV' ), '>' );
|
||||
}
|
||||
|
||||
/** https URL on exactly the configured host (no userinfo tricks). */
|
||||
public static function isAllowedUrl( string $url, string $host ): bool {
|
||||
$p = parse_url( $url );
|
||||
if ( ! is_array( $p ) || ! isset( $p['scheme'], $p['host'] ) || isset( $p['user'] ) || isset( $p['pass'] ) ) {
|
||||
return false;
|
||||
}
|
||||
return 'https' === strtolower( $p['scheme'] ) && '' !== $host && strtolower( $p['host'] ) === strtolower( $host );
|
||||
}
|
||||
|
||||
private static function pickPackage( array $assets, string $host ): ?string {
|
||||
$exact = null;
|
||||
$first = null;
|
||||
foreach ( $assets as $a ) {
|
||||
if ( ! is_array( $a ) || ! is_string( $a['name'] ?? null ) || ! is_string( $a['browser_download_url'] ?? null ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( ! self::isAllowedUrl( $a['browser_download_url'], $host ) ) {
|
||||
continue;
|
||||
}
|
||||
if ( self::ASSET_NAME === $a['name'] ) {
|
||||
$exact = $exact ?? $a['browser_download_url'];
|
||||
} elseif ( null === $first && str_ends_with( strtolower( $a['name'] ), '.zip' ) ) {
|
||||
$first = $a['browser_download_url'];
|
||||
}
|
||||
}
|
||||
return $exact ?? $first;
|
||||
}
|
||||
|
||||
/** Minimal markdown to safe HTML: everything is escaped first; only paragraphs, headings (as <h4>) and lists. */
|
||||
public static function changelogHtml( string $markdown ): string {
|
||||
$lines = preg_split( '/\r\n|\r|\n/', $markdown ) ?: array();
|
||||
$out = '';
|
||||
$list = false;
|
||||
$para = array();
|
||||
$flush = static function () use ( &$out, &$para ): void {
|
||||
if ( $para ) {
|
||||
$out .= '<p>' . implode( ' ', $para ) . '</p>';
|
||||
$para = array();
|
||||
}
|
||||
};
|
||||
foreach ( $lines as $line ) {
|
||||
$t = trim( $line );
|
||||
if ( 1 === preg_match( '/^[*\-+]\s+(.*)$/', $t, $m ) ) {
|
||||
$flush();
|
||||
if ( ! $list ) {
|
||||
$out .= '<ul>';
|
||||
$list = true;
|
||||
}
|
||||
$out .= '<li>' . self::esc( $m[1] ) . '</li>';
|
||||
continue;
|
||||
}
|
||||
if ( $list ) {
|
||||
$out .= '</ul>';
|
||||
$list = false;
|
||||
}
|
||||
if ( '' === $t ) {
|
||||
$flush();
|
||||
} elseif ( 1 === preg_match( '/^#{1,6}\s+(.*)$/', $t, $m ) ) {
|
||||
$flush();
|
||||
$out .= '<h4>' . self::esc( $m[1] ) . '</h4>';
|
||||
} else {
|
||||
$para[] = self::esc( $t );
|
||||
}
|
||||
}
|
||||
$flush();
|
||||
if ( $list ) {
|
||||
$out .= '</ul>';
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
private static function esc( string $s ): string {
|
||||
return htmlspecialchars( $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Update;
|
||||
|
||||
use StreamGoals\Admin\Admin;
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/**
|
||||
* Self-updater: checks the Gitea repo's latest release and feeds WordPress' plugin update machinery.
|
||||
* Every network/parse failure degrades to "no update known"; nothing here throws into WP screens.
|
||||
*/
|
||||
final class Updater {
|
||||
|
||||
public const SLUG = 'streamgoals-donate';
|
||||
public const BASE_URL = 'https://repo.anhonesthost.net';
|
||||
public const OWNER = 'wp-plugins';
|
||||
public const REPO = 'wp-donations';
|
||||
public const CACHE_KEY = 'sg_update_release';
|
||||
public const CACHE_OK = HOUR_IN_SECONDS;
|
||||
public const CACHE_FAIL = 10 * MINUTE_IN_SECONDS;
|
||||
public const TIMEOUT = 8;
|
||||
public const ACTION_CHECK = 'sg_update_check';
|
||||
|
||||
public static function register(): void {
|
||||
if ( ! self::enabled() ) {
|
||||
return;
|
||||
}
|
||||
add_filter( 'pre_set_site_transient_update_plugins', array( self::class, 'inject' ) );
|
||||
add_filter( 'plugins_api', array( self::class, 'pluginInfo' ), 10, 3 );
|
||||
add_filter( 'http_request_args', array( self::class, 'authorize' ), 10, 2 );
|
||||
add_action( 'upgrader_process_complete', array( self::class, 'afterUpgrade' ), 10, 2 );
|
||||
add_action( 'admin_post_' . self::ACTION_CHECK, array( self::class, 'handleCheck' ) );
|
||||
}
|
||||
|
||||
public static function enabled(): bool {
|
||||
return (bool) apply_filters( 'streamgoals_updates_enabled', true );
|
||||
}
|
||||
|
||||
/** @return array{base:string,owner:string,repo:string,host:string} */
|
||||
public static function repo(): array {
|
||||
$r = apply_filters( 'streamgoals_update_repo', array( 'base' => self::BASE_URL, 'owner' => self::OWNER, 'repo' => self::REPO ) );
|
||||
$r = is_array( $r ) ? $r : array();
|
||||
$base = rtrim( is_string( $r['base'] ?? null ) ? $r['base'] : self::BASE_URL, '/' );
|
||||
$host = parse_url( $base, PHP_URL_HOST );
|
||||
return array(
|
||||
'base' => $base,
|
||||
'owner' => is_string( $r['owner'] ?? null ) ? $r['owner'] : self::OWNER,
|
||||
'repo' => is_string( $r['repo'] ?? null ) ? $r['repo'] : self::REPO,
|
||||
'host' => is_string( $host ) ? strtolower( $host ) : '',
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached latest release (parsed) or null. Failures are cached briefly so WP never re-hits a broken endpoint.
|
||||
*
|
||||
* @return array{version:string,package:string,url:string,notes:string,published:string}|null
|
||||
*/
|
||||
public static function latest( bool $force = false ): ?array {
|
||||
try {
|
||||
if ( ! $force ) {
|
||||
$c = get_site_transient( self::CACHE_KEY );
|
||||
if ( is_array( $c ) && array_key_exists( 'release', $c ) ) {
|
||||
return is_array( $c['release'] ) ? $c['release'] : null;
|
||||
}
|
||||
}
|
||||
$release = self::fetch();
|
||||
set_site_transient( self::CACHE_KEY, array( 'release' => $release ), null === $release ? self::CACHE_FAIL : self::CACHE_OK );
|
||||
return $release;
|
||||
} catch ( \Throwable $e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static function clearCache(): void {
|
||||
delete_site_transient( self::CACHE_KEY );
|
||||
}
|
||||
|
||||
private static function fetch(): ?array {
|
||||
$repo = self::repo();
|
||||
if ( '' === $repo['host'] || 'https' !== strtolower( (string) parse_url( $repo['base'], PHP_URL_SCHEME ) ) ) {
|
||||
return null;
|
||||
}
|
||||
$url = $repo['base'] . '/api/v1/repos/' . rawurlencode( $repo['owner'] ) . '/' . rawurlencode( $repo['repo'] ) . '/releases/latest';
|
||||
$resp = wp_remote_get( $url, array( 'timeout' => self::TIMEOUT, 'redirection' => 2, 'headers' => array( 'Accept' => 'application/json' ) ) );
|
||||
if ( is_wp_error( $resp ) || 200 !== (int) wp_remote_retrieve_response_code( $resp ) ) {
|
||||
return null;
|
||||
}
|
||||
$data = json_decode( (string) wp_remote_retrieve_body( $resp ), true );
|
||||
return is_array( $data ) ? ReleaseParser::parse( $data, $repo['host'] ) : null;
|
||||
}
|
||||
|
||||
public static function pluginFile(): string {
|
||||
return plugin_basename( STREAMGOALS_FILE );
|
||||
}
|
||||
|
||||
private static function entry( array $rel ): object {
|
||||
$e = new \stdClass();
|
||||
$e->id = $rel['url'] ?: self::BASE_URL;
|
||||
$e->slug = self::SLUG;
|
||||
$e->plugin = self::pluginFile();
|
||||
$e->new_version = $rel['version'];
|
||||
$e->url = $rel['url'];
|
||||
$e->package = $rel['package'];
|
||||
$e->requires = '6.8';
|
||||
$e->requires_php = '8.1';
|
||||
return $e;
|
||||
}
|
||||
|
||||
public static function inject( mixed $transient ): mixed {
|
||||
try {
|
||||
if ( ! is_object( $transient ) ) {
|
||||
return $transient;
|
||||
}
|
||||
$rel = self::latest();
|
||||
$file = self::pluginFile();
|
||||
unset( $transient->response[ $file ], $transient->no_update[ $file ] );
|
||||
if ( null === $rel ) {
|
||||
return $transient;
|
||||
}
|
||||
$entry = self::entry( $rel );
|
||||
if ( ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ) {
|
||||
$transient->response = is_array( $transient->response ?? null ) ? $transient->response : array();
|
||||
$transient->response[ $file ] = $entry;
|
||||
} else {
|
||||
$entry->new_version = STREAMGOALS_VERSION;
|
||||
$transient->no_update = is_array( $transient->no_update ?? null ) ? $transient->no_update : array();
|
||||
$transient->no_update[ $file ] = $entry;
|
||||
}
|
||||
} catch ( \Throwable $e ) {
|
||||
// Never break the Updates screen.
|
||||
}
|
||||
return $transient;
|
||||
}
|
||||
|
||||
public static function pluginInfo( mixed $result, mixed $action = '', mixed $args = null ): mixed {
|
||||
try {
|
||||
if ( 'plugin_information' !== $action || ! is_object( $args ) || ( $args->slug ?? '' ) !== self::SLUG ) {
|
||||
return $result;
|
||||
}
|
||||
$rel = self::latest();
|
||||
if ( null === $rel ) {
|
||||
return $result;
|
||||
}
|
||||
$i = new \stdClass();
|
||||
$i->name = 'StreamGoals Donate';
|
||||
$i->slug = self::SLUG;
|
||||
$i->version = $rel['version'];
|
||||
$i->author = 'StreamGoals';
|
||||
$i->homepage = $rel['url'];
|
||||
$i->requires = '6.8';
|
||||
$i->requires_php = '8.1';
|
||||
$i->last_updated = $rel['published'];
|
||||
$i->download_link = $rel['package'];
|
||||
$i->sections = array(
|
||||
'description' => 'PayPal donations with multiple goals, fee coverage, and OBS stream overlays.',
|
||||
'changelog' => '' !== $rel['notes'] ? ReleaseParser::changelogHtml( $rel['notes'] ) : '<p>No release notes.</p>',
|
||||
);
|
||||
return $i;
|
||||
} catch ( \Throwable $e ) {
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
/** Adds the token ONLY for https requests to the configured Gitea host. */
|
||||
public static function authorize( mixed $args, mixed $url ): mixed {
|
||||
try {
|
||||
if ( ! is_array( $args ) || ! is_string( $url ) ) {
|
||||
return $args;
|
||||
}
|
||||
$token = trim( (string) Settings::get( 'update_token', '' ) );
|
||||
$host = self::repo()['host'];
|
||||
if ( '' === $token || ! ReleaseParser::isAllowedUrl( $url, $host ) ) {
|
||||
return $args;
|
||||
}
|
||||
$args['headers'] = is_array( $args['headers'] ?? null ) ? $args['headers'] : array();
|
||||
$args['headers']['Authorization'] = 'token ' . $token;
|
||||
} catch ( \Throwable $e ) {
|
||||
// Fall through without credentials.
|
||||
}
|
||||
return $args;
|
||||
}
|
||||
|
||||
public static function afterUpgrade( mixed $upgrader, mixed $options ): void {
|
||||
if ( is_array( $options ) && ( $options['type'] ?? '' ) === 'plugin' ) {
|
||||
self::clearCache();
|
||||
}
|
||||
}
|
||||
|
||||
public static function handleCheck(): void {
|
||||
Admin::guard( self::ACTION_CHECK );
|
||||
self::clearCache();
|
||||
delete_site_transient( 'update_plugins' );
|
||||
$rel = self::latest( true );
|
||||
$back = Admin::url( 'streamgoals-settings' );
|
||||
if ( null === $rel ) {
|
||||
Admin::redirect( $back, 'warning', 'Could not read the latest release. Check your connection and, if the update repository is private, the access token.' );
|
||||
}
|
||||
Admin::redirect( $back, 'success', ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ? 'Version ' . $rel['version'] . ' is available. See Dashboard > Updates.' : 'You are up to date.' );
|
||||
}
|
||||
}
|
||||
@@ -31,4 +31,5 @@ spl_autoload_register(
|
||||
);
|
||||
|
||||
register_activation_hook( __FILE__, array( \StreamGoals\Core\Installer::class, 'activate' ) );
|
||||
register_deactivation_hook( __FILE__, array( \StreamGoals\Core\Maintenance::class, 'unschedule' ) );
|
||||
add_action( 'plugins_loaded', array( \StreamGoals\Core\Plugin::class, 'boot' ) );
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\Csv;
|
||||
use StreamGoals\Admin\Format;
|
||||
use StreamGoals\Admin\Input;
|
||||
use StreamGoals\Admin\RuleConfig;
|
||||
use StreamGoals\Admin\Templates;
|
||||
|
||||
final class AdminLogicTest extends TestCase {
|
||||
|
||||
public function test_csv_escapes_formula_prefixes(): void {
|
||||
foreach ( array( '=1+1', '+1', '-1', '@SUM(A1)', "\tx", "\rx" ) as $v ) {
|
||||
$this->assertSame( "'" . $v, Csv::cell( $v ) );
|
||||
}
|
||||
$this->assertSame( 'hello', Csv::cell( 'hello' ) );
|
||||
$this->assertSame( '10.00', Csv::cell( '10.00' ) );
|
||||
$this->assertSame( '', Csv::cell( null ) );
|
||||
$this->assertSame( "\"a\",\"'=b\",\"say \"\"hi\"\"\"\r\n", Csv::line( array( 'a', '=b', 'say "hi"' ) ) );
|
||||
}
|
||||
|
||||
public function test_amount_parsing(): void {
|
||||
$this->assertSame( 100, Input::amountToMinor( '1', 'USD' ) );
|
||||
$this->assertSame( 100050, Input::amountToMinor( '$1,000.50', 'USD' ) );
|
||||
$this->assertSame( 500, Input::amountToMinor( '500', 'JPY' ) );
|
||||
$this->assertNull( Input::amountToMinor( '1.234', 'USD' ) );
|
||||
$this->assertNull( Input::amountToMinor( '-5', 'USD' ) );
|
||||
$this->assertNull( Input::amountToMinor( 'abc', 'USD' ) );
|
||||
$this->assertNull( Input::amountToMinor( '', 'USD' ) );
|
||||
$this->assertNull( Input::amountToMinor( array( '1' ), 'USD' ) );
|
||||
}
|
||||
|
||||
public function test_percent_and_misc_input(): void {
|
||||
$this->assertSame( 349, Input::percentToBps( '3.49' ) );
|
||||
$this->assertSame( 350, Input::percentToBps( '3.5%' ) );
|
||||
$this->assertSame( 0, Input::percentToBps( '0' ) );
|
||||
$this->assertNull( Input::percentToBps( '31' ) );
|
||||
$this->assertNull( Input::percentToBps( 'x' ) );
|
||||
$this->assertSame( "bad\nword", Input::words( " Bad\r\nword\nBAD" ) );
|
||||
$this->assertSame( 'big_donation', Input::slug( '!!!' ) );
|
||||
$this->assertSame( 'mega_win', Input::slug( 'Mega Win' ) );
|
||||
$this->assertTrue( Input::secretUnchanged( Input::maskSecret( 'abc' ) ) );
|
||||
$this->assertTrue( Input::secretUnchanged( '' ) );
|
||||
$this->assertFalse( Input::secretUnchanged( 'newsecret' ) );
|
||||
$this->assertSame( '', Input::maskSecret( '' ) );
|
||||
}
|
||||
|
||||
public function test_add_time_sanitize_uses_exact_config_keys(): void {
|
||||
$r = RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1.00', 'cap_minutes' => '10', 'max_total_minutes' => '' ), 'USD' );
|
||||
$this->assertSame( array(), $r['errors'] );
|
||||
$this->assertSame(
|
||||
array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'max_timer_seconds' => null, 'basis' => 'base' ),
|
||||
$r['config']
|
||||
);
|
||||
}
|
||||
|
||||
public function test_sanitize_validation_errors(): void {
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array(), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array( 'time_amount' => '0', 'time_unit' => 'minutes', 'unit_amount' => '1' ), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '0' ), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1', 'cap_minutes' => 'x' ), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'counter', array( 'step' => '1' ), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'bonus', array( 'min_amount' => '0' ), 'USD' )['errors'] );
|
||||
$this->assertNotEmpty( RuleConfig::sanitize( 'nope', array(), 'USD' )['errors'] );
|
||||
$this->assertNull( RuleConfig::sanitize( 'nope', array(), 'USD' )['config'] );
|
||||
}
|
||||
|
||||
public function test_counter_and_bonus_sanitize(): void {
|
||||
$c = RuleConfig::sanitize( 'counter', array( 'step' => '1', 'unit_amount' => '10', 'carry_over' => '1', 'label' => '<b>Pies</b>' ), 'USD' );
|
||||
$this->assertSame( array( 'step' => 1, 'per_minor' => 1000, 'carry_over' => true, 'basis' => 'base', 'label' => 'Pies' ), $c['config'] );
|
||||
$b = RuleConfig::sanitize( 'bonus', array( 'min_amount' => '50', 'event' => 'Big Donation', 'basis' => 'total' ), 'USD' );
|
||||
$this->assertSame( array( 'min_minor' => 5000, 'event' => 'big_donation', 'basis' => 'total' ), $b['config'] );
|
||||
}
|
||||
|
||||
public function test_summaries(): void {
|
||||
$this->assertSame( 'Adds 1 minute for every $1.00', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ), 'USD' ) );
|
||||
$this->assertStringContainsString( 'at most 10 minutes per donation', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600 ), 'USD' ) );
|
||||
$this->assertStringContainsString( 'Adds 1 to "Pies" for every $10.00', RuleConfig::summary( 'counter', array( 'step' => 1, 'per_minor' => 1000, 'label' => 'Pies', 'carry_over' => true ), 'USD' ) );
|
||||
$this->assertStringContainsString( '$50.00 or more', RuleConfig::summary( 'bonus', array( 'min_minor' => 5000, 'event' => 'big' ), 'USD' ) );
|
||||
$this->assertSame( '1 hour 1 minute 1 second', Format::duration( 3661 ) );
|
||||
}
|
||||
|
||||
public function test_preview_for_25_dollars(): void {
|
||||
$rules = array(
|
||||
array( 'type' => 'add_time', 'config' => array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ) ),
|
||||
array( 'type' => 'counter', 'config' => array( 'step' => 1, 'per_minor' => 1000, 'label' => 'Pies' ) ),
|
||||
array( 'type' => 'bonus', 'config' => array( 'min_minor' => 5000, 'event' => 'big' ) ),
|
||||
);
|
||||
$this->assertSame( array( 'Timer: +25 minutes', 'Pies: +2', 'Bonus "big" does not trigger' ), RuleConfig::preview( $rules, 2500, 'USD' ) );
|
||||
}
|
||||
|
||||
public function test_max_timer_validation_and_summary(): void {
|
||||
$base = array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1.00' );
|
||||
$this->assertNull( RuleConfig::sanitize( 'add_time', $base, 'USD' )['config']['max_timer_seconds'] );
|
||||
$this->assertNull( RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => ' ' ), 'USD' )['config']['max_timer_seconds'] );
|
||||
$this->assertSame( 86400, RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => '1440' ), 'USD' )['config']['max_timer_seconds'] );
|
||||
foreach ( array( '0', '-5', 'abc', '1.5' ) as $bad ) {
|
||||
$r = RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => $bad ), 'USD' );
|
||||
$this->assertNotEmpty( $r['errors'], $bad );
|
||||
$this->assertNull( $r['config'] );
|
||||
}
|
||||
$this->assertSame( 'Adds 1 minute for every $1.00, up to 1 day on the clock', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 86400 ), 'USD' ) );
|
||||
$this->assertSame( 'Adds 1 minute for every $1.00', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ), 'USD' ) );
|
||||
$this->assertSame( array( 'Timer: +25 minutes (the timer never goes above 1 hour)' ), RuleConfig::preview( array( array( 'type' => 'add_time', 'config' => array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 3600 ) ) ), 2500, 'USD' ) );
|
||||
}
|
||||
|
||||
public function test_form_roundtrip(): void {
|
||||
$cfg = array( 'seconds_per_unit' => 120, 'unit_minor' => 250, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'max_timer_seconds' => 86400, 'basis' => 'base' );
|
||||
$form = RuleConfig::toForm( 'add_time', $cfg, 'USD' );
|
||||
$back = RuleConfig::sanitize( 'add_time', $form, 'USD' );
|
||||
$this->assertSame( $cfg, $back['config'] );
|
||||
}
|
||||
|
||||
public function test_templates(): void {
|
||||
$t = Templates::build( 'subathon', 'USD', 100000 );
|
||||
$this->assertSame( 60, $t['rules'][0]['config']['seconds_per_unit'] );
|
||||
$this->assertSame( 100, $t['rules'][0]['config']['unit_minor'] );
|
||||
$c = Templates::build( 'counter', 'USD', 5000, 'Pies' );
|
||||
$this->assertSame( 1000, $c['rules'][0]['config']['per_minor'] );
|
||||
$this->assertSame( 'Pies', $c['goal']['title'] );
|
||||
$this->assertSame( 10, Templates::build( 'counter', 'JPY', 5000 )['rules'][0]['config']['per_minor'] );
|
||||
$this->assertSame( array(), Templates::build( 'simple', 'USD', 5000 )['rules'] );
|
||||
$this->assertFalse( Templates::exists( 'x' ) );
|
||||
}
|
||||
|
||||
public function test_donor_name_and_test_flag(): void {
|
||||
$this->assertSame( 'Anonymous', Format::donorName( array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ) );
|
||||
$this->assertSame( 'Anonymous', Format::donorName( array( 'is_anonymous' => 0, 'donor_name' => '' ) ) );
|
||||
$this->assertSame( 'Sam', Format::donorName( array( 'is_anonymous' => 0, 'donor_name' => 'Sam' ) ) );
|
||||
$this->assertTrue( Format::isTest( array( 'paypal_order_id' => 'TEST-abc' ) ) );
|
||||
$this->assertFalse( Format::isTest( array( 'paypal_order_id' => '5O1234' ) ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\Store;
|
||||
|
||||
/**
|
||||
* Regression: Store::rules() must return rules whose `config` is a decoded array, not the raw JSON string.
|
||||
* (A by-reference foreach over a cast temporary once discarded the decoding and crashed the Rules screen.)
|
||||
*/
|
||||
final class AdminStoreRulesTest extends TestCase {
|
||||
|
||||
private $previous;
|
||||
|
||||
protected function setUp(): void {
|
||||
if ( ! defined( 'ARRAY_A' ) ) {
|
||||
define( 'ARRAY_A', 'ARRAY_A' ); // WordPress constant; not loaded in plain PHPUnit
|
||||
}
|
||||
$this->previous = $GLOBALS['wpdb'] ?? null;
|
||||
$GLOBALS['wpdb'] = new class() {
|
||||
public string $prefix = 'wp_';
|
||||
public function prepare( string $q, ...$args ): string { return $q; }
|
||||
public function get_results( string $q, $output = null ): array {
|
||||
return array(
|
||||
array( 'id' => '1', 'goal_id' => '1', 'type' => 'add_time', 'config' => '{"seconds_per_unit":60,"unit_minor":100,"max_timer_seconds":5400}', 'enabled' => '1', 'sort' => '0' ),
|
||||
array( 'id' => '2', 'goal_id' => '1', 'type' => 'counter', 'config' => 'not json', 'enabled' => '0', 'sort' => '1' ),
|
||||
array( 'id' => '3', 'goal_id' => '1', 'type' => 'bonus', 'config' => '{"min_minor":5000}', 'enabled' => '1', 'sort' => '2' ),
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
$GLOBALS['wpdb'] = $this->previous;
|
||||
}
|
||||
|
||||
public function test_every_rule_config_is_a_decoded_array(): void {
|
||||
$rules = Store::rules( 1 );
|
||||
$this->assertCount( 3, $rules );
|
||||
foreach ( $rules as $r ) {
|
||||
$this->assertIsArray( $r['config'], 'rule ' . $r['id'] . ' config was not decoded' );
|
||||
}
|
||||
$this->assertSame( 5400, $rules[0]['config']['max_timer_seconds'] );
|
||||
$this->assertSame( array(), $rules[1]['config'], 'invalid JSON becomes an empty config, not a crash' );
|
||||
$this->assertSame( 5000, $rules[2]['config']['min_minor'] );
|
||||
}
|
||||
|
||||
public function test_rule_lookup_returns_decoded_config(): void {
|
||||
$r = Store::rule( 3, 1 );
|
||||
$this->assertIsArray( $r['config'] );
|
||||
$this->assertNull( Store::rule( 99, 1 ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Core\ClientIp;
|
||||
|
||||
final class ClientIpTest extends TestCase {
|
||||
|
||||
private const PROXY = '172.70.1.1';
|
||||
private const CLIENT = '203.0.113.9';
|
||||
|
||||
public function test_direct_mode_uses_remote_addr_and_ignores_headers(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4', 'HTTP_X_FORWARDED_FOR' => '5.6.7.8' );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_DIRECT ) );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv ) );
|
||||
}
|
||||
|
||||
public function test_cloudflare_mode_uses_cf_header(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_CLOUDFLARE ) );
|
||||
}
|
||||
|
||||
public function test_cloudflare_mode_without_header_falls_back_to_remote_addr(): void {
|
||||
$this->assertSame( self::PROXY, ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY ), ClientIp::MODE_CLOUDFLARE ) );
|
||||
}
|
||||
|
||||
public function test_invalid_header_values_are_ignored(): void {
|
||||
foreach ( array( 'not-an-ip', '999.1.1.1', '', '1.2.3.4, 5.6.7.8', '<script>', "1.2.3.4\r\nX: y" ) as $bad ) {
|
||||
$srv = array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_CF_CONNECTING_IP' => $bad );
|
||||
$this->assertSame( self::PROXY, ClientIp::resolve( $srv, ClientIp::MODE_CLOUDFLARE ), "accepted bad value: $bad" );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_x_real_ip_mode(): void {
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_X_REAL_IP' => self::CLIENT ), ClientIp::MODE_REAL_IP ) );
|
||||
}
|
||||
|
||||
public function test_forwarded_mode_takes_the_last_entry_not_the_spoofable_first(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_X_FORWARDED_FOR' => '6.6.6.6, ' . self::CLIENT );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_FORWARDED ) );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_X_FORWARDED_FOR' => self::CLIENT ), ClientIp::MODE_FORWARDED ) );
|
||||
}
|
||||
|
||||
public function test_ipv6_is_accepted(): void {
|
||||
$this->assertSame( '2001:db8::1', ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_CF_CONNECTING_IP' => '2001:db8::1' ), ClientIp::MODE_CLOUDFLARE ) );
|
||||
}
|
||||
|
||||
public function test_unknown_when_nothing_valid(): void {
|
||||
$this->assertSame( 'unknown', ClientIp::resolve( array(), ClientIp::MODE_CLOUDFLARE ) );
|
||||
$this->assertSame( 'unknown', ClientIp::resolve( array( 'REMOTE_ADDR' => 'garbage' ) ) );
|
||||
}
|
||||
|
||||
public function test_unrecognised_mode_behaves_like_direct(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4' );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, 'something_else' ) );
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ final class EngineToOverlayIntegrationTest extends TestCase {
|
||||
}
|
||||
public function counter( int $goalId ): array { return array( 'label' => 'Pies', 'value' => $this->s->getInt( $goalId, 'counter:2' ) ); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return array(); }
|
||||
public function bonusesFor( array $donationIds ): array { return array(); }
|
||||
} );
|
||||
|
||||
$d = new Donation( 7, 1, 2500, 0, 2500, 'USD' ); // $25 -> +25 min, counter +2
|
||||
@@ -53,4 +54,55 @@ final class EngineToOverlayIntegrationTest extends TestCase {
|
||||
$engine->reverseDonation( $d );
|
||||
$this->assertSame( 0, $svc->payload( 'counter', $now )['value'] );
|
||||
}
|
||||
|
||||
private function bonusOverlay( FakeEventStore $events, array $donations ): OverlayService {
|
||||
return new OverlayService( new class( $events, $donations ) implements OverlayDataSource {
|
||||
public function __construct( private FakeEventStore $ev, private array $rows ) {}
|
||||
public function activeGoal(): ?array { return array( 'id' => 1, 'title' => 'G', 'target_minor' => 5000, 'currency' => 'USD' ); }
|
||||
public function raisedMinor( array $goal ): int { return 0; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return $this->rows; }
|
||||
public function bonusesFor( array $donationIds ): array {
|
||||
$out = array();
|
||||
foreach ( $this->ev->events as $k => $e ) {
|
||||
[ , $did ] = array_map( 'intval', explode( ':', $k ) );
|
||||
if ( 1 === $e[0] && ! $e[1] && in_array( $did, $donationIds, true ) ) {
|
||||
$out[ $did ][] = 'big_donation';
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
} );
|
||||
}
|
||||
|
||||
public function test_bonus_over_threshold_visible_in_alerts_below_is_not_and_refund_removes(): void {
|
||||
$events = new FakeEventStore();
|
||||
$fired = array();
|
||||
$engine = new Engine(
|
||||
new FakeRuleStore( array( new RuleDef( 3, 1, 'bonus', array( 'min_minor' => 5000, 'event' => 'big_donation' ) ) ) ),
|
||||
$events,
|
||||
new FakeStateRepository(),
|
||||
null,
|
||||
function ( string $event, RuleDef $r, Donation $d, bool $rev ) use ( &$fired ): void {
|
||||
$fired[] = array( $event, $d->id, $rev );
|
||||
}
|
||||
);
|
||||
$big = new Donation( 10, 1, 5000, 0, 5000, 'USD' );
|
||||
$small = new Donation( 11, 1, 4999, 0, 4999, 'USD' );
|
||||
$engine->applyDonation( $big );
|
||||
$engine->applyDonation( $small );
|
||||
$this->assertSame( array( array( 'big_donation', 10, false ) ), $fired );
|
||||
|
||||
$row = static fn( int $id ): array => array( 'id' => $id, 'base_minor' => 5000, 'currency' => 'USD', 'donor_name' => 'A',
|
||||
'is_anonymous' => 0, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
|
||||
$svc = $this->bonusOverlay( $events, array( $row( 10 ), $row( 11 ) ) );
|
||||
$alerts = $svc->payload( 'alerts', 1, 0 )['alerts'];
|
||||
$this->assertSame( array( 'Big donation' ), $alerts[0]['bonuses'] );
|
||||
$this->assertSame( array(), $alerts[1]['bonuses'] );
|
||||
|
||||
$engine->reverseDonation( $big );
|
||||
$this->assertSame( array(), $svc->payload( 'alerts', 1, 0 )['alerts'][0]['bonuses'] );
|
||||
$this->assertSame( true, $fired[1][2] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Core\FeeCalculator;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\PayPal\OrderValidator;
|
||||
use StreamGoals\PayPal\ValidationException;
|
||||
|
||||
final class MinimumDonationTest extends TestCase {
|
||||
|
||||
private const NOW = 1800000000;
|
||||
|
||||
private function quote( string $amount, int $configuredMin, string $currency = 'USD' ): array {
|
||||
$goal = array( 'id' => 1, 'currency' => $currency, 'status' => 'active', 'starts_at' => null, 'ends_at' => null );
|
||||
$settings = array_merge( Settings::defaults(), array( 'min_donation_minor' => $configuredMin ) );
|
||||
return OrderValidator::quote( array( 'amount' => $amount ), $goal, $settings, new FeeCalculator( 349, 49 ), self::NOW );
|
||||
}
|
||||
|
||||
public function test_effective_min_never_below_hard_floor(): void {
|
||||
$this->assertSame( 100, Settings::effectiveMin( 0 ) );
|
||||
$this->assertSame( 100, Settings::effectiveMin( 1 ) );
|
||||
$this->assertSame( 100, Settings::effectiveMin( 99 ) );
|
||||
$this->assertSame( 500, Settings::effectiveMin( 500 ) );
|
||||
}
|
||||
|
||||
public function test_configured_zero_or_tiny_minimum_still_enforces_floor(): void {
|
||||
foreach ( array( 0, 1, 50 ) as $configured ) {
|
||||
try {
|
||||
$this->quote( '0.50', $configured );
|
||||
$this->fail( "0.50 accepted with configured min $configured" );
|
||||
} catch ( ValidationException $e ) {
|
||||
$this->assertSame( 'amount_too_small', $e->errorCode );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function test_exactly_the_floor_is_accepted(): void {
|
||||
$this->assertSame( 100, $this->quote( '1.00', 0 )['base_minor'] );
|
||||
$this->assertSame( 100, $this->quote( '1', 100 )['base_minor'] );
|
||||
}
|
||||
|
||||
public function test_higher_configured_minimum_wins_and_error_names_it(): void {
|
||||
$this->assertSame( 500, $this->quote( '5.00', 500 )['base_minor'] );
|
||||
try {
|
||||
$this->quote( '4.99', 500 );
|
||||
$this->fail( 'expected rejection' );
|
||||
} catch ( ValidationException $e ) {
|
||||
$this->assertSame( 'amount_too_small', $e->errorCode );
|
||||
$this->assertStringContainsString( '5.00 USD', $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_zero_and_negative_rejected(): void {
|
||||
foreach ( array( '0', '0.00', '-5' ) as $amt ) {
|
||||
try {
|
||||
$this->quote( $amt, 100 );
|
||||
$this->fail( "amount '$amt' was accepted" );
|
||||
} catch ( ValidationException $e ) {
|
||||
$this->assertContains( $e->errorCode, array( 'amount_too_small', 'invalid_amount' ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function test_fee_cover_does_not_change_the_floor_check(): void {
|
||||
// The floor applies to the base amount the streamer receives, not the fee-inflated total.
|
||||
$this->expectException( ValidationException::class );
|
||||
$goal = array( 'id' => 1, 'currency' => 'USD', 'status' => 'active', 'starts_at' => null, 'ends_at' => null );
|
||||
OrderValidator::quote( array( 'amount' => '0.60', 'cover_fees' => true ), $goal, Settings::defaults(), new FeeCalculator( 349, 49 ), self::NOW );
|
||||
}
|
||||
}
|
||||
@@ -96,6 +96,41 @@ final class OverlayPayloadsTest extends TestCase {
|
||||
$this->assertSame( Payloads::etag( $g ), Payloads::etag( $g ) );
|
||||
}
|
||||
|
||||
public function test_alert_bonuses_humanized_and_empty_when_none(): void {
|
||||
$out = Payloads::alerts( array( $this->don( 1, array( 'bonuses' => array( 'big_donation', 'mega-win' ) ) ), $this->don( 2 ) ), 0 );
|
||||
$this->assertSame( array( 'Big donation', 'Mega win' ), $out['alerts'][0]['bonuses'] );
|
||||
$this->assertSame( array(), $out['alerts'][1]['bonuses'] );
|
||||
}
|
||||
|
||||
public function test_alert_bonuses_sanitize_hostile_event(): void {
|
||||
$out = Payloads::alerts( array( $this->don( 1, array( 'bonuses' => array( '<img src=x onerror=alert(1)>', '"><script>', '<>', 42, 'big_donation', 'BIG_DONATION' ) ) ) ), 0 );
|
||||
$b = $out['alerts'][0]['bonuses'];
|
||||
$this->assertSame( 'Imgsrcxonerroralert1', $b[0] );
|
||||
foreach ( $b as $label ) {
|
||||
$this->assertMatchesRegularExpression( '/^[A-Za-z0-9 ]+$/', $label );
|
||||
}
|
||||
$this->assertSame( 1, count( array_keys( $b, 'Big donation', true ) ) ); // deduped
|
||||
}
|
||||
|
||||
public function test_bonuses_do_not_affect_masking_moderation_or_since(): void {
|
||||
$rows = array(
|
||||
$this->don( 1, array( 'bonuses' => array( 'big_donation' ) ) ),
|
||||
$this->don( 2, array( 'is_anonymous' => 1, 'donor_name' => 'Secret Sam', 'bonuses' => array( 'big_donation' ) ) ),
|
||||
$this->don( 3, array( 'moderation' => 'pending', 'bonuses' => array( 'big_donation' ) ) ),
|
||||
);
|
||||
$out = Payloads::alerts( $rows, 1 );
|
||||
$this->assertSame( array( 2 ), array_column( $out['alerts'], 'id' ) );
|
||||
$this->assertSame( 'Anonymous', $out['alerts'][0]['name'] );
|
||||
$this->assertStringNotContainsString( 'Secret Sam', json_encode( $out ) );
|
||||
$this->assertSame( array(), Payloads::alerts( $rows, null )['alerts'] );
|
||||
}
|
||||
|
||||
public function test_etag_changes_when_bonus_added(): void {
|
||||
$plain = Payloads::alerts( array( $this->don( 5 ) ), 0 );
|
||||
$bonus = Payloads::alerts( array( $this->don( 5, array( 'bonuses' => array( 'big_donation' ) ) ) ), 0 );
|
||||
$this->assertNotSame( Payloads::etag( $plain ), Payloads::etag( $bonus ) );
|
||||
}
|
||||
|
||||
public function test_style_sanitizes(): void {
|
||||
$s = Style::fromQuery( array( 'theme' => 'bogus', 'accent' => '#FF00AA', 'color' => 'red;}</style>', 'bg' => '11223344',
|
||||
'font' => 'x;}body{', 'scale' => '99' ) );
|
||||
@@ -114,6 +149,7 @@ final class OverlayPayloadsTest extends TestCase {
|
||||
public function raisedMinor( array $goal ): int { return 250; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return 'timer_ends_at' === $key ? '2000' : null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => 'Pies', 'value' => 4 ); }
|
||||
public function bonusesFor( array $donationIds ): array { return array( 3 => array( 'big_donation' ) ); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return array( array( 'id' => 3, 'base_minor' => 100, 'currency' => 'USD', 'donor_name' => 'Z', 'is_anonymous' => 1, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' ) ); }
|
||||
};
|
||||
$svc = new OverlayService( $src );
|
||||
@@ -121,6 +157,7 @@ final class OverlayPayloadsTest extends TestCase {
|
||||
$this->assertSame( 2000, $svc->payload( 'timer', 1500 )['ends_at'] );
|
||||
$this->assertSame( 4, $svc->payload( 'counter', 1 )['value'] );
|
||||
$this->assertSame( 'Anonymous', $svc->payload( 'alerts', 1, 0 )['alerts'][0]['name'] );
|
||||
$this->assertSame( array( 'Big donation' ), $svc->payload( 'alerts', 1, 0 )['alerts'][0]['bonuses'] );
|
||||
$this->assertNull( $svc->payload( 'nope', 1 ) );
|
||||
}
|
||||
}
|
||||
@@ -81,6 +81,88 @@ final class RulesEngineTest extends TestCase {
|
||||
$this->assertSame( 1000 + 100, $this->state->getInt( 1, 'timer_ends_at' ) );
|
||||
}
|
||||
|
||||
private function ends(): int {
|
||||
return $this->state->getInt( 1, 'timer_ends_at' );
|
||||
}
|
||||
|
||||
public function test_max_timer_clamps_and_records_actual_delta(): void {
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 1200 ) ) ) ); // now=1000
|
||||
$this->state->setInt( 1, 'timer_ends_at', 2000 ); // 1000s remaining
|
||||
$e->applyDonation( $this->d( 1, 1000 ) ); // wants +600, room 200
|
||||
$this->assertSame( 2200, $this->ends() );
|
||||
$this->assertSame( 200, $this->events->events['1:1'][0] );
|
||||
$this->assertSame( 200, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
}
|
||||
|
||||
public function test_max_timer_exactly_at_cap_adds_zero(): void {
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 1000 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 2000 );
|
||||
$e->applyDonation( $this->d( 1, 100 ) );
|
||||
$this->assertSame( 2000, $this->ends() );
|
||||
$this->assertSame( 0, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
}
|
||||
|
||||
public function test_max_timer_lowered_below_existing_timer_does_not_shorten(): void {
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 100 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 9000 );
|
||||
$e->applyDonation( $this->d( 1, 100 ) );
|
||||
$this->assertSame( 9000, $this->ends() );
|
||||
$this->assertSame( 0, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
}
|
||||
|
||||
public function test_uncapped_by_default_and_null(): void {
|
||||
foreach ( array( array(), array( 'max_timer_seconds' => null ) ) as $extra ) {
|
||||
$e = $this->engine( array( $this->timer( $extra ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 10000000 );
|
||||
$e->applyDonation( $this->d( 1, 100000 ) );
|
||||
$this->assertSame( 10000000 + 60000, $this->ends() );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_max_timer_with_other_caps_most_restrictive_wins(): void {
|
||||
// per-donation 50 is the tightest
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 500, 'cap_seconds_per_donation' => 50, 'max_total_seconds' => 400 ) ) ) );
|
||||
$e->applyDonation( $this->d( 1, 1000 ) );
|
||||
$this->assertSame( 1050, $this->ends() );
|
||||
// max_total tightest: 30 left of 40 total, clock has room
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 500, 'max_total_seconds' => 40 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_added:1', 10 );
|
||||
$e->applyDonation( $this->d( 1, 1000 ) );
|
||||
$this->assertSame( 1030, $this->ends() );
|
||||
$this->assertSame( 40, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
// clock cap tightest: only 20 of room
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 120, 'cap_seconds_per_donation' => 300, 'max_total_seconds' => 900 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 1100 );
|
||||
$e->applyDonation( $this->d( 1, 1000 ) );
|
||||
$this->assertSame( 1120, $this->ends() );
|
||||
$this->assertSame( 20, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
}
|
||||
|
||||
public function test_max_timer_with_expired_timer_starts_from_now(): void {
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 100 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 10 );
|
||||
$e->applyDonation( $this->d( 1, 1000 ) ); // wants 600
|
||||
$this->assertSame( 1100, $this->ends() );
|
||||
}
|
||||
|
||||
public function test_max_timer_replay_idempotent_and_reversal_uses_clamped_delta(): void {
|
||||
$e = $this->engine( array( $this->timer( array( 'max_timer_seconds' => 1200 ) ) ) );
|
||||
$this->state->setInt( 1, 'timer_ends_at', 2000 );
|
||||
$d = $this->d( 1, 1000 );
|
||||
$e->applyDonation( $d );
|
||||
$e->applyDonation( $d );
|
||||
$this->assertSame( 2200, $this->ends() );
|
||||
$e->reverseDonation( $d );
|
||||
$e->reverseDonation( $d );
|
||||
$this->assertSame( 2000, $this->ends() );
|
||||
$this->assertSame( 0, $this->state->getInt( 1, 'timer_added:1' ) );
|
||||
}
|
||||
|
||||
public function test_max_timer_invalid_value_rejected_by_rule(): void {
|
||||
$this->expectException( \InvalidArgumentException::class );
|
||||
\StreamGoals\Rules\AddTimeRule::fromConfig( array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 0 ) );
|
||||
}
|
||||
|
||||
public function test_reversal_undoes_and_is_not_double_applied(): void {
|
||||
$e = $this->engine( array( $this->timer(), $this->counter() ) );
|
||||
$d = $this->d( 10, 2500 );
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Update\ReleaseParser;
|
||||
|
||||
final class UpdateReleaseParserTest extends TestCase {
|
||||
|
||||
private const HOST = 'repo.anhonesthost.net';
|
||||
private const ZIP = 'https://repo.anhonesthost.net/wp-plugins/wp-donations/releases/download/2026.11.15-1941/streamgoals-donate.zip';
|
||||
|
||||
private function release( array $over = array() ): array {
|
||||
return array_merge(
|
||||
array(
|
||||
'tag_name' => '2026.11.15-1941',
|
||||
'draft' => false,
|
||||
'prerelease' => false,
|
||||
'body' => "## What's New\n\n* one\n* two",
|
||||
'html_url' => 'https://repo.anhonesthost.net/wp-plugins/wp-donations/releases/tag/2026.11.15-1941',
|
||||
'published_at' => '2026-11-15T19:41:00Z',
|
||||
'assets' => array( array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => self::ZIP ) ),
|
||||
),
|
||||
$over
|
||||
);
|
||||
}
|
||||
|
||||
public function test_valid_release(): void {
|
||||
$r = ReleaseParser::parse( $this->release(), self::HOST );
|
||||
$this->assertSame( '2026.11.15-1941', $r['version'] );
|
||||
$this->assertSame( self::ZIP, $r['package'] );
|
||||
$this->assertSame( '2026-11-15T19:41:00Z', $r['published'] );
|
||||
$this->assertStringContainsString( 'releases/tag', $r['url'] );
|
||||
}
|
||||
|
||||
public function test_draft_and_prerelease_ignored(): void {
|
||||
$this->assertNull( ReleaseParser::parse( $this->release( array( 'draft' => true ) ), self::HOST ) );
|
||||
$this->assertNull( ReleaseParser::parse( $this->release( array( 'prerelease' => true ) ), self::HOST ) );
|
||||
}
|
||||
|
||||
public function test_bad_tag(): void {
|
||||
foreach ( array( 'nightly', '2026.1.15-1941', '', null, array() ) as $t ) {
|
||||
$this->assertNull( ReleaseParser::parse( $this->release( array( 'tag_name' => $t ) ), self::HOST ) );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_v_prefix_and_semver(): void {
|
||||
$this->assertSame( '2026.11.15-1941', ReleaseParser::parse( $this->release( array( 'tag_name' => 'v2026.11.15-1941' ) ), self::HOST )['version'] );
|
||||
$this->assertSame( '1.2.3', ReleaseParser::parse( $this->release( array( 'tag_name' => 'v1.2.3' ) ), self::HOST )['version'] );
|
||||
}
|
||||
|
||||
public function test_wrong_host_and_non_https_rejected(): void {
|
||||
foreach ( array( 'https://evil.example/streamgoals-donate.zip', 'http://repo.anhonesthost.net/x.zip', 'https://repo.anhonesthost.net@evil.example/x.zip', 'https://repo.anhonesthost.net.evil.example/x.zip', '//repo.anhonesthost.net/x.zip' ) as $u ) {
|
||||
$rel = $this->release( array( 'assets' => array( array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => $u ) ) ) );
|
||||
$this->assertNull( ReleaseParser::parse( $rel, self::HOST ), $u );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_missing_asset(): void {
|
||||
$this->assertNull( ReleaseParser::parse( $this->release( array( 'assets' => array() ) ), self::HOST ) );
|
||||
$this->assertNull( ReleaseParser::parse( $this->release( array( 'assets' => array( array( 'name' => 'notes.txt', 'browser_download_url' => self::ZIP ) ) ) ), self::HOST ) );
|
||||
$this->assertNull( ReleaseParser::parse( array( 'tag_name' => '1.0.0' ), self::HOST ) );
|
||||
}
|
||||
|
||||
public function test_picks_right_asset(): void {
|
||||
$other = 'https://repo.anhonesthost.net/dl/other.zip';
|
||||
$a = array( array( 'name' => 'source.zip', 'browser_download_url' => $other ), array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => self::ZIP ) );
|
||||
$this->assertSame( self::ZIP, ReleaseParser::parse( $this->release( array( 'assets' => $a ) ), self::HOST )['package'] );
|
||||
$this->assertSame( $other, ReleaseParser::parse( $this->release( array( 'assets' => array( $a[0] ) ) ), self::HOST )['package'] );
|
||||
}
|
||||
|
||||
public function test_version_comparison(): void {
|
||||
$this->assertTrue( ReleaseParser::isNewer( '2026.11.15-1830', '2026.11.15-0930' ) );
|
||||
$this->assertFalse( ReleaseParser::isNewer( '2026.11.15-0930', '2026.11.15-1830' ) );
|
||||
$this->assertFalse( ReleaseParser::isNewer( '2026.11.15-0930', '2026.11.15-0930' ) );
|
||||
$this->assertTrue( ReleaseParser::isNewer( 'v2026.11.16-0001', '2026.11.15-2359' ) );
|
||||
$this->assertTrue( ReleaseParser::isNewer( '2026.11.15-1941', '0.1.0' ) );
|
||||
$this->assertFalse( ReleaseParser::isNewer( 'garbage', '0.1.0' ) );
|
||||
}
|
||||
|
||||
public function test_changelog_escapes_html(): void {
|
||||
$h = ReleaseParser::changelogHtml( "<script>alert(1)</script>\n\n* <b>bold</b> & \"q\"\n* two" );
|
||||
$this->assertStringNotContainsString( '<script', $h );
|
||||
$this->assertStringNotContainsString( '<b>', $h );
|
||||
$this->assertStringContainsString( '<script>', $h );
|
||||
$this->assertStringContainsString( '<ul><li><b>bold</b> & "q"</li><li>two</li></ul>', $h );
|
||||
}
|
||||
|
||||
public function test_changelog_paragraphs_and_headings(): void {
|
||||
$this->assertSame( '<h4>What's New</h4><p>a b</p><ul><li>x</li></ul>', ReleaseParser::changelogHtml( "## What's New\n\na\nb\n\n- x" ) );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user