Compare commits

...
Author SHA1 Message Date
shadowdaoandClaude Sonnet 5.5 afa768fa42 Overlays refresh themselves after updates; media URLs versioned; frameless (transparent) alerts
Test and Release / test (push) Successful in 1m17s
Test and Release / release (push) Successful in 5s
- Overlay\Build id (plugin version + admin epoch) in X-SG-Build; overlay.js reloads once on mismatch (loop-guarded); 'Refresh all overlays now'
- Media URLs carry ?v=<mtime>
- Alert option 'Frameless' (schema v5): no box so transparent PNG/GIF/WebP and VP9-alpha WebM show through; admin preview with checkerboard and ffmpeg help

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 13:41:18 -08:00
shadowdaoandClaude Sonnet 5.5 9249b80cb6 Donation form: non-refundable notice under the PayPal buttons (editable in Settings)
Test and Release / test (push) Successful in 1m16s
Test and Release / release (push) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 13:34:54 -08:00
shadowdaoandClaude Sonnet 5.5 cc5b9518e4 Mobile pass 2: reward checkmark spacing, admin table/cell/radio/slider sizing on phones, alert preview scaling
Test and Release / test (push) Successful in 1m19s
Test and Release / release (push) Successful in 4s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 13:34:15 -08:00
shadowdaoandClaude Sonnet 5.5 f6cd67ed0d README: alerts with media, tiers, end-at-target, Cloudflare
Test and Release / test (push) Successful in 1m26s
Test and Release / release (push) Successful in 9s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 13:28:57 -08:00
28 changed files with 366 additions and 17 deletions

No files matched your search

+31
View File
@@ -30,6 +30,11 @@ You need two values from PayPal: a **Client ID** and a **Secret**.
Start in **Sandbox**, make a test donation using a PayPal sandbox buyer account, then repeat the steps
with the Live credentials and switch the mode to Live in Settings.
### Behind Cloudflare?
Nothing to do: the plugin recognises Cloudflare automatically (by its published addresses) so each visitor is rate
limited separately. For another proxy, choose it in StreamGoals > Settings > Advanced; the panel there shows what your
server sees.
### Notes on fees and currency
- "Cover the processing fees" adds an estimate based on the rates in Settings (default: US domestic,
3.49% + $0.49). Your actual PayPal rate depends on your account, country and payment method.
@@ -51,6 +56,19 @@ with the Live credentials and switch the mode to Live in Settings.
form, as a **Rewards menu** overlay for OBS, and as a highlighted line in the donation alert. Triggered rewards land in a
**queue** on the Rewards screen so you can tick them off as you do them. Rewards count the donation amount, not the
optional fee cover, and must be at least your minimum donation.
- **Alerts with pictures, GIFs, videos and sounds:** StreamGoals > Alerts. Pick files from your WordPress Media Library
(PNG, JPEG, GIF, WebP, MP4, WebM for the picture/video; MP3, OGG, WAV for sound). Tie an alert to **a donation size**
("any donation of at least $5": the highest matching amount wins) or to **a reward** (a reward alert beats an amount
alert). Set the volume, how long a picture stays, and a message using `{name}`, `{amount}` and `{reward}`. In OBS media
plays automatically; in an ordinary browser tab click the page once before sound is allowed. Keep files small (videos
under about 25 MB). If a file is deleted the alert still shows, just without it.
- **Tiers (milestones):** on the Goals screen use **Tiers** to turn one goal into a ladder, for example $100 "Giveaway",
$250 "New microphone", $500 "24-hour stream". The goal bar shows the current tier and fills within it; unlocking a tier
shows a **TIER UNLOCKED** line in the alert and the bar moves on to the next one. The goal's final target is your highest
tier. The donation form shows "Next unlock: ... to go".
- **End at target:** tick "Close this goal to donations when the target is reached" on a goal. When the total reaches or
passes the target (for a tiered goal, the final tier) the goal closes and the donation page says so. Donations already
in checkout still go through. Use **Reopen** after raising the target.
- **Test:** "Send test donation" on the Overlays screen shows an alert without touching real totals.
## Privacy and moderation
@@ -61,6 +79,19 @@ with the Live credentials and switch the mode to Live in Settings.
- **Refunds and chargebacks are not tracked.** If you refund someone in PayPal, goal totals, timers and
counters are not adjusted.
## Transparent alerts
In StreamGoals > Alerts, tick **Frameless** on an alert to drop the dark box, border and glow so only your picture or
video shows. Transparency works with PNG, GIF and WebP pictures that have an alpha channel and with WebM (VP8/VP9)
videos made with alpha; MP4 (H.264) can never be transparent. To make a WebM with alpha:
`ffmpeg -i input.mov -c:v libvpx-vp9 -pix_fmt yuva420p -b:v 0 -crf 30 output.webm`. The name and bonus lines still
show under the media, outlined so they stay readable. The alert preview has a checkerboard/sample-scene backdrop.
## Overlays update themselves
An open OBS Browser Source never reloads on its own. Every overlay response now carries a build id (plugin version
plus a counter); when it differs from the one the page was loaded with, the overlay reloads itself once. Updating the
plugin does this automatically, and StreamGoals > Overlays > "Refresh all overlays now" does it on demand. Alert media
URLs also carry `?v=<file modified time>`, so replacing a file with the same name is picked up.
## Updates
New versions appear in WordPress automatically (Dashboard > Updates and the Plugins screen), checked against
this repository's releases. The repository is public, so no token is needed. (If you run a private fork, paste an
+6 -1
View File
@@ -47,7 +47,12 @@
/* Phones: wide tables scroll inside their own box instead of pushing the page; controls never exceed the card. */
@media (max-width: 782px) {
.sg-admin table.sg-table { display: block; max-width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; }
.sg-admin .sg-table th, .sg-admin .sg-table td { min-width: 4.5em; }
.sg-admin .sg-table th, .sg-admin .sg-table td { min-width: 3em; padding: 8px 6px; font-size: 13px; }
.sg-admin .sg-table code { overflow-wrap: anywhere; word-break: break-all; font-size: 12px; }
.sg-admin .sg-table td:last-child .button { margin: 0 4px 4px 0; }
.sg-admin .sg-card details > summary { min-height: 44px; display: flex; align-items: center; cursor: pointer; }
.sg-admin .sg-card label > input[type="radio"], .sg-admin .sg-card label > input[type="checkbox"] { margin-right: 6px; }
.sg-admin .sg-card p > label + .description, .sg-admin .sg-card p > label { display: inline-block; margin: 4px 0; }
.sg-admin select, .sg-admin input[type="text"], .sg-admin input[type="url"], .sg-admin input[type="number"], .sg-admin textarea { max-width: 100%; box-sizing: border-box; }
.sg-admin .sg-card { padding-left: 14px; padding-right: 14px; }
}
+20
View File
@@ -11,3 +11,23 @@
.sga-alert-head{font-weight:800;font-size:1.2em}
.sga-alert-head b{color:#22d3ee}
.sga-idle{color:#bbb;font-size:14px;align-self:center}
/* Phones: radio rows breathe, slider fills the width, preview stage scales and never overflows. */
@media (max-width:782px){
.sga-form label{display:inline-block;margin:6px 0;min-height:32px}
.sga-form input[type=range]{width:100%;min-height:32px}
.sga-stage{min-height:120px;padding:10px;font-size:16px;overflow:hidden;box-sizing:border-box;max-width:100%}
.sga-alert{box-sizing:border-box}
.sga-alert-media img,.sga-alert-media video{max-height:180px}
.sga-media .button{min-height:40px}
}
/* Frameless alerts: preview backdrops and card without the box */
.sga-bg-light{background:repeating-conic-gradient(#e8e8ee 0 25%,#fff 0 50%) 0 0/20px 20px;color:#111}
.sga-bg-scene{background:linear-gradient(135deg,#1e6f3c 0 33%,#c2410c 33% 66%,#1d4ed8 66%)}
.sga-alert.sga-frameless{background:none;border:0;padding:0}
.sga-frameless .sga-alert-head{text-shadow:0 0 3px #000,0 0 6px #000,0 1px 4px #000}
.sga-bg-light .sga-frameless .sga-alert-head{text-shadow:0 0 3px #fff,0 0 6px #fff;color:#111}
.sga-howto{margin-top:8px}
.sga-howto pre{overflow-x:auto;max-width:100%;padding:8px;background:#f0f0f1}
.sga-bg-pick{margin-left:12px}
+6 -1
View File
@@ -110,7 +110,8 @@
var vals = { name: 'Alex', amount: money( amt || 500 ), reward: reward };
var msg = render( form.elements.message.value, vals );
var card = el( 'div', 'sga-alert' );
var frameless = !! ( visUrl && form.elements.frameless && form.elements.frameless.checked );
var card = el( 'div', 'sga-alert' + ( frameless ? ' sga-frameless' : '' ) );
var isVideo = /^video\//.test( visMime ), video = null;
if ( visUrl ) {
var box = el( 'div', 'sga-alert-media' );
@@ -145,6 +146,10 @@
timers.push( setTimeout( end, dur ) );
}
}
/* Preview backdrop: dark / light checkerboard or a busy "scene" so transparency is visible. */
var bgSel = document.getElementById( 'sga-bg' );
function setBg() { stage.className = 'sga-stage' + ( bgSel && bgSel.value !== 'dark' ? ' sga-bg-' + bgSel.value : '' ); }
if ( bgSel ) { bgSel.addEventListener( 'change', setBg ); }
playBtn.addEventListener( 'click', play );
stage.appendChild( el( 'span', 'sga-idle', 'Press "Play preview".' ) );
}() );
+4
View File
@@ -38,3 +38,7 @@
.sg-donate .sg-next-unlock{margin:0 0 .9rem;padding:.5rem .75rem;border:1px solid rgba(128,128,128,.5);border-left-width:4px;border-radius:.4rem;font-weight:600;line-height:1.4;overflow-wrap:anywhere}
.sg-donate .sg-next-unlock[hidden]{display:none}
.sg-donate .sg-presets button.sg-action{padding-right:2.2em}
.sg-donate .sg-presets.sg-actions{padding:0 5px}
.sg-donate .sg-notice{margin:.6rem 0 0;font-size:.9em;line-height:1.4;opacity:.85;overflow-wrap:anywhere}
+1
View File
@@ -121,6 +121,7 @@
root.appendChild(row([total]));
root.appendChild(status); // messages sit above the PayPal buttons, next to the form fields
root.appendChild(buttons);
if (C.notice) { root.appendChild(el('p', { 'class': 'sg-notice', text: String(C.notice) })); } // e.g. "Donations are non-refundable." right where the donor pays
function say(text, cls) { status.textContent = text || ''; status.className = 'sg-msg' + (cls ? ' ' + cls : ''); }
function amountStr() { return amount.value.trim().replace(',', '.'); }
+10
View File
@@ -59,3 +59,13 @@ body.sg-offline #sg-root{opacity:.6}
@keyframes sg-tier-pop{0%{transform:scale(1)}30%{transform:scale(1.06)}100%{transform:scale(1)}}
@keyframes sg-tier-glow{0%,100%{box-shadow:0 0 0 transparent}50%{box-shadow:0 0 1em #f59e0b,0 0 2em var(--sg-accent2)}}
@media (prefers-reduced-motion:reduce){.sg-card.sg-tier-up{animation:none;box-shadow:0 0 .8em #f59e0b}}
/* Frameless alerts (transparent PNG/GIF/WebP/WebM): no box, border or glow; media fits the window; text gets an outline. */
.sg-alert.sg-frameless{background:none;border:0;box-shadow:none;padding:0;max-height:100%;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;min-height:0}
.sg-alert.sg-frameless.sg-bonus{border:0;animation:sg-in .6s cubic-bezier(.22,1,.36,1) both}
.sg-alert.sg-frameless.sg-bonus.sg-out,.sg-alert.sg-frameless.sg-out{animation:sg-out .5s ease-in both}
.sg-frameless .sg-alert-media{flex:0 1 auto;min-height:0;max-width:100%;max-height:100%;margin-bottom:.2em;overflow:hidden}
.sg-frameless .sg-alert-media img,.sg-frameless .sg-alert-media video{max-width:100%;max-height:calc(100vh - 9em);width:auto;height:auto;object-fit:contain;border-radius:0;background:transparent}
.sg-frameless .sg-alert-head,.sg-frameless .sg-alert-msg,.sg-frameless .sg-bonus-line{text-shadow:0 0 .06em #000,0 0 .12em #000,0 0 .2em #000,0 .04em .3em #000,.04em 0 0 #000,-.04em 0 0 #000,0 .04em 0 #000,0 -.04em 0 #000}
.sg-theme-light .sg-frameless .sg-alert-head,.sg-theme-light .sg-frameless .sg-alert-msg{text-shadow:0 0 .06em #fff,0 0 .12em #fff,0 0 .2em #fff,.04em 0 0 #fff,-.04em 0 0 #fff,0 .04em 0 #fff,0 -.04em 0 #fff}
@media (prefers-reduced-motion:reduce){.sg-alert.sg-frameless,.sg-alert.sg-frameless.sg-out,.sg-alert.sg-frameless.sg-bonus,.sg-alert.sg-frameless.sg-bonus.sg-out{animation:none;box-shadow:none}}
+31 -1
View File
@@ -5,6 +5,7 @@
var endpoint = body.getAttribute('data-endpoint');
var poll = Math.max(1000, parseInt(body.getAttribute('data-poll'), 10) || 2500);
var root = document.getElementById('sg-root');
var build = body.getAttribute('data-build') || '';
var etag = null, failures = 0, skew = 0, timerState = null;
var queue = [], showing = false;
@@ -151,7 +152,7 @@
if (!v && !s && !msg) return null;
var vol = Number(m.volume); if (!isFinite(vol)) vol = 80;
var dur = Number(m.duration_ms); if (!isFinite(dur) || dur <= 0) dur = DEFAULT_HOLD;
return { visual: v, sound: s, volume: Math.max(0, Math.min(100, vol)) / 100, duration: Math.max(1000, Math.min(60000, dur)), message: msg };
return { frameless: !!(v && m.frameless === true), visual: v, sound: s, volume: Math.max(0, Math.min(100, vol)) / 100, duration: Math.max(1000, Math.min(60000, dur)), message: msg };
}
// Loads visual + sound before the card appears (no flash of an empty frame). Anything that fails or takes
// longer than MEDIA_TIMEOUT is dropped, so the alert falls back to text and the queue never stalls.
@@ -212,6 +213,7 @@
box.appendChild(vis);
card.appendChild(box);
card.classList.add('sg-has-media');
if (m && m.frameless) card.classList.add('sg-frameless');
}
if (m && m.message) {
head.textContent = m.message;
@@ -364,6 +366,33 @@
var delay = failures ? Math.min(15000, poll * Math.pow(2, Math.min(failures, 3))) : poll;
setTimeout(tick, delay);
}
// Self-refresh: every overlay response carries the current build id (plugin version + admin epoch) in X-SG-Build.
// A different value than the one this page was rendered with means the page is stale (OBS never reloads a
// running source after an update), so reload once. Guard: at most one reload per build per 30 s, remembered in
// sessionStorage, or in a module flag when storage is blocked. Applies to 200 and 304 responses alike.
var RELOAD_GUARD_MS = 30000, reloadTried = {};
// sessionStorage first; if it is blocked, window.name (which also survives a reload) carries the marker, so a
// blocked-storage source cannot reload in a loop. The module-level reloadTried only covers one page life.
function readGuard(key) {
try { return JSON.parse(sessionStorage.getItem(key) || 'null'); } catch (e) { /* fall through */ }
try { var m = /(?:^|;)sg_reload=([^;]*)/.exec(window.name || ''); return m ? JSON.parse(decodeURIComponent(m[1])) : null; } catch (e2) { return null; }
}
function writeGuard(key, v) {
try { sessionStorage.setItem(key, JSON.stringify(v)); return; } catch (e) { /* fall through */ }
try { window.name = (window.name || '').replace(/(?:^|;)sg_reload=[^;]*/, '') + ';sg_reload=' + encodeURIComponent(JSON.stringify(v)); } catch (e2) { /* module flag only */ }
}
function checkBuild(r) {
var b = null;
try { b = r.headers.get('X-SG-Build'); } catch (e) { return false; }
if (!b || !build || b === build) return false;
var now = Date.now(), key = 'sg_overlay_reload', last = readGuard(key);
var seen = last && last.b === b ? Number(last.t) : 0;
if (reloadTried[b] && reloadTried[b] > seen) seen = reloadTried[b];
if (seen && now - seen < RELOAD_GUARD_MS && now >= seen) return false;
reloadTried[b] = now;
writeGuard(key, { b: b, t: now });
try { location.reload(); return true; } catch (e3) { return false; }
}
function tick() {
var ctrl = typeof AbortController === 'function' ? new AbortController() : null;
var to = ctrl ? setTimeout(function () { ctrl.abort(); }, 8000) : 0;
@@ -372,6 +401,7 @@
fetch(url(), { headers: headers, cache: 'no-store', signal: ctrl ? ctrl.signal : undefined })
.then(function (r) {
clearTimeout(to);
if (checkBuild(r)) return null;
if (r.status === 304) return null;
if (!r.ok) throw new Error('http ' + r.status);
var et = r.headers.get('ETag');
+1
View File
@@ -40,6 +40,7 @@ final class Admin {
'sg_test_donation' => array( OverlaysPage::class, 'handleTestDonation' ),
'sg_delete_tests' => array( OverlaysPage::class, 'handleDeleteTests' ),
'sg_regen_token' => array( OverlaysPage::class, 'handleRegenerate' ),
'sg_refresh_overlays' => array( OverlaysPage::class, 'handleRefreshAll' ),
'sg_settings_save' => array( SettingsPage::class, 'handleSave' ),
);
+4 -1
View File
@@ -178,6 +178,9 @@ final class AlertsPage {
echo '</select><p class="description">A reward alert beats an amount alert. Only rewards that are turned on can be picked.</p></td></tr>';
self::mediaField( 'visual_id', 'Picture, GIF or video', 'visual', (int) $val( 'visual_id', 0 ), 'PNG, JPEG, GIF, WebP, MP4 or WebM. Optional. Under 25 MB works best; big videos can slow OBS down.' );
self::mediaField( 'sound_id', 'Sound', 'sound', (int) $val( 'sound_id', 0 ), 'MP3, OGG or WAV. Optional. If you also pick a video, the video is muted and this sound plays instead.' );
echo '<tr><th scope="row">Frameless</th><td><label><input type="checkbox" name="frameless" value="1" id="sga_frameless"' . checked( ! empty( $d['frameless'] ), true, false ) . '> Show the picture/video without the alert box (for transparent PNG, GIF, WebP or WebM files)</label>';
echo '<p class="description">Normally the alert sits in a dark rounded box. Tick this to remove the box, border and glow so only your picture or video shows, with the see-through parts showing your stream underneath. Transparency works with <strong>PNG, GIF and WebP</strong> pictures and <strong>WebM</strong> videos made with transparency. <strong>MP4 never supports transparency</strong>, so an MP4 always shows a solid picture. The name and bonus lines still appear under the media, with an outline so they stay readable on any scene. Only applies when you picked a picture or video.</p>';
echo '<details class="sga-howto"><summary>How do I make a transparent video?</summary><p>Export your animation with an alpha channel (a "transparent background"), then convert it to WebM with <a href="https://ffmpeg.org/" target="_blank" rel="noopener noreferrer">ffmpeg</a>:</p><pre><code>ffmpeg -i input.mov -c:v libvpx-vp9 -pix_fmt yuva420p -b:v 0 -crf 30 -an output.webm</code></pre><p>Replace <code>input.mov</code> with your file (a ProRes 4444 .mov or a PNG sequence both work). Use <code>-an</code> to drop audio (pick a separate sound above instead) or remove it to keep the clip\'s own sound. Then upload <code>output.webm</code> to your Media Library. Use the preview below to check it: the checkerboard shows through the transparent parts.</p></details></td></tr>';
echo '<tr><th scope="row"><label for="sga_volume">Volume</label></th><td><input type="range" min="0" max="100" id="sga_volume" name="volume" value="' . (int) $val( 'volume', 80 ) . '"> <output id="sga_volume_out">' . (int) $val( 'volume', 80 ) . '</output>%</td></tr>';
echo '<tr><th scope="row"><label for="sga_duration">How long a picture stays</label></th><td><input type="number" min="1" max="60" step="1" id="sga_duration" name="duration" class="small-text" value="' . esc_attr( (string) (int) round( (int) $val( 'duration_ms', 6000 ) / 1000 ) ) . '"> seconds<p class="description">1 to 60. Videos play to the end instead, for at most 30 seconds.</p></td></tr>';
echo '<tr><th scope="row"><label for="sga_message">Message</label></th><td><input type="text" maxlength="255" id="sga_message" name="message" class="large-text" value="' . esc_attr( (string) $val( 'message' ) ) . '"><p class="description">Optional. Use {name}, {amount} and {reward}, for example "{name} just sent {amount}!". Leave empty for the normal text ("Name donated $5.00").</p></td></tr>';
@@ -186,7 +189,7 @@ final class AlertsPage {
echo '<div class="sg-card"><h3>Preview</h3>';
echo '<p class="description">This is how the alert will look on stream. Press the button to play it (browsers only allow sound after you click).</p>';
echo '<p><button type="button" class="button" id="sga-play">Play preview</button></p>';
echo '<p><button type="button" class="button" id="sga-play">Play preview</button> <label class="sga-bg-pick">Preview background <select id="sga-bg"><option value="dark">Dark checkerboard</option><option value="light">Light checkerboard</option><option value="scene">Sample scene</option></select></label></p>';
echo '<div id="sga-stage" class="sga-stage" aria-live="polite"></div>';
echo '<script type="application/json" id="sga-data">' . wp_json_encode( $data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . '</script></div>';
echo '<p><button class="button button-primary">' . ( $d ? 'Save alert' : 'Add alert' ) . '</button> <a class="button" href="' . esc_url( self::url() ) . '">Cancel</a></p></form>';
+12
View File
@@ -4,6 +4,7 @@ declare( strict_types=1 );
namespace StreamGoals\Admin;
use StreamGoals\Core\Settings;
use StreamGoals\Overlay\Build;
use StreamGoals\Overlay\Style;
use StreamGoals\Rest\OverlayController;
@@ -73,6 +74,11 @@ final class OverlaysPage {
self::urlList( true );
echo '</div>';
echo '<div class="sg-card"><h2>Refresh overlays</h2>';
Admin::form( 'sg_refresh_overlays', array(), 'sg-inline' );
echo '<button type="submit" class="button">Refresh all overlays now</button></form>';
echo '<p class="description">Reloads every open OBS source. Done automatically after a plugin update.</p></div>';
echo '<div class="sg-card"><h2>Send a test donation</h2>';
echo '<p>Shows a fake donation on the <strong>Donation alerts</strong> overlay so you can check your OBS setup. Open the alerts preview above (or have OBS running) first, then press the button; the alert appears within a few seconds.</p>';
echo '<p class="description"><strong>How tests are kept out of your numbers:</strong> test donations are not attached to any goal, so they never count towards raised totals, timers or counters. They are excluded from the CSV export, and marked <em>TEST</em> in the Donations list. Test donations are kept in the database until you delete them below.</p>';
@@ -105,6 +111,12 @@ final class OverlaysPage {
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', $n . ' test donation(s) deleted.' );
}
public static function handleRefreshAll(): void {
Admin::guard( 'sg_refresh_overlays' );
Build::bump();
Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', 'All open overlays will reload within a few seconds.' );
}
public static function handleRegenerate(): void {
Admin::guard( 'sg_regen_token' );
Settings::update( array( 'overlay_token' => bin2hex( random_bytes( 16 ) ) ) );
+2
View File
@@ -34,6 +34,7 @@ final class SettingsPage {
}
echo '</select><p class="description">One currency for the whole site. It applies to goals you create from now on; existing goals keep their currency. Check the fixed fee below after changing it.</p></td></tr>';
echo '<tr><th scope="row"><label for="sg_min">Minimum donation (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_min" name="min_donation" class="small-text" inputmode="decimal" value="' . esc_attr( Format::decimal( \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ), $cur ) ) . '"> <span class="description">At least ' . esc_html( Format::money( \StreamGoals\Core\Settings::HARD_MIN_MINOR, $cur ) ) . '. Visitors cannot donate less than this.</span></td></tr>';
echo '<tr><th scope="row"><label for="sg_notice">Notice under the donation form</label></th><td><input type="text" id="sg_notice" name="donation_notice" class="large-text" maxlength="200" value="' . esc_attr( (string) $s['donation_notice'] ) . '"><p class="description">Shown right under the PayPal buttons so donors see it before paying. Plain text, up to 200 characters. The default says donations are non-refundable. Leave it empty to hide the notice.</p></td></tr>';
echo '<tr><th scope="row"><label for="sg_len">Longest message</label></th><td><input type="number" id="sg_len" name="message_max_length" min="0" max="500" class="small-text" value="' . (int) $s['message_max_length'] . '"> characters <span class="description">(0 to 500; 0 = no messages)</span></td></tr>';
echo '<tr><th scope="row">Names</th><td><fieldset>';
foreach ( self::POLICIES as $k => $l ) {
@@ -147,6 +148,7 @@ final class SettingsPage {
}
$upd['funding_card'] = ! empty( $post['funding_card'] );
$upd['funding_paylater'] = ! empty( $post['funding_paylater'] );
$upd['donation_notice'] = Input::text( $post['donation_notice'] ?? '', 200 );
$upd['moderate_messages'] = ! empty( $post['moderate_messages'] );
$upd['profanity_filter'] = ! empty( $post['profanity_filter'] );
$upd['profanity_use_builtin'] = ! empty( $post['profanity_use_builtin'] );
+12 -4
View File
@@ -13,8 +13,8 @@ final class AlertMedia {
* @param array<string,mixed> $row Donation row (goal_id, base_minor).
* @param array<int,array<string,mixed>> $defs Raw alert definitions.
* @param array<int,array{action_id:int,amount_minor:int,title:string}> $triggered Rewards this donation triggered.
* @param callable(int):?array{url:string,mime:string} $attachment
* @return array{visual:?array{type:string,url:string},sound:?array{url:string},volume:int,duration_ms:int,message:?string}|null
* @param callable(int):?array{url:string,mime:string,v?:int,modified?:string} $attachment
* @return array{visual:?array{type:string,url:string},sound:?array{url:string},volume:int,duration_ms:int,message:?string,frameless:bool}|null
*/
public static function build( array $row, string $name, string $amountDisplay, array $defs, array $triggered, callable $attachment ): ?array {
if ( ! $defs ) {
@@ -36,13 +36,15 @@ final class AlertMedia {
/** @return array<string,mixed>|null */
public static function fromDef( array $def, string $name, string $amountDisplay, array $triggered, callable $attachment ): ?array {
$visual = null;
$visual = null;
$frameless = false;
$vid = (int) ( $def['visual_id'] ?? 0 );
if ( $vid > 0 ) {
$a = self::lookup( $attachment, $vid );
$type = $a ? Media::visualType( $a['mime'] ) : null;
if ( $a && $type ) {
$visual = array( 'type' => $type, 'url' => $a['url'] );
$frameless = ! empty( $def['frameless'] );
}
}
$sound = null;
@@ -81,6 +83,7 @@ final class AlertMedia {
'volume' => Media::clampVolume( $def['volume'] ?? 80 ),
'duration_ms' => $duration,
'message' => '' === $msg ? null : $msg,
'frameless' => $frameless,
);
}
@@ -95,6 +98,11 @@ final class AlertMedia {
return null;
}
$url = Media::safeUrl( $a['url'] ?? null );
return null === $url ? null : array( 'url' => $url, 'mime' => (string) $a['mime'] );
if ( null === $url ) {
return null;
}
// Cache-bust suffix from server-side data only (file mtime / post_modified_gmt supplied by the lookup).
$versioned = Media::safeUrl( Media::withVersion( $url, (int) ( $a['v'] ?? 0 ), isset( $a['modified'] ) && is_string( $a['modified'] ) ? $a['modified'] : null ) );
return array( 'url' => $versioned ?? $url, 'mime' => (string) $a['mime'] );
}
}
+7
View File
@@ -99,6 +99,7 @@ final class DefInput {
if ( null === $sort ) {
return $fail( 'The sort order must be a whole number from 0 to 99999.' );
}
$frameless = self::checkbox( $post['frameless'] ?? null ) ? 1 : 0;
return array(
'data' => array(
'goal_id' => $goal,
@@ -113,12 +114,18 @@ final class DefInput {
'duration_ms' => $dur,
'message' => $message,
'sort' => $sort,
'frameless' => $frameless,
),
'error' => null,
'warnings' => $warnings,
);
}
/** HTML checkbox: present with a truthy value = on; absent or anything odd = off. */
public static function checkbox( mixed $v ): bool {
return is_scalar( $v ) && in_array( strtolower( trim( (string) $v ) ), array( '1', 'on', 'true', 'yes' ), true );
}
/** @param string[] $warnings */
private static function sizeWarning( array $a, string $what, bool $video, array &$warnings ): void {
if ( (int) ( $a['size'] ?? 0 ) > Media::WARN_BYTES ) {
+4 -3
View File
@@ -31,6 +31,7 @@ final class DefRepository {
'volume' => (int) ( $r['volume'] ?? 80 ),
'duration_ms' => (int) ( $r['duration_ms'] ?? 6000 ),
'message' => (string) ( $r['message'] ?? '' ),
'frameless' => (int) ( $r['frameless'] ?? 0 ) ? 1 : 0,
'enabled' => (int) ( $r['enabled'] ?? 0 ),
'sort' => (int) ( $r['sort'] ?? 0 ),
'created_at' => (string) ( $r['created_at'] ?? '' ),
@@ -57,13 +58,13 @@ final class DefRepository {
private const COLS = array(
'goal_id' => '%d', 'trigger_type' => '%s', 'min_minor' => '%d', 'action_id' => '%d', 'title' => '%s', 'visual_id' => '%d',
'visual_type' => '%s', 'sound_id' => '%d', 'volume' => '%d', 'duration_ms' => '%d', 'message' => '%s', 'sort' => '%d',
'visual_type' => '%s', 'sound_id' => '%d', 'volume' => '%d', 'duration_ms' => '%d', 'message' => '%s', 'sort' => '%d', 'frameless' => '%d',
);
public function create( array $d ): int {
$row = array();
foreach ( self::COLS as $k => $f ) {
$row[ $k ] = $d[ $k ];
$row[ $k ] = $d[ $k ] ?? ( '%d' === $f ? 0 : '' );
}
$row['enabled'] = 1;
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
@@ -74,7 +75,7 @@ final class DefRepository {
public function update( int $id, array $d ): void {
$row = array();
foreach ( self::COLS as $k => $f ) {
$row[ $k ] = $d[ $k ];
$row[ $k ] = $d[ $k ] ?? ( '%d' === $f ? 0 : '' );
}
$this->db->update( $this->t(), $row, array( 'id' => $id ), array_values( self::COLS ), array( '%d' ) );
}
+18
View File
@@ -66,6 +66,24 @@ final class Media {
return is_numeric( $v ) ? max( 0, min( 100, (int) $v ) ) : $default;
}
/**
* Appends ?v=<timestamp> so a replaced file with the same name is fetched again. The timestamp comes from the
* server (file mtime, else the attachment's post_modified_gmt), never from input. Unknown time = URL unchanged.
*/
public static function withVersion( string $url, int $fileMtime, ?string $postModifiedGmt = null ): string {
$v = $fileMtime;
if ( $v <= 0 && null !== $postModifiedGmt && preg_match( '/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $postModifiedGmt ) ) {
$t = strtotime( $postModifiedGmt . ' UTC' );
$v = false === $t ? 0 : $t;
}
if ( $v <= 0 || str_contains( $url, '#' ) ) {
return $url;
}
$base = preg_replace( '/([?&])v=[^&]*(&|$)/', '$1', $url ) ?? $url;
$base = rtrim( $base, '?&' );
return $base . ( str_contains( $base, '?' ) ? '&' : '?' ) . 'v=' . $v;
}
/** Only plain http(s) URLs are ever handed to the overlay. */
public static function safeUrl( mixed $url ): ?string {
if ( ! is_string( $url ) || '' === $url || strlen( $url ) > 2000 || preg_match( '/[\x00-\x20\x7F"\'<>\\\\]/', $url ) ) {
+2 -1
View File
@@ -8,7 +8,7 @@ namespace StreamGoals\Core;
*/
final class Installer {
public const DB_VERSION = '4';
public const DB_VERSION = '5';
public static function activate(): void {
self::install_schema();
@@ -138,6 +138,7 @@ final class Installer {
message VARCHAR(255) NOT NULL DEFAULT '',
enabled TINYINT(1) NOT NULL DEFAULT 1,
sort INT NOT NULL DEFAULT 0,
frameless TINYINT(1) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL,
PRIMARY KEY (id),
KEY goal_enabled (goal_id,enabled)
+1
View File
@@ -34,6 +34,7 @@ final class Settings {
'profanity_words' => '', // streamer's extra words, one per line
'message_max_length' => 200,
'min_donation_minor' => 100,
'donation_notice' => 'Donations are non-refundable.', // shown under the donation form; empty hides it
'overlay_token' => '',
'visitor_ip_header' => 'auto', // auto | '' (direct) | cloudflare | real_ip | forwarded (see Core\ClientIp)
'funding_paylater' => false, // show PayPal "Pay Later" button
+1 -1
View File
@@ -20,7 +20,7 @@ interface AlertMediaSource {
/**
* Server-side attachment lookup (the only place media URLs come from). Null when it is gone.
*
* @return array{url:string,mime:string}|null
* @return array{url:string,mime:string,v?:int,modified?:string}|null (v = file mtime, modified = post_modified_gmt; used only for the ?v= cache-bust suffix)
*/
public function attachment( int $id ): ?array;
}
+44
View File
@@ -0,0 +1,44 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Overlay;
/**
* Overlay build id: plugin version + a manual "epoch". The overlay page embeds it, every overlay REST response
* repeats it in a header, and a page that sees a different value reloads itself (OBS never does that on its own).
*/
final class Build {
public const HEADER = 'X-SG-Build';
public const OPTION = 'sg_overlay_epoch';
/** Pure: the build id string for a version and epoch. Only [A-Za-z0-9._-] survive, so it is header- and attribute-safe. */
public static function id( string $version, mixed $epoch ): string {
$v = preg_replace( '/[^A-Za-z0-9._-]/', '', $version ) ?? '';
return ( '' === $v ? '0' : $v ) . '-' . self::epochInt( $epoch );
}
/** Pure: stored option value (anything) to a non-negative integer. */
public static function epochInt( mixed $raw ): int {
return ( is_int( $raw ) || ( is_string( $raw ) && ctype_digit( $raw ) && strlen( $raw ) < 15 ) ) ? max( 0, (int) $raw ) : 0;
}
/** Pure: the epoch after a bump. Strictly increasing, never lower than the clock so a deleted option cannot repeat an old value. */
public static function nextEpoch( mixed $current, int $now ): int {
return max( self::epochInt( $current ) + 1, $now );
}
/** Pure: response headers carrying the build id (merged into the existing ones; ETag semantics untouched). */
public static function headers( string $build ): array {
return array( self::HEADER => $build );
}
public static function current(): string {
return self::id( defined( 'STREAMGOALS_VERSION' ) ? (string) STREAMGOALS_VERSION : '', get_option( self::OPTION, 0 ) );
}
/** Reloads every open overlay at its next poll. */
public static function bump(): void {
update_option( self::OPTION, self::nextEpoch( get_option( self::OPTION, 0 ), time() ), false );
}
}
+1 -1
View File
@@ -74,7 +74,7 @@ final class Router {
<title>StreamGoals overlay</title>
<link rel="stylesheet" href="<?php echo $asset( 'overlay.css' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>">
</head>
<body class="sg-theme-<?php echo esc_attr( $style['theme'] ); ?> sg-w-<?php echo esc_attr( $widget ); ?>" data-widget="<?php echo esc_attr( $widget ); ?>" data-endpoint="<?php echo esc_url( $endpoint ); ?>" data-poll="2500">
<body class="sg-theme-<?php echo esc_attr( $style['theme'] ); ?> sg-w-<?php echo esc_attr( $widget ); ?>" data-widget="<?php echo esc_attr( $widget ); ?>" data-endpoint="<?php echo esc_url( $endpoint ); ?>" data-poll="2500" data-build="<?php echo esc_attr( Build::current() ); ?>">
<main id="sg-root" aria-live="polite"></main>
<script src="<?php echo $asset( 'overlay.js' ); // phpcs:ignore WordPress.Security.EscapeOutput ?>"></script>
</body>
+4 -2
View File
@@ -6,7 +6,7 @@ namespace StreamGoals\Overlay;
/** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource, TiersSource {
/** @var array<int,?array{url:string,mime:string}> */
/** @var array<int,?array{url:string,mime:string,v:int,modified:string}> */
private array $attachments = array();
private function t( string $name ): string {
@@ -160,7 +160,9 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
$mime = (string) get_post_mime_type( $id );
$url = wp_get_attachment_url( $id );
if ( \StreamGoals\Alerts\Media::isAllowed( $mime ) && is_string( $url ) && '' !== $url ) {
$out = array( 'url' => $url, 'mime' => $mime );
$path = get_attached_file( $id );
$mtime = ( is_string( $path ) && is_file( $path ) ) ? (int) @filemtime( $path ) : 0;
$out = array( 'url' => $url, 'mime' => $mime, 'v' => $mtime, 'modified' => (string) get_post_field( 'post_modified_gmt', $id ) );
}
}
return $this->attachments[ $id ] = $out;
+1
View File
@@ -188,6 +188,7 @@ final class DonateController {
'policy' => (string) $s['anonymity_policy'],
'minMinor' => \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ),
'messageMax' => min( 500, (int) $s['message_max_length'] ),
'notice' => (string) ( $s['donation_notice'] ?? '' ),
'disableFunding' => array_values( array_filter( array( empty( $s['funding_paylater'] ) ? 'paylater' : '', empty( $s['funding_card'] ) ? 'card' : '' ) ) ),
'goals' => $goals,
'i18n' => array(
+2 -1
View File
@@ -4,6 +4,7 @@ declare( strict_types=1 );
namespace StreamGoals\Rest;
use StreamGoals\Core\Settings;
use StreamGoals\Overlay\Build;
use StreamGoals\Overlay\OverlayService;
use StreamGoals\Overlay\Payloads;
use StreamGoals\Overlay\Router;
@@ -56,7 +57,7 @@ final class OverlayController {
}
$etag = Payloads::etag( $payload, $service->etagSalt( (string) $req['widget'] ) );
$headers = array( 'ETag' => $etag, 'Cache-Control' => 'private, max-age=1, must-revalidate', 'X-Robots-Tag' => 'noindex' );
$headers = array( 'ETag' => $etag, 'Cache-Control' => 'private, max-age=1, must-revalidate', 'X-Robots-Tag' => 'noindex' ) + Build::headers( Build::current() );
$inm = (string) $req->get_header( 'if_none_match' );
if ( '' !== $inm && in_array( $etag, array_map( 'trim', explode( ',', str_replace( 'W/', '', $inm ) ) ), true ) ) {
$res = new \WP_REST_Response( null, 304 );
+10
View File
@@ -103,4 +103,14 @@ final class AlertDefInputTest extends TestCase {
$this->assertStringNotContainsString( '<', $this->run_( $this->post( array( 'title' => '<script>x</script>Hi', 'message' => '<b>hi</b>' ) ) )['data']['title'] );
$this->assertStringNotContainsString( '<', $this->run_( $this->post( array( 'message' => '<b>hi</b>{name}' ) ) )['data']['message'] );
}
public function test_frameless_checkbox_parsing_defaults_off(): void {
$this->assertSame( 0, $this->run_( $this->post() )['data']['frameless'] );
foreach ( array( '1', 'on', 1, true, 'true' ) as $on ) {
$this->assertSame( 1, $this->run_( $this->post( array( 'frameless' => $on ) ) )['data']['frameless'], 'on: ' . var_export( $on, true ) );
}
foreach ( array( '0', '', 'off', array( '1' ), 'banana' ) as $off ) {
$this->assertSame( 0, $this->run_( $this->post( array( 'frameless' => $off ) ) )['data']['frameless'], 'off: ' . var_export( $off, true ) );
}
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Admin\Input;
use StreamGoals\Core\Settings;
final class DonationNoticeTest extends TestCase {
public function test_default_notice_says_donations_are_non_refundable(): void {
$d = Settings::defaults();
$this->assertArrayHasKey( 'donation_notice', $d );
$this->assertStringContainsString( 'non-refundable', strtolower( (string) $d['donation_notice'] ) );
}
public function test_admin_input_is_plain_text_and_length_capped(): void {
$this->assertSame( 'No refunds, sorry.', Input::text( ' No refunds, sorry. ', 200 ) );
$this->assertStringNotContainsString( '<', Input::text( '<script>alert(1)</script><b>Hi</b>', 200 ), 'no markup survives (and it is rendered as text anyway)' );
$this->assertStringNotContainsString( '<', Input::text( '<b>Bold</b> <i>text</i>', 200 ) );
$this->assertSame( 200, strlen( Input::text( str_repeat( 'a', 500 ), 200 ) ) );
$this->assertSame( '', Input::text( "\x00\x1F", 200 ) );
}
public function test_form_script_renders_the_notice_with_textcontent_only(): void {
$js = (string) file_get_contents( dirname( __DIR__, 2 ) . '/assets/donate/donate.js' );
$this->assertMatchesRegularExpression( '/if \(C\.notice\).*sg-notice.*text: String\(C\.notice\)/s', $js, 'notice must be rendered as text, never HTML' );
$this->assertStringNotContainsString( 'innerHTML', $js );
}
public function test_form_config_passes_the_notice_through(): void {
$php = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Rest/DonateController.php' );
$this->assertStringContainsString( "'notice' => (string) ( \$s['donation_notice'] ?? '' )", $php );
}
}
+19
View File
@@ -47,6 +47,7 @@ final class OverlayAlertMediaTest extends TestCase {
'volume' => 60,
'duration_ms' => 7000,
'message' => 'Al gave $25.00',
'frameless' => false,
), $m );
}
@@ -169,4 +170,22 @@ final class OverlayAlertMediaTest extends TestCase {
Payloads::alerts( array( $this->row( 1, array( 'is_anonymous' => 1 ) ), $this->row( 2, array( 'moderation' => 'rejected' ) ) ), null, 10, true, $cb );
$this->assertSame( array( array( 1, 'Anonymous', '$25.00' ) ), $seen );
}
public function test_frameless_passes_through_only_with_a_visual(): void {
$this->assertTrue( $this->build( $this->def( 1, array( 'frameless' => 1 ) ) )['frameless'] );
$this->assertFalse( $this->build( $this->def( 1, array( 'frameless' => 0 ) ) )['frameless'] );
$this->assertFalse( $this->build( $this->def( 1, array( 'frameless' => 1, 'visual_id' => 0, 'message' => 'hi' ) ) )['frameless'], 'no visual, nothing to unframe' );
$this->assertFalse( $this->build( $this->def( 1, array( 'frameless' => 1, 'visual_id' => 13 ) ) )['frameless'], 'rejected media never unframes' );
}
public function test_media_url_gets_version_suffix_from_server_data_only(): void {
$files = array( 10 => array( 'url' => 'https://cdn.test/a.png', 'mime' => 'image/png', 'v' => 1700000000 ), 11 => array( 'url' => 'https://cdn.test/a.png?x=1', 'mime' => 'image/png', 'modified' => '2024-01-02 03:04:05' ) );
$get = static fn( int $id ): ?array => $files[ $id ] ?? null;
$m = AlertMedia::fromDef( $this->def( 1, array( 'sound_id' => 0 ) ), 'Al', '$1', array(), $get );
$this->assertSame( 'https://cdn.test/a.png?v=1700000000', $m['visual']['url'] );
$m = AlertMedia::fromDef( $this->def( 1, array( 'visual_id' => 11, 'sound_id' => 0 ) ), 'Al', '$1', array(), $get );
$this->assertSame( 'https://cdn.test/a.png?x=1&v=' . strtotime( '2024-01-02 03:04:05 UTC' ), $m['visual']['url'] );
$row = $this->row( 1, array( 'media' => array( 'visual' => array( 'type' => 'image', 'url' => 'https://evil.test/z.png' ) ) ) );
$this->assertNotSame( 'https://evil.test/z.png', $this->build( $this->def( 1 ), $row )['visual']['url'] );
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Alerts\Media;
use StreamGoals\Overlay\Build;
final class OverlayBuildTest extends TestCase {
public function test_build_id_combines_version_and_epoch_and_is_safe(): void {
$this->assertSame( '0.1.0-0', Build::id( '0.1.0', false ) );
$this->assertSame( '0.1.0-7', Build::id( '0.1.0', '7' ) );
$this->assertSame( '1.2x-0', Build::id( '1.2"<x>', 'abc' ), 'junk characters are stripped, junk epoch is 0' );
$this->assertSame( '0-0', Build::id( '', null ) );
$this->assertNotSame( Build::id( '0.1.0', 1 ), Build::id( '0.1.1', 1 ) );
$this->assertNotSame( Build::id( '0.1.0', 1 ), Build::id( '0.1.0', 2 ) );
}
public function test_headers_carry_only_the_build_and_never_touch_the_etag(): void {
$this->assertSame( array( 'X-SG-Build' => '0.1.0-3' ), Build::headers( '0.1.0-3' ) );
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Rest/OverlayController.php' );
$this->assertStringContainsString( 'Build::headers( Build::current() )', $src );
$this->assertStringContainsString( 'Payloads::etag( $payload, $service->etagSalt(', $src, 'ETag is still computed from the payload only' );
}
public function test_epoch_bump_rules(): void {
$this->assertSame( 1000, Build::nextEpoch( 0, 1000 ) );
$this->assertSame( 1000, Build::nextEpoch( false, 1000 ) );
$this->assertSame( 1000, Build::nextEpoch( '999', 1000 ) );
$this->assertSame( 2001, Build::nextEpoch( 2000, 1000 ), 'strictly increasing even if the clock went back' );
$this->assertSame( 1000, Build::nextEpoch( '-5', 1000 ) );
$this->assertSame( 1000, Build::nextEpoch( array( 9 ), 1000 ) );
$this->assertSame( 0, Build::epochInt( 1.5 ) );
$this->assertSame( 0, Build::epochInt( '99999999999999999999' ) );
}
public function test_refresh_handler_is_guarded_registered_and_option_is_not_autoloaded(): void {
$root = dirname( __DIR__, 2 ) . '/includes/';
$page = (string) file_get_contents( $root . 'Admin/OverlaysPage.php' );
$start = strpos( $page, 'function handleRefreshAll' );
$this->assertNotFalse( $start );
$this->assertStringContainsString( "Admin::guard( 'sg_refresh_overlays' )", substr( $page, $start, 200 ) );
$this->assertStringContainsString( "'sg_refresh_overlays' => array( OverlaysPage::class, 'handleRefreshAll' )", (string) file_get_contents( $root . 'Admin/Admin.php' ) );
$this->assertStringContainsString( 'Reloads every open OBS source. Done automatically after a plugin update.', $page );
$this->assertStringContainsString( ', false );', substr( (string) file_get_contents( $root . 'Overlay/Build.php' ), (int) strpos( (string) file_get_contents( $root . 'Overlay/Build.php' ), 'update_option' ) ) );
$this->assertStringContainsString( 'data-build=', (string) file_get_contents( $root . 'Overlay/Router.php' ) );
}
public function test_media_version_suffix_builder(): void {
$this->assertSame( 'https://x.test/a.png?v=123', Media::withVersion( 'https://x.test/a.png', 123 ) );
$this->assertSame( 'https://x.test/a.png?q=1&v=123', Media::withVersion( 'https://x.test/a.png?q=1', 123 ) );
$this->assertSame( 'https://x.test/a.png?v=123', Media::withVersion( 'https://x.test/a.png?v=5', 123 ), 'replaces an old v' );
$this->assertSame( 'https://x.test/a.png?q=1&v=123', Media::withVersion( 'https://x.test/a.png?v=5&q=1', 123 ) );
$this->assertSame( 'https://x.test/a.png?v=' . strtotime( '2024-05-06 07:08:09 UTC' ), Media::withVersion( 'https://x.test/a.png', 0, '2024-05-06 07:08:09' ), 'falls back to post_modified_gmt' );
$this->assertSame( 'https://x.test/a.png?v=50', Media::withVersion( 'https://x.test/a.png', 50, '2024-05-06 07:08:09' ), 'file mtime wins' );
$this->assertSame( 'https://x.test/a.png', Media::withVersion( 'https://x.test/a.png', 0, '0000-00-00 00:00:00x' ) );
$this->assertSame( 'https://x.test/a.png', Media::withVersion( 'https://x.test/a.png', 0 ) );
$this->assertSame( 'https://x.test/a.png#f', Media::withVersion( 'https://x.test/a.png#f', 9 ) );
$this->assertNotNull( Media::safeUrl( Media::withVersion( 'https://x.test/a.png', 123 ) ) );
}
public function test_installer_has_frameless_column_and_version_five(): void {
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
$this->assertSame( 1, preg_match( "/DB_VERSION = '(\\d+)'/", $src, $m ) );
$this->assertGreaterThanOrEqual( 5, (int) $m[1] );
$this->assertMatchesRegularExpression( '/CREATE TABLE \{\$p\}alert_defs \([^;]*frameless TINYINT\(1\) NOT NULL DEFAULT 0,/s', $src );
}
public function test_overlay_js_checks_build_on_every_response_including_304(): void {
$js = (string) file_get_contents( dirname( __DIR__, 2 ) . '/assets/overlay/overlay.js' );
$this->assertLessThan( strpos( $js, 'r.status === 304' ), strpos( $js, 'checkBuild(r)' ), 'build is compared before the 304 shortcut' );
$this->assertStringContainsString( 'X-SG-Build', $js );
}
}