Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
971a4ac482 | ||
|
|
96bae1cbf9 | ||
|
|
0180aacd72 | ||
|
|
c6520b761a | ||
|
|
55d1c34b1f | ||
|
|
565ee0a352 | ||
|
|
a41ad107a1 | ||
|
|
f19ed5c5f2 | ||
|
|
9f33ea7975 | ||
|
|
b80010f422 |
No files matched your search
@@ -30,6 +30,23 @@ 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.
|
||||
|
||||
### Going live
|
||||
1. In the PayPal developer dashboard (Apps & Credentials), switch to **Live** and create a Live app (type Merchant).
|
||||
2. In StreamGoals > Settings, paste the Live **Client ID** and **Secret**.
|
||||
3. Switch the mode to **Live**, then **Save and test connection**.
|
||||
4. Webhook: the plugin registers it for you when the test succeeds (changing mode or credentials clears the old one, so
|
||||
the Live webhook is created fresh). It points to `https://YOUR-SITE/wp-json/streamgoals/v1/webhook` and listens for
|
||||
`PAYMENT.CAPTURE.COMPLETED`. If the message says it could not register it (needs a public https site, or a webhook
|
||||
for that address already exists), add it by hand in your Live app in the PayPal dashboard with that URL and that event.
|
||||
5. Make a small real donation and check it appears under Donations and on your goal, then refund yourself in PayPal if you like.
|
||||
6. Set the visitor IP header if needed (Settings > Advanced; Cloudflare is detected automatically).
|
||||
7. Add the overlays in OBS as Browser Sources (StreamGoals > Overlays).
|
||||
8. Turn on two-factor authentication for both your PayPal and WordPress accounts.
|
||||
|
||||
### Chargebacks and refunds
|
||||
Chargebacks and refunds are handled manually in PayPal. The plugin does not track them, so totals, timers, counters
|
||||
and tiers are not reduced. If you need to compensate, adjust the goal or its rules yourself by editing them.
|
||||
|
||||
### 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
|
||||
@@ -45,6 +62,12 @@ server sees.
|
||||
|
||||
## Using it
|
||||
- **Donation page:** add the shortcode `[streamgoals_donate]` to a page (or `[streamgoals_donate goal="ID"]` to pin one goal).
|
||||
- `show_progress="no"` hides the progress bar above the form (default `yes`; also accepts `true/false/1/0`).
|
||||
- `[streamgoals_progress]` (or `[streamgoals_progress goal="ID"]`) shows just the progress bar, e.g. in a sidebar or a stream page.
|
||||
The bar shows raised / target, the percentage and, for tiered goals, the current tier and its target, using the same
|
||||
numbers as the overlay (base amounts, or including fees only if the goal counts fees). It refreshes after a donation and
|
||||
about every 30 seconds while the tab is visible, from the public `GET /wp-json/streamgoals/v1/progress?goal=ID` (totals only).
|
||||
The first render is server-side HTML, so page caches and Cloudflare are fine.
|
||||
- **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.
|
||||
@@ -69,6 +92,9 @@ server sees.
|
||||
- **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.
|
||||
- **Replay an alert:** StreamGoals > Donations, then **Replay** next to a donation. The alerts overlay shows it again
|
||||
within a few seconds (it must be open at the time; a request expires after a minute). Totals, timers, counters,
|
||||
rewards and tiers are not applied again. Held or rejected donations cannot be replayed.
|
||||
- **Test:** "Send test donation" on the Overlays screen shows an alert without touching real totals.
|
||||
|
||||
## Privacy and moderation
|
||||
@@ -99,6 +125,9 @@ plus a counter); when it differs from the one the page was loaded with, the over
|
||||
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.
|
||||
|
||||
Overlay data, overlay pages, the progress bar and the fee preview are never page-cached (the plugin tells LiteSpeed
|
||||
Cache to skip them). With another caching plugin or CDN, exclude `/wp-json/streamgoals/` and `/streamgoals-overlay/`.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
.sg-donate{max-width:min(100%,440px);font:inherit}
|
||||
.sg-donate{width:100%;max-width:min(100%,440px);margin-left:auto;margin-right:auto;box-sizing:border-box;text-align:left;font:inherit}
|
||||
.sg-donate .sg-row{margin:0 0 .9rem}
|
||||
.sg-donate label{display:block;font-weight:600;margin-bottom:.25rem}
|
||||
.sg-donate label.sg-inline{display:flex;gap:.5rem;align-items:center;font-weight:400}
|
||||
@@ -42,3 +42,18 @@
|
||||
.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}
|
||||
|
||||
/* Progress bar (theme-neutral: inherits text colour; fill uses currentColor so it follows the theme). */
|
||||
.sg-donate .sg-progress{margin:0 0 .9rem;max-width:100%;box-sizing:border-box}
|
||||
.sg-donate .sg-progress-bar{position:relative;height:14px;border:1px solid rgba(128,128,128,.45);border-radius:999px;background:rgba(128,128,128,.22);overflow:hidden;box-shadow:inset 0 1px 2px rgba(0,0,0,.18)}
|
||||
.sg-donate .sg-progress-fill{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--sg-accent,#7c5cff),var(--sg-accent2,#22d3ee));min-width:0;border-radius:999px;transition:width .6s ease}
|
||||
.sg-donate .sg-progress-text{display:flex;flex-wrap:wrap;justify-content:space-between;gap:.25rem .75rem;margin-top:.35rem;font-weight:600;line-height:1.4;overflow-wrap:anywhere}
|
||||
.sg-donate .sg-progress-tier,.sg-donate .sg-progress-done{margin:.25rem 0 0;font-size:.9em;line-height:1.4;overflow-wrap:anywhere}
|
||||
.sg-donate .sg-progress-done{font-weight:700}
|
||||
.sg-donate .sg-progress [hidden]{display:none}
|
||||
.sg-donate.sg-progress-only .sg-progress{margin-bottom:0}
|
||||
@media (prefers-reduced-motion:reduce){.sg-donate .sg-progress-fill{transition:none}}
|
||||
.sg-donate .sg-thanks{margin:.5rem 0 0;padding:1.1rem 1rem;border:1px solid rgba(26,127,55,.55);border-left-width:4px;border-radius:.4rem;text-align:center}
|
||||
.sg-donate .sg-thanks:focus{outline:0}
|
||||
.sg-donate .sg-thanks-title{margin:0;font-size:1.15em;font-weight:700;line-height:1.4;overflow-wrap:anywhere}
|
||||
.sg-donate [hidden]{display:none!important}
|
||||
+75
-6
@@ -1,9 +1,12 @@
|
||||
/* StreamGoals donate form (vanilla JS). Config comes from window.StreamGoalsDonate. */
|
||||
(function () {
|
||||
'use strict';
|
||||
var C = window.StreamGoalsDonate;
|
||||
if (!C) { return; }
|
||||
var T = C.i18n || {};
|
||||
var C = window.StreamGoalsDonate; // donate form config (absent on pages with only [streamgoals_progress])
|
||||
var PC = window.StreamGoalsProgress; // progress bar config (rest url, labels, poll interval)
|
||||
if (!C && !PC) { return; }
|
||||
var T = (C && C.i18n) || {};
|
||||
var PT = (PC && PC.i18n) || {};
|
||||
var REST = (C && C.restUrl) || (PC && PC.restUrl) || '';
|
||||
var sdkPromise = null, sdkCurrency = null;
|
||||
|
||||
function el(tag, attrs, children) {
|
||||
@@ -18,7 +21,7 @@
|
||||
|
||||
function api(path, opts) {
|
||||
opts = opts || {};
|
||||
return fetch(C.restUrl + path, {
|
||||
return fetch(REST + path, {
|
||||
method: opts.method || 'GET',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: opts.body ? JSON.stringify(opts.body) : undefined,
|
||||
@@ -62,12 +65,60 @@
|
||||
}
|
||||
function sprintf1(tpl, v) { return String(tpl || '%s').replace('%s', v); }
|
||||
|
||||
/* ---- Progress bar: server renders the markup, this keeps it fresh (same code for form and [streamgoals_progress]). ---- */
|
||||
function tpl(str, a, b) {
|
||||
return String(str || '').replace('%1$s', function () { return a; }).replace('%2$s', function () { return b; });
|
||||
}
|
||||
function applyBar(box, p) {
|
||||
if (!box || !p) { return; }
|
||||
var pct = Math.max(0, Math.min(100, parseInt(p.percent, 10) || 0));
|
||||
var bar = box.querySelector('.sg-progress-bar');
|
||||
var of = tpl(PT['of'] || '%1$s / %2$s', p.raised_display, p.target_display);
|
||||
box.setAttribute('data-goal', String(p.goal_id));
|
||||
box.className = 'sg-progress' + (p.reached ? ' sg-progress-reached' : '');
|
||||
bar.setAttribute('aria-valuenow', String(pct));
|
||||
bar.setAttribute('aria-valuetext', p.reached ? (PT.reached || '') : of + ' (' + pct + '%)');
|
||||
bar.setAttribute('aria-label', String(PT.label || '%s').replace('%s', function () { return p.title; }));
|
||||
bar.firstChild.style.width = ((pct < 2 && (parseInt(p.raised_minor, 10) || 0) > 0) ? 2 : pct) + '%';
|
||||
box.querySelector('.sg-progress-amounts').textContent = of;
|
||||
box.querySelector('.sg-progress-pct').textContent = pct + '%';
|
||||
var tier = box.querySelector('.sg-progress-tier'), done = box.querySelector('.sg-progress-done');
|
||||
tier.hidden = !p.tier;
|
||||
tier.textContent = p.tier ? tpl(PT.tier, p.tier.title, p.tier.target_display) : '';
|
||||
done.hidden = !p.reached;
|
||||
done.textContent = p.reached ? (PT.reached || '') : '';
|
||||
}
|
||||
function refreshGoal(id, bust) {
|
||||
return api('/progress?goal=' + encodeURIComponent(id) + (bust ? '&t=' + Date.now() : '')).then(function (p) {
|
||||
Array.prototype.forEach.call(document.querySelectorAll('.sg-progress'), function (b) {
|
||||
if (b.getAttribute('data-goal') === String(p.goal_id)) { applyBar(b, p); }
|
||||
});
|
||||
}, function () { /* keep showing the last known numbers */ });
|
||||
}
|
||||
function refreshAll(bust) {
|
||||
var seen = {};
|
||||
Array.prototype.forEach.call(document.querySelectorAll('.sg-progress'), function (b) {
|
||||
var id = b.getAttribute('data-goal');
|
||||
if (id && id !== '0' && !seen[id]) { seen[id] = true; refreshGoal(id, bust); }
|
||||
});
|
||||
}
|
||||
function startPolling() {
|
||||
if (!REST || !document.querySelector('.sg-progress')) { return; }
|
||||
var every = Math.max(15000, (PC && PC.pollMs) || 30000);
|
||||
setInterval(function () { if (document.visibilityState !== 'hidden') { refreshAll(false); } }, every);
|
||||
document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible') { refreshAll(true); } });
|
||||
refreshAll(true); // a cached page may hold old numbers
|
||||
}
|
||||
// After a successful donation: refresh now, and again shortly (a pending capture can finalize a moment later).
|
||||
function afterDonation() { refreshAll(true); [1500, 5000, 12000].forEach(function (ms) { setTimeout(function () { refreshAll(true); }, ms); }); }
|
||||
|
||||
function init(root) {
|
||||
var pinned = parseInt(root.getAttribute('data-goal'), 10) || 0;
|
||||
var goals = C.goals.filter(function (g) { return !pinned || g.id === pinned; });
|
||||
if (!goals.length) { return; }
|
||||
var uid = 'sg' + Math.random().toString(36).slice(2, 8);
|
||||
var state = { goal: goals[0], renderToken: 0, quote: null };
|
||||
var barBox = root.querySelector('.sg-progress');
|
||||
|
||||
var goalSel = el('select', { id: uid + '-goal' });
|
||||
goals.forEach(function (g) { goalSel.appendChild(el('option', { value: g.id, text: g.title + ' (' + g.currency + ')' })); });
|
||||
@@ -211,6 +262,18 @@
|
||||
};
|
||||
}
|
||||
|
||||
// Replace the form with a confirmation (keeps the progress bar). No way back until the page is reloaded,
|
||||
// so the donor does not pay twice thinking it failed.
|
||||
function showThanks(text) {
|
||||
state.renderToken++;
|
||||
Array.prototype.forEach.call(root.children, function (n) { if (n !== barBox) { n.hidden = true; } });
|
||||
var panel = el('div', { 'class': 'sg-thanks', role: 'status', tabindex: '-1' }, [
|
||||
el('p', { 'class': 'sg-thanks-title', text: text })
|
||||
]);
|
||||
root.appendChild(panel);
|
||||
try { panel.focus(); panel.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
function renderButtons() {
|
||||
var token = ++state.renderToken;
|
||||
buttons.textContent = '';
|
||||
@@ -226,7 +289,9 @@
|
||||
},
|
||||
onApprove: function (data) {
|
||||
return api('/orders/' + encodeURIComponent(data.orderID) + '/capture', { method: 'POST' }).then(function (r) {
|
||||
say(r.status === 'completed' ? T.thanks : T.processing, 'sg-ok');
|
||||
say('');
|
||||
showThanks(r.status === 'completed' ? T.thanks : T.processing);
|
||||
afterDonation();
|
||||
});
|
||||
},
|
||||
onError: function (err) { say((err && err.message) || T.error, 'sg-error'); }
|
||||
@@ -236,11 +301,15 @@
|
||||
|
||||
goalSel.addEventListener('change', function () {
|
||||
state.goal = goals.filter(function (g) { return String(g.id) === goalSel.value; })[0] || goals[0];
|
||||
if (barBox && state.goal.progress) { applyBar(barBox, state.goal.progress); refreshGoal(state.goal.id, true); }
|
||||
showNext(); buildPresets(); refresh(); renderButtons();
|
||||
});
|
||||
showNext(); buildPresets(); refresh(); renderButtons();
|
||||
}
|
||||
|
||||
function boot() { Array.prototype.forEach.call(document.querySelectorAll('.sg-donate'), init); }
|
||||
function boot() {
|
||||
if (C) { Array.prototype.forEach.call(document.querySelectorAll('.sg-donate:not(.sg-progress-only)'), init); }
|
||||
startPolling();
|
||||
}
|
||||
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot); } else { boot(); }
|
||||
})();
|
||||
@@ -129,6 +129,7 @@
|
||||
seenIds[id] = true; seenOrder.push(id);
|
||||
while (seenOrder.length > SEEN_MAX) delete seenIds[seenOrder.shift()];
|
||||
}
|
||||
var seenReplays = {};
|
||||
function renderAlerts(d) {
|
||||
var list = (d.alerts || []).slice().sort(function (a, b) { return a.id - b.id; });
|
||||
for (var i = 0; i < list.length; i++) {
|
||||
@@ -137,6 +138,15 @@
|
||||
markSeen(a.id);
|
||||
if (!firstAlertPoll) queue.push(a);
|
||||
}
|
||||
// Replays asked for in the admin: each request number plays once. Like new alerts, anything already on the
|
||||
// feed at the first poll is only remembered, so refreshing OBS plays nothing.
|
||||
var again = Array.isArray(d.replays) ? d.replays : [];
|
||||
for (var j = 0; j < again.length; j++) {
|
||||
var n = again[j].replay;
|
||||
if (seenReplays[n]) continue;
|
||||
seenReplays[n] = true;
|
||||
if (!firstAlertPoll) queue.push(again[j]);
|
||||
}
|
||||
firstAlertPoll = false;
|
||||
next();
|
||||
}
|
||||
|
||||
@@ -47,6 +47,8 @@ Rule `config` examples (`max_total_seconds` caps what one rule has added over ti
|
||||
## Public REST (namespace `streamgoals/v1`)
|
||||
- `POST /orders` (create order; server computes total incl. optional fee cover), `POST /orders/{id}/capture`
|
||||
- `POST /webhook` (PayPal signature verified; deduped by capture id)
|
||||
- `GET /progress?goal=ID` — public, read-only, rate limited (60/min per visitor). Returns `Overlay\Progress::payload()` only: `goal_id,title,currency,raised_minor,target_minor,percent,raised_display,target_display,reached,tier|null` (`tier` = `{index,count,title,target_minor,target_display}`). No donor data. 404 unless goal status is active/complete. `Cache-Control: public, max-age=10`.
|
||||
Shortcodes `[streamgoals_donate show_progress="yes|no"]` (default yes) and `[streamgoals_progress goal=""]` server-render `Progress::html()` (role=progressbar); `donate.js` updates it in place (after a donation, every 30 s while the tab is visible, and once on load for cached pages). Numbers come from `Payloads::goal()`, so they match the overlay; reached = closed at target, all tiers reached, or raised >= target.
|
||||
- `GET /overlay/{token}/{widget}` — ETag'd JSON, polled every 2–3 s; widgets: `goal`, `timer`, `counter`, `alerts`
|
||||
|
||||
## Fee cover
|
||||
|
||||
@@ -37,6 +37,7 @@ final class Admin {
|
||||
'sg_event_done_all' => array( ActionsPage::class, 'handleDoneAll' ),
|
||||
'sg_export_csv' => array( DonationsPage::class, 'handleExport' ),
|
||||
'sg_moderate' => array( DonationsPage::class, 'handleModerate' ),
|
||||
'sg_replay_alert' => array( DonationsPage::class, 'handleReplay' ),
|
||||
'sg_test_donation' => array( OverlaysPage::class, 'handleTestDonation' ),
|
||||
'sg_delete_tests' => array( OverlaysPage::class, 'handleDeleteTests' ),
|
||||
'sg_regen_token' => array( OverlaysPage::class, 'handleRegenerate' ),
|
||||
|
||||
@@ -4,6 +4,7 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Replays;
|
||||
|
||||
/** Donations table (search, filter, pagination), CSV export, and the message moderation queue. */
|
||||
final class DonationsPage {
|
||||
@@ -34,6 +35,7 @@ final class DonationsPage {
|
||||
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>';
|
||||
echo '<p class="description"><strong>Replay</strong> shows a donation\'s alert again on the Donation alerts overlay. The overlay must be open when you press it. Totals, timers and counters do not change.</p>';
|
||||
|
||||
if ( ! $res['rows'] ) {
|
||||
echo '<div class="sg-card"><p>No donations found.</p></div>';
|
||||
@@ -44,7 +46,7 @@ final class DonationsPage {
|
||||
foreach ( Store::goals()->all() as $g ) {
|
||||
$goals[ (int) $g['id'] ] = (string) $g['title'];
|
||||
}
|
||||
echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Fee', 'Total paid', 'Goal', 'Status', 'Message' ), 'Donations', false );
|
||||
echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Fee', 'Total paid', 'Goal', 'Status', 'Message', 'Alert' ), 'Donations', false );
|
||||
foreach ( $res['rows'] as $r ) {
|
||||
$cur = Format::currency( $r['currency'] );
|
||||
$test = Format::isTest( $r );
|
||||
@@ -53,7 +55,12 @@ final class DonationsPage {
|
||||
echo Admin::td( 'Amount' ) . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td>' . Admin::td( 'Fee' ) . esc_html( Format::money( (int) $r['fee_minor'], $cur ) ) . '</td>' . Admin::td( 'Total paid' ) . esc_html( Format::money( (int) $r['total_minor'], $cur ) ) . '</td>';
|
||||
echo Admin::td( 'Goal' ) . esc_html( $test ? '(test)' : ( $goals[ (int) $r['goal_id'] ] ?? '#' . (int) $r['goal_id'] ) ) . '</td>';
|
||||
echo Admin::td( 'Status' ) . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' <span class="sg-badge sg-' . esc_attr( (string) $r['moderation'] ) . '">' . esc_html( strtolower( Format::flaggedLabel( $r ) ) . ' ' . (string) $r['moderation'] ) . '</span>' ) . '</td>';
|
||||
echo Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '</td></tr>';
|
||||
echo Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '</td>' . Admin::td( 'Alert', 'sg-actions' );
|
||||
if ( self::canReplay( $r ) ) {
|
||||
Admin::form( 'sg_replay_alert', array( 'donation_id' => (int) $r['id'] ), 'sg-inline' );
|
||||
echo '<button class="button">Replay</button></form>';
|
||||
}
|
||||
echo '</td></tr>';
|
||||
}
|
||||
echo Admin::tableClose();
|
||||
$pages = (int) ceil( $res['total'] / self::PER_PAGE );
|
||||
@@ -71,6 +78,24 @@ final class DonationsPage {
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
/** Only donations that may appear on stream: paid, and not held or rejected by moderation. */
|
||||
public static function canReplay( array $row ): bool {
|
||||
return 'completed' === ( $row['status'] ?? '' ) && 'approved' === ( $row['moderation'] ?? '' );
|
||||
}
|
||||
|
||||
public static function handleReplay(): void {
|
||||
Admin::guard( 'sg_replay_alert' );
|
||||
$post = Admin::post_raw();
|
||||
$id = isset( $post['donation_id'] ) ? absint( $post['donation_id'] ) : 0;
|
||||
$row = $id ? Store::donationById( $id ) : null;
|
||||
$ok = $row && self::canReplay( $row );
|
||||
if ( $ok ) {
|
||||
Replays::request( $id );
|
||||
}
|
||||
$back = wp_get_referer(); // keeps the current filter and page
|
||||
Admin::redirect( $back ? $back : Admin::url( 'streamgoals-donations' ), $ok ? 'success' : 'error', $ok ? 'Alert sent again. Watch your alerts overlay.' : 'That donation cannot be replayed.' );
|
||||
}
|
||||
|
||||
public static function renderModeration(): void {
|
||||
Admin::open( 'Moderation' );
|
||||
if ( ! Settings::get( 'moderate_messages' ) ) {
|
||||
@@ -98,13 +123,19 @@ final class DonationsPage {
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
/** Moderation submenu exists only when moderation is on or items are pending (see Admin::menu); otherwise land on Donations. */
|
||||
public static function afterModerationPage( bool $moderationOn, int $pending ): string {
|
||||
return ( $moderationOn || $pending > 0 ) ? 'streamgoals-moderation' : 'streamgoals-donations';
|
||||
}
|
||||
|
||||
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 ? 'Donation approved.' : 'Donation rejected.' ) : 'That donation could not be updated (it may already be reviewed).' );
|
||||
$page = self::afterModerationPage( (bool) Settings::get( 'moderate_messages' ), Store::pendingModerationCount() );
|
||||
Admin::redirect( Admin::url( $page ), $ok ? 'success' : 'error', $ok ? ( 'approved' === $to ? 'Donation approved.' : 'Donation rejected.' ) : 'That donation could not be updated (it may already be reviewed).' );
|
||||
}
|
||||
|
||||
public static function handleExport(): void {
|
||||
|
||||
@@ -152,6 +152,12 @@ final class Store {
|
||||
return (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . self::t( 'donations' ) . " WHERE status = 'completed' AND moderation = 'pending'" );
|
||||
}
|
||||
|
||||
public static function donationById( int $id ): ?array {
|
||||
global $wpdb;
|
||||
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id = %d', $id ), ARRAY_A );
|
||||
return $row ?: null;
|
||||
}
|
||||
|
||||
public static function setModeration( int $id, string $to ): bool {
|
||||
global $wpdb;
|
||||
if ( ! in_array( $to, array( 'approved', 'rejected' ), true ) ) {
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/**
|
||||
* Keeps live responses out of page caches. LiteSpeed Cache stores REST responses (and pages sending
|
||||
* nocache_headers()) for days unless told otherwise, which freezes overlays that poll for changes.
|
||||
*/
|
||||
final class PageCache {
|
||||
|
||||
public const LITESPEED_HEADER = 'X-LiteSpeed-Cache-Control';
|
||||
|
||||
/** Call before any output, early enough that error responses are covered too. */
|
||||
public static function skip( string $reason ): void {
|
||||
do_action( 'litespeed_control_set_nocache', 'streamgoals ' . $reason );
|
||||
if ( ! headers_sent() ) {
|
||||
header( self::LITESPEED_HEADER . ': no-cache' ); // also covers LiteSpeed server caching without the plugin
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ final class Uninstaller {
|
||||
'sg_settings',
|
||||
'sg_db_version',
|
||||
'sg_overlay_epoch',
|
||||
'sg_alert_replays',
|
||||
'sg_overlay_rules_version',
|
||||
'sg_currency',
|
||||
'sg_paypal_verified',
|
||||
|
||||
@@ -53,15 +53,20 @@ final class OverlayService {
|
||||
} else {
|
||||
$rows = $this->source->donations( $since, 20 );
|
||||
}
|
||||
$ids = array_values( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), $rows ) ) );
|
||||
// Replays travel beside the normal feed and may point at donations older than the recent window.
|
||||
$requests = ( $recent && $this->source instanceof ReplaySource ) ? $this->source->pendingReplays( $now ) : array();
|
||||
$replayRows = $requests ? $this->source->donationsByIds( array_column( $requests, 'id' ) ) : array();
|
||||
$ids = array_values( array_unique( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), array_merge( $rows, $replayRows ) ) ) ) );
|
||||
$bonuses = ( ( $recent || null !== $since ) && $ids ) ? $this->source->bonusesFor( $ids ) : array();
|
||||
$actions = ( ( $recent || null !== $since ) && $ids && $this->source instanceof ActionsSource ) ? $this->source->actionsFor( $ids ) : array();
|
||||
$tiers = ( ( $recent || null !== $since ) && $ids && $this->source instanceof TiersSource ) ? $this->source->tiersReachedFor( $ids ) : array();
|
||||
foreach ( $rows as $i => $r ) {
|
||||
$rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
$rows[ $i ]['actions'] = $actions[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
$rows[ $i ]['tiers'] = $tiers[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
}
|
||||
$decorate = static fn( array $r ): array => array(
|
||||
'bonuses' => $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array(),
|
||||
'actions' => $actions[ (int) ( $r['id'] ?? 0 ) ] ?? array(),
|
||||
'tiers' => $tiers[ (int) ( $r['id'] ?? 0 ) ] ?? array(),
|
||||
) + $r;
|
||||
$rows = array_map( $decorate, $rows );
|
||||
$replayRows = array_map( $decorate, $replayRows );
|
||||
$mediaFor = null;
|
||||
$defs = ( $recent || null !== $since ) ? $this->defs() : array();
|
||||
if ( $defs && $ids && $this->source instanceof AlertMediaSource ) {
|
||||
@@ -71,7 +76,12 @@ final class OverlayService {
|
||||
$r, $name, $amount, $defs, $triggered[ (int) ( $r['id'] ?? 0 ) ] ?? array(), static fn( int $id ): ?array => $src->attachment( $id )
|
||||
);
|
||||
}
|
||||
return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent, $mediaFor );
|
||||
$out = Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent, $mediaFor );
|
||||
$replays = Payloads::replays( $replayRows, $requests, $mediaFor );
|
||||
if ( $replays ) {
|
||||
$out['replays'] = $replays;
|
||||
}
|
||||
return $out;
|
||||
case 'actions':
|
||||
$rows = ( $gid && $this->source instanceof ActionsSource ) ? $this->source->menuActions( $gid ) : array();
|
||||
return Payloads::actionsMenu( $goal, $rows );
|
||||
|
||||
@@ -154,6 +154,28 @@ final class Payloads {
|
||||
return array( 'alerts' => $alerts, 'last_id' => $lastId );
|
||||
}
|
||||
|
||||
/**
|
||||
* One alert per replay request whose donation is still public, in request order, tagged with the request number.
|
||||
*
|
||||
* @param array<int,array<string,mixed>> $rows
|
||||
* @param array<int,array{seq:int,id:int}> $requests
|
||||
*/
|
||||
public static function replays( array $rows, array $requests, ?callable $mediaFor = null ): array {
|
||||
$byId = array();
|
||||
foreach ( $rows as $r ) {
|
||||
if ( 'completed' === ( $r['status'] ?? '' ) && 'approved' === ( $r['moderation'] ?? '' ) ) {
|
||||
$byId[ (int) $r['id'] ] = $r;
|
||||
}
|
||||
}
|
||||
$out = array();
|
||||
foreach ( $requests as $q ) {
|
||||
if ( isset( $byId[ (int) $q['id'] ] ) ) {
|
||||
$out[] = array( 'replay' => (int) $q['seq'] ) + self::alert( $byId[ (int) $q['id'] ], $mediaFor );
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $r
|
||||
* @param (callable(array,string,string):?array)|null $mediaFor Builds the `media` block from (row, public name, amount display).
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
use StreamGoals\Core\GoalTargetPolicy;
|
||||
use StreamGoals\Tiers\TierPolicy;
|
||||
|
||||
/**
|
||||
* Pure, WordPress-free public progress view for the donate form / [streamgoals_progress] / GET /progress.
|
||||
* Numbers come from Payloads::goal() so they match the overlay exactly. Public-safe fields only (no donor data).
|
||||
*/
|
||||
final class Progress {
|
||||
|
||||
/** Parse a shortcode yes/no attribute. Unknown or empty values fall back to $default. */
|
||||
public static function flag( mixed $raw, bool $default ): bool {
|
||||
if ( is_bool( $raw ) ) {
|
||||
return $raw;
|
||||
}
|
||||
if ( is_array( $raw ) || null === $raw ) {
|
||||
return $default;
|
||||
}
|
||||
$v = strtolower( trim( (string) $raw ) );
|
||||
if ( in_array( $v, array( 'yes', 'true', '1', 'on' ), true ) ) {
|
||||
return true;
|
||||
}
|
||||
if ( in_array( $v, array( 'no', 'false', '0', 'off' ), true ) ) {
|
||||
return false;
|
||||
}
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $goal sg_goals row
|
||||
* @param array<int,array<string,mixed>>|null $tiers raw sg_goal_tiers rows
|
||||
* @return array{goal_id:int,title:string,currency:string,raised_minor:int,target_minor:int,percent:int,raised_display:string,target_display:string,reached:bool,tier:?array}
|
||||
*/
|
||||
public static function payload( array $goal, int $raised, ?array $tiers = null ): array {
|
||||
$g = Payloads::goal( $goal, $raised, $tiers ?: null );
|
||||
$tier = null;
|
||||
$reached = GoalTargetPolicy::isClosedAtTarget( $goal );
|
||||
if ( isset( $g['tiers'] ) ) {
|
||||
$cur = $g['tiers']['current'];
|
||||
if ( null !== $cur ) {
|
||||
$tier = array(
|
||||
'index' => (int) $g['tiers']['index'],
|
||||
'count' => (int) $g['tiers']['count'],
|
||||
'title' => (string) $cur['title'],
|
||||
'target_minor' => (int) $cur['target_minor'],
|
||||
'target_display' => (string) $cur['target_display'],
|
||||
);
|
||||
}
|
||||
$reached = $reached || ! empty( $g['tiers']['all_reached'] );
|
||||
} else {
|
||||
$reached = $reached || ( $g['target_minor'] > 0 && $g['raised_minor'] >= $g['target_minor'] );
|
||||
}
|
||||
return array(
|
||||
'goal_id' => (int) ( $goal['id'] ?? 0 ),
|
||||
'title' => $g['title'],
|
||||
'currency' => $g['currency'],
|
||||
'raised_minor' => $g['raised_minor'],
|
||||
'target_minor' => $g['target_minor'],
|
||||
'percent' => $reached ? 100 : $g['percent'],
|
||||
'raised_display' => $g['raised_display'],
|
||||
'target_display' => $g['target_display'],
|
||||
'reached' => $reached,
|
||||
'tier' => $tier,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-rendered bar (the JS updates this same markup in place). Labels are already translated.
|
||||
*
|
||||
* @param array<string,string> $labels reached, of (%1$s raised, %2$s target), tier (%1$s name, %2$s target), label (%s title)
|
||||
*/
|
||||
public static function html( array $p, array $labels ): string {
|
||||
$e = static fn( string $s ): string => htmlspecialchars( $s, ENT_QUOTES, 'UTF-8' );
|
||||
$pct = max( 0, min( 100, (int) $p['percent'] ) );
|
||||
$fill = ( $pct < 2 && (int) ( $p['raised_minor'] ?? 0 ) > 0 ) ? 2 : $pct; // a first small donation still shows
|
||||
$sub = static fn( string $tpl, array $v ): string => (string) preg_replace_callback( '/%(\d)\$s/', static fn( array $m ): string => $v[ (int) $m[1] - 1 ] ?? '', $tpl );
|
||||
$of = $sub( $labels['of'] ?? '%1$s / %2$s', array( $p['raised_display'], $p['target_display'] ) );
|
||||
$out = '<div class="sg-progress' . ( $p['reached'] ? ' sg-progress-reached' : '' ) . '" data-goal="' . (int) $p['goal_id'] . '">';
|
||||
$out .= '<div class="sg-progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' . $pct . '"'
|
||||
. ' aria-valuetext="' . $e( $p['reached'] ? ( $labels['reached'] ?? '' ) : $of . ' (' . $pct . '%)' ) . '"'
|
||||
. ' aria-label="' . $e( str_replace( '%s', (string) $p['title'], $labels['label'] ?? '%s' ) ) . '">'
|
||||
. '<span class="sg-progress-fill" style="width:' . $fill . '%"></span></div>';
|
||||
$out .= '<div class="sg-progress-text"><span class="sg-progress-amounts">' . $e( $of ) . '</span> <span class="sg-progress-pct">' . $pct . '%</span></div>';
|
||||
$out .= '<p class="sg-progress-tier"' . ( $p['tier'] ? '' : ' hidden' ) . '>'
|
||||
. ( $p['tier'] ? $e( $sub( $labels['tier'] ?? '%1$s (%2$s)', array( $p['tier']['title'], $p['tier']['target_display'] ) ) ) : '' ) . '</p>';
|
||||
$out .= '<p class="sg-progress-done"' . ( $p['reached'] ? '' : ' hidden' ) . '>' . $e( $p['reached'] ? ( $labels['reached'] ?? '' ) : '' ) . '</p>';
|
||||
return $out . '</div>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** Optional capability: alerts the streamer asked to see again. */
|
||||
interface ReplaySource {
|
||||
|
||||
/** @return array<int,array{seq:int,id:int}> Unexpired replay requests, oldest first. */
|
||||
public function pendingReplays( int $now ): array;
|
||||
|
||||
/**
|
||||
* The completed + approved donations among $ids, any age.
|
||||
*
|
||||
* @param int[] $ids
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function donationsByIds( array $ids ): array;
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/**
|
||||
* Short-lived queue of "play this alert again" requests. The alerts overlay already knows a donation's id, so
|
||||
* every request gets its own strictly increasing sequence number and the overlay plays each number once.
|
||||
* Replaying only shows the alert: totals, timers, counters, rewards and tiers are never touched.
|
||||
*/
|
||||
final class Replays {
|
||||
|
||||
public const OPTION = 'sg_alert_replays';
|
||||
|
||||
/** Seconds a request stays on the feed. An overlay that is not open during this time never plays it. */
|
||||
public const TTL = 60;
|
||||
|
||||
public const MAX = 10;
|
||||
|
||||
/**
|
||||
* Pure: well-formed, unexpired requests, oldest first.
|
||||
*
|
||||
* @return array<int,array{seq:int,id:int,at:int}>
|
||||
*/
|
||||
public static function active( mixed $stored, int $now ): array {
|
||||
$out = array();
|
||||
foreach ( is_array( $stored ) ? $stored : array() as $r ) {
|
||||
if ( ! is_array( $r ) || ! isset( $r['seq'], $r['id'], $r['at'] ) || (int) $r['id'] <= 0 || $now - (int) $r['at'] >= self::TTL ) {
|
||||
continue;
|
||||
}
|
||||
$out[] = array( 'seq' => (int) $r['seq'], 'id' => (int) $r['id'], 'at' => (int) $r['at'] );
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Pure: the queue after asking for $donationId again. The number never drops below the clock, so it cannot repeat after the queue empties. */
|
||||
public static function push( mixed $stored, int $donationId, int $now ): array {
|
||||
$list = self::active( $stored, $now );
|
||||
$last = $list ? max( array_column( $list, 'seq' ) ) : 0;
|
||||
$list[] = array( 'seq' => max( $last + 1, $now ), 'id' => $donationId, 'at' => $now );
|
||||
return array_slice( $list, -self::MAX );
|
||||
}
|
||||
|
||||
public static function request( int $donationId ): void {
|
||||
update_option( self::OPTION, self::push( get_option( self::OPTION, array() ), $donationId, time() ), false );
|
||||
}
|
||||
|
||||
/** @return array<int,array{seq:int,id:int,at:int}> */
|
||||
public static function pending( int $now ): array {
|
||||
return self::active( get_option( self::OPTION, array() ), $now );
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
use StreamGoals\Core\PageCache;
|
||||
use StreamGoals\Rest\OverlayController;
|
||||
|
||||
/** Serves the transparent OBS browser-source page at /streamgoals-overlay/{token}/{widget}/. */
|
||||
@@ -46,6 +47,7 @@ final class Router {
|
||||
if ( '' === $token || '' === $widget ) {
|
||||
return;
|
||||
}
|
||||
PageCache::skip( 'overlay page' ); // nocache_headers() alone does not stop LiteSpeed Cache
|
||||
if ( ! is_string( $token ) || ! is_string( $widget ) || ! in_array( $widget, OverlayService::WIDGETS, true ) || ! OverlayController::verify_token( $token ) ) {
|
||||
global $wp_query;
|
||||
$wp_query->set_404();
|
||||
|
||||
@@ -4,7 +4,7 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource, TiersSource {
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource, TiersSource, ReplaySource {
|
||||
|
||||
/** @var array<int,?array{url:string,mime:string,v:int,modified:string}> */
|
||||
private array $attachments = array();
|
||||
@@ -184,6 +184,24 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
|
||||
return (array) $rows;
|
||||
}
|
||||
|
||||
public function pendingReplays( int $now ): array {
|
||||
return Replays::pending( $now );
|
||||
}
|
||||
|
||||
public function donationsByIds( array $ids ): array {
|
||||
global $wpdb;
|
||||
$ids = array_values( array_unique( array_filter( array_map( 'intval', $ids ), static fn( $i ) => $i > 0 ) ) );
|
||||
if ( ! $ids ) {
|
||||
return array();
|
||||
}
|
||||
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
return (array) $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT id, goal_id, base_minor, currency, donor_name, is_anonymous, message, status, moderation FROM {$this->t('donations')}
|
||||
WHERE status = 'completed' AND moderation = 'approved' AND id IN ($in)",
|
||||
$ids
|
||||
), ARRAY_A );
|
||||
}
|
||||
|
||||
public function recentDonations( int $limit ): array {
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
|
||||
@@ -3,9 +3,11 @@ declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Rest;
|
||||
|
||||
use StreamGoals\Core\PageCache;
|
||||
use StreamGoals\Core\GoalTargetPolicy;
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Progress;
|
||||
use StreamGoals\PayPal\CaptureFinalizer;
|
||||
use StreamGoals\PayPal\Client;
|
||||
use StreamGoals\PayPal\DonationStore;
|
||||
@@ -27,6 +29,7 @@ final class DonateController {
|
||||
public static function register(): void {
|
||||
add_action( 'rest_api_init', array( self::class, 'routes' ) );
|
||||
add_shortcode( 'streamgoals_donate', array( self::class, 'shortcode' ) );
|
||||
add_shortcode( 'streamgoals_progress', array( self::class, 'progress_shortcode' ) );
|
||||
}
|
||||
|
||||
public static function routes(): void {
|
||||
@@ -57,10 +60,37 @@ final class DonateController {
|
||||
'permission_callback' => '__return_true',
|
||||
)
|
||||
);
|
||||
register_rest_route(
|
||||
self::NS,
|
||||
'/progress',
|
||||
array(
|
||||
'methods' => 'GET',
|
||||
'callback' => array( self::class, 'progress_route' ),
|
||||
'permission_callback' => '__return_true',
|
||||
'args' => array( 'goal' => array( 'sanitize_callback' => 'absint' ) ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- REST */
|
||||
|
||||
/** Public, read-only totals for the progress bar. Whitelisted goal figures only; never donor data. */
|
||||
public static function progress_route( \WP_REST_Request $req ) {
|
||||
if ( $limited = self::limit( 'progress', 60, 60 ) ) {
|
||||
return $limited;
|
||||
}
|
||||
$goal = DonationStore::goal( (int) $req->get_param( 'goal' ) );
|
||||
if ( ! $goal || ! in_array( (string) $goal['status'], array( 'active', 'complete' ), true ) ) {
|
||||
return new \WP_Error( 'sg_goal_not_found', __( 'Goal not found.', 'streamgoals-donate' ), array( 'status' => 404 ) );
|
||||
}
|
||||
$res = rest_ensure_response( self::progress_for( $goal ) );
|
||||
// Short shared cache lets a CDN collapse bursts; the page JS adds a cache-busting parameter after a donation.
|
||||
$res->header( 'Cache-Control', 'public, max-age=10, s-maxage=10' );
|
||||
PageCache::skip( 'progress' ); // LiteSpeed would otherwise hold REST responses for days
|
||||
$res->header( PageCache::LITESPEED_HEADER, 'no-cache' );
|
||||
return $res;
|
||||
}
|
||||
|
||||
public static function create_order( \WP_REST_Request $req ) {
|
||||
if ( $limited = self::limit( 'order', 10, 300 ) ) {
|
||||
return $limited;
|
||||
@@ -141,6 +171,7 @@ final class DonateController {
|
||||
}
|
||||
|
||||
public static function fee_preview( \WP_REST_Request $req ) {
|
||||
PageCache::skip( 'fee preview' ); // follows the current fee settings and goal status
|
||||
if ( $limited = self::limit( 'preview', 120, 60 ) ) {
|
||||
return $limited;
|
||||
}
|
||||
@@ -159,8 +190,9 @@ final class DonateController {
|
||||
/* ----------------------------------------------------------- Shortcode */
|
||||
|
||||
public static function shortcode( $atts ): string {
|
||||
$atts = shortcode_atts( array( 'goal' => '' ), (array) $atts, 'streamgoals_donate' );
|
||||
$atts = shortcode_atts( array( 'goal' => '', 'show_progress' => 'yes' ), (array) $atts, 'streamgoals_donate' );
|
||||
$pinned = (int) $atts['goal'];
|
||||
$showP = Progress::flag( $atts['show_progress'], true );
|
||||
$s = Settings::all();
|
||||
if ( '' === (string) $s['paypal_client_id'] ) {
|
||||
return '<p class="sg-donate-unavailable">' . esc_html__( 'Donations are not available right now.', 'streamgoals-donate' ) . '</p>';
|
||||
@@ -179,13 +211,15 @@ final class DonateController {
|
||||
'currency' => strtoupper( (string) $g['currency'] ),
|
||||
'exp' => Money::exponent( (string) $g['currency'] ),
|
||||
'actions' => $actions[ (int) $g['id'] ] ?? array(),
|
||||
);
|
||||
) + ( $showP ? array( 'progress' => self::progress_for( $g ) ) : array() );
|
||||
}
|
||||
if ( ! $goals ) {
|
||||
$reached = $pinned ? DonationStore::goal( $pinned ) : null;
|
||||
$reached = $pinned ? ( $reached && GoalTargetPolicy::isClosedAtTarget( $reached ) ) : (bool) DonationStore::reached_goals();
|
||||
if ( $reached ) {
|
||||
return '<p class="sg-donate-unavailable sg-donate-reached">' . esc_html__( 'This goal has been reached - thank you for your support!', 'streamgoals-donate' ) . '</p>';
|
||||
$rg = $pinned ? DonationStore::goal( $pinned ) : ( DonationStore::reached_goals()[0] ?? null );
|
||||
$bar = ( $showP && $rg ) ? self::progress_markup( self::progress_for( $rg ) ) : '';
|
||||
return $bar . '<p class="sg-donate-unavailable sg-donate-reached">' . esc_html__( 'This goal has been reached - thank you for your support!', 'streamgoals-donate' ) . '</p>';
|
||||
}
|
||||
return '<p class="sg-donate-unavailable">' . esc_html__( 'There is no active goal to donate to right now.', 'streamgoals-donate' ) . '</p>';
|
||||
}
|
||||
@@ -231,11 +265,68 @@ final class DonateController {
|
||||
);
|
||||
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' );
|
||||
|
||||
return '<div class="sg-donate" data-goal="' . esc_attr( (string) $pinned ) . '"></div>';
|
||||
self::enqueue_progress();
|
||||
$first = $showP ? $goals[0]['progress'] : null;
|
||||
return '<div class="sg-donate" data-goal="' . esc_attr( (string) $pinned ) . '"' . ( $showP ? ' data-progress="1"' : '' ) . '>'
|
||||
. ( $first ? self::progress_markup( $first ) : '' ) . '</div>';
|
||||
}
|
||||
|
||||
/** [streamgoals_progress goal=""]: the same bar without the form. Server-rendered; JS refreshes it. */
|
||||
public static function progress_shortcode( $atts ): string {
|
||||
$atts = shortcode_atts( array( 'goal' => '' ), (array) $atts, 'streamgoals_progress' );
|
||||
$id = (int) $atts['goal'];
|
||||
$goal = $id ? DonationStore::goal( $id ) : ( DonationStore::active_goals()[0] ?? ( DonationStore::reached_goals()[0] ?? null ) );
|
||||
if ( ! $goal || ! in_array( (string) $goal['status'], array( 'active', 'complete' ), true ) ) {
|
||||
return '';
|
||||
}
|
||||
self::enqueue_progress();
|
||||
return '<div class="sg-donate sg-progress-only">' . self::progress_markup( self::progress_for( $goal ) ) . '</div>';
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- Helpers */
|
||||
|
||||
/** @return array<string,mixed> Progress::payload() for a goal row (same raised basis and tiers as the overlay). */
|
||||
private static function progress_for( array $goal ): array {
|
||||
global $wpdb;
|
||||
$id = (int) $goal['id'];
|
||||
$tiers = array();
|
||||
try {
|
||||
$tiers = ( new \StreamGoals\Tiers\TierRepository( $wpdb ) )->forGoal( $id );
|
||||
} catch ( \Throwable $e ) {
|
||||
$tiers = array();
|
||||
}
|
||||
return Progress::payload( $goal, ( new \StreamGoals\Overlay\WpdbDataSource() )->raisedMinor( $goal ), $tiers ?: null );
|
||||
}
|
||||
|
||||
private static function progress_i18n(): array {
|
||||
return array(
|
||||
'reached' => __( 'Goal reached', 'streamgoals-donate' ),
|
||||
/* translators: 1: formatted amount raised, 2: formatted target */
|
||||
'of' => __( '%1$s of %2$s', 'streamgoals-donate' ),
|
||||
/* translators: 1: current tier name, 2: formatted tier target */
|
||||
'tier' => __( 'Current tier: %1$s (target %2$s)', 'streamgoals-donate' ),
|
||||
/* translators: %s: goal title */
|
||||
'label' => __( 'Progress towards %s', 'streamgoals-donate' ),
|
||||
);
|
||||
}
|
||||
|
||||
private static function progress_markup( array $p ): string {
|
||||
return Progress::html( $p, self::progress_i18n() );
|
||||
}
|
||||
|
||||
/** Enqueue assets and the (once per page) config the bar's JS needs. */
|
||||
private static function enqueue_progress(): void {
|
||||
static $done = false;
|
||||
wp_enqueue_style( 'streamgoals-donate', STREAMGOALS_URL . 'assets/donate/donate.css', array(), STREAMGOALS_VERSION );
|
||||
wp_enqueue_script( 'streamgoals-donate', STREAMGOALS_URL . 'assets/donate/donate.js', array(), STREAMGOALS_VERSION, true );
|
||||
if ( $done ) {
|
||||
return;
|
||||
}
|
||||
$done = true;
|
||||
$cfg = array( 'restUrl' => esc_url_raw( rest_url( self::NS ) ), 'i18n' => self::progress_i18n(), 'pollMs' => 30000 );
|
||||
wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsProgress=' . wp_json_encode( $cfg, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' );
|
||||
}
|
||||
|
||||
/**
|
||||
* "Next unlock" hint for a tiered goal: the current (first unreached) tier's title and the amount still needed, in minor units.
|
||||
* Null for goals without tiers or with every tier reached. Computed when the page renders.
|
||||
|
||||
@@ -3,6 +3,7 @@ declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Rest;
|
||||
|
||||
use StreamGoals\Core\PageCache;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Build;
|
||||
use StreamGoals\Overlay\OverlayService;
|
||||
@@ -54,6 +55,7 @@ final class OverlayController {
|
||||
}
|
||||
|
||||
public static function handle( \WP_REST_Request $req ): \WP_REST_Response|\WP_Error {
|
||||
PageCache::skip( 'overlay data' ); // a cached poll response would freeze the goal bar and alerts
|
||||
if ( ! self::verify_token( (string) $req['token'] ) ) {
|
||||
return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) );
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\Csv;
|
||||
use StreamGoals\Admin\DonationsPage;
|
||||
use StreamGoals\Admin\Format;
|
||||
use StreamGoals\Admin\Input;
|
||||
use StreamGoals\Admin\RuleConfig;
|
||||
@@ -133,4 +134,11 @@ final class AdminLogicTest extends TestCase {
|
||||
$this->assertTrue( Format::isTest( array( 'paypal_order_id' => 'TEST-abc' ) ) );
|
||||
$this->assertFalse( Format::isTest( array( 'paypal_order_id' => '5O1234' ) ) );
|
||||
}
|
||||
|
||||
public function test_after_moderation_redirect_only_to_registered_page(): void {
|
||||
$this->assertSame( 'streamgoals-donations', DonationsPage::afterModerationPage( false, 0 ) );
|
||||
$this->assertSame( 'streamgoals-moderation', DonationsPage::afterModerationPage( false, 2 ) );
|
||||
$this->assertSame( 'streamgoals-moderation', DonationsPage::afterModerationPage( true, 0 ) );
|
||||
$this->assertSame( 'streamgoals-moderation', DonationsPage::afterModerationPage( true, 5 ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\DonationsPage;
|
||||
use StreamGoals\Overlay\OverlayDataSource;
|
||||
use StreamGoals\Overlay\OverlayService;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\Overlay\RecentDonationsSource;
|
||||
use StreamGoals\Overlay\ReplaySource;
|
||||
use StreamGoals\Overlay\Replays;
|
||||
|
||||
final class AlertReplayTest extends TestCase {
|
||||
|
||||
private function row( int $id, array $o = array() ): array {
|
||||
return $o + array( 'id' => $id, 'base_minor' => 500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0,
|
||||
'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
|
||||
}
|
||||
|
||||
/** Donation 1 is older than the recent window; only 2 is "recent". */
|
||||
private function svc( array $db, array $requests ): OverlayService {
|
||||
return new OverlayService( new class( $db, $requests ) implements OverlayDataSource, RecentDonationsSource, ReplaySource {
|
||||
public function __construct( private array $db, private array $requests ) {}
|
||||
public function activeGoal(): ?array { return null; }
|
||||
public function raisedMinor( array $goal ): int { return 0; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); }
|
||||
public function bonusesFor( array $ids ): array { return array_fill_keys( $ids, array( 'big_donation' ) ); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return array(); }
|
||||
public function recentDonations( int $limit ): array { return array_slice( $this->db, -1 ); }
|
||||
public function pendingReplays( int $now ): array { return $this->requests; }
|
||||
public function donationsByIds( array $ids ): array { return array_values( array_filter( $this->db, static fn( $d ) => in_array( $d['id'], $ids, true ) ) ); }
|
||||
} );
|
||||
}
|
||||
|
||||
public function test_old_donation_is_replayed_with_its_extras_once_per_request(): void {
|
||||
$svc = $this->svc( array( $this->row( 1 ), $this->row( 2 ) ), array( array( 'seq' => 100, 'id' => 1 ), array( 'seq' => 101, 'id' => 1 ) ) );
|
||||
$out = $svc->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( array( 2 ), array_column( $out['alerts'], 'id' ) );
|
||||
$this->assertSame( array( 100, 101 ), array_column( $out['replays'], 'replay' ) );
|
||||
$this->assertSame( array( 1, 1 ), array_column( $out['replays'], 'id' ) );
|
||||
$this->assertSame( array( 'Big donation' ), $out['replays'][0]['bonuses'] );
|
||||
$this->assertSame( array( 'Big donation' ), $out['alerts'][0]['bonuses'] );
|
||||
}
|
||||
|
||||
public function test_no_requests_leaves_the_payload_and_etag_unchanged(): void {
|
||||
$out = $this->svc( array( $this->row( 2 ) ), array() )->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( array( 'alerts', 'last_id' ), array_keys( $out ) );
|
||||
$with = $this->svc( array( $this->row( 2 ) ), array( array( 'seq' => 5, 'id' => 2 ) ) )->payload( 'alerts', 1, null, true );
|
||||
$this->assertNotSame( Payloads::etag( $out ), Payloads::etag( $with ) );
|
||||
}
|
||||
|
||||
public function test_held_rejected_and_pending_donations_are_never_replayed_and_names_stay_masked(): void {
|
||||
$rows = array( $this->row( 1, array( 'moderation' => 'pending' ) ), $this->row( 2, array( 'moderation' => 'rejected' ) ),
|
||||
$this->row( 3, array( 'status' => 'pending' ) ), $this->row( 4, array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ) );
|
||||
$requests = array_map( static fn( $i ) => array( 'seq' => $i, 'id' => $i ), array( 1, 2, 3, 4, 99 ) );
|
||||
$out = Payloads::replays( $rows, $requests );
|
||||
$this->assertSame( array( 4 ), array_column( $out, 'id' ) );
|
||||
$this->assertSame( 'Anonymous', $out[0]['name'] );
|
||||
foreach ( array_slice( $rows, 0, 3 ) as $r ) {
|
||||
$this->assertFalse( DonationsPage::canReplay( $r ) );
|
||||
}
|
||||
$this->assertTrue( DonationsPage::canReplay( $rows[3] ) );
|
||||
}
|
||||
|
||||
public function test_queue_numbers_increase_expire_and_are_capped(): void {
|
||||
$q = Replays::push( false, 7, 1000 );
|
||||
$q = Replays::push( $q, 7, 1000 );
|
||||
$this->assertSame( array( 1000, 1001 ), array_column( $q, 'seq' ) );
|
||||
$this->assertCount( 2, Replays::active( $q, 1000 + Replays::TTL - 1 ) );
|
||||
$this->assertSame( array(), Replays::active( $q, 1000 + Replays::TTL ) );
|
||||
$this->assertSame( array( 2000 ), array_column( Replays::push( $q, 8, 2000 ), 'seq' ) );
|
||||
for ( $i = 0; $i < 30; $i++ ) {
|
||||
$q = Replays::push( $q, 7, 1000 );
|
||||
}
|
||||
$this->assertCount( Replays::MAX, $q );
|
||||
$this->assertSame( array(), Replays::active( array( 'junk', array( 'seq' => 1 ) ), 1000 ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
/** Live responses must opt out of page caching, or OBS overlays freeze behind LiteSpeed Cache. */
|
||||
final class PageCacheOptOutTest extends TestCase {
|
||||
|
||||
public function test_every_live_response_opts_out_of_page_caching(): void {
|
||||
$root = dirname( __DIR__, 2 ) . '/includes/';
|
||||
$expected = array(
|
||||
'Rest/OverlayController.php' => "PageCache::skip( 'overlay data' )",
|
||||
'Overlay/Router.php' => "PageCache::skip( 'overlay page' )",
|
||||
'Rest/DonateController.php' => "PageCache::skip( 'fee preview' )",
|
||||
);
|
||||
foreach ( $expected as $file => $call ) {
|
||||
$this->assertStringContainsString( $call, (string) file_get_contents( $root . $file ), $file );
|
||||
}
|
||||
$helper = (string) file_get_contents( $root . 'Core/PageCache.php' );
|
||||
$this->assertStringContainsString( 'litespeed_control_set_nocache', $helper );
|
||||
}
|
||||
|
||||
public function test_overlay_opts_out_before_the_token_check_so_404s_are_not_cached(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Rest/OverlayController.php' );
|
||||
$this->assertLessThan( strpos( $src, 'self::verify_token( (string)' ), strpos( $src, 'PageCache::skip(' ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\Overlay\Progress;
|
||||
|
||||
final class ProgressTest extends TestCase {
|
||||
|
||||
private function goal( array $over = array() ): array {
|
||||
return $over + array( 'id' => 7, 'title' => 'New mic', 'target_minor' => 10000, 'currency' => 'USD', 'status' => 'active', 'close_at_target' => 0, 'counts_fees' => 0 );
|
||||
}
|
||||
|
||||
/** @dataProvider flags */
|
||||
public function test_show_progress_attribute_parsing( $raw, bool $expected ): void {
|
||||
$this->assertSame( $expected, Progress::flag( $raw, true ) );
|
||||
}
|
||||
|
||||
public static function flags(): array {
|
||||
return array(
|
||||
array( 'yes', true ), array( 'YES', true ), array( 'true', true ), array( '1', true ), array( 1, true ), array( ' on ', true ),
|
||||
array( 'no', false ), array( 'No', false ), array( 'false', false ), array( '0', false ), array( 0, false ), array( 'off', false ),
|
||||
array( '', true ), array( null, true ), array( 'banana', true ), array( array( 'x' ), true ),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_flag_default_is_respected_for_unknown_values(): void {
|
||||
$this->assertFalse( Progress::flag( 'banana', false ) );
|
||||
$this->assertFalse( Progress::flag( null, false ) );
|
||||
}
|
||||
|
||||
public function test_percentage_is_clamped_and_target_zero_is_safe(): void {
|
||||
$this->assertSame( 0, Progress::payload( $this->goal( array( 'target_minor' => 0 ) ), 500 )['percent'] );
|
||||
$this->assertSame( 100, Progress::payload( $this->goal(), 999999 )['percent'] );
|
||||
$this->assertSame( 0, Progress::payload( $this->goal(), -50 )['percent'] );
|
||||
$this->assertSame( 25, Progress::payload( $this->goal(), 2500 )['percent'] );
|
||||
}
|
||||
|
||||
public function test_numbers_match_the_overlay_goal_payload(): void {
|
||||
$p = Progress::payload( $this->goal(), 2500 );
|
||||
$o = Payloads::goal( $this->goal(), 2500 );
|
||||
foreach ( array( 'raised_minor', 'target_minor', 'percent', 'raised_display', 'target_display', 'currency', 'title' ) as $k ) {
|
||||
$this->assertSame( $o[ $k ], $p[ $k ], $k );
|
||||
}
|
||||
$this->assertSame( '$25.00', $p['raised_display'] );
|
||||
$this->assertSame( '$100.00', $p['target_display'] );
|
||||
$this->assertFalse( $p['reached'] );
|
||||
$this->assertNull( $p['tier'] );
|
||||
}
|
||||
|
||||
public function test_tiered_goal_shows_current_tier_and_matches_overlay(): void {
|
||||
$tiers = array(
|
||||
array( 'id' => 1, 'target_minor' => 5000, 'title' => 'Giveaway', 'description' => 'secret', 'reached_at' => '2026-01-01 00:00:00' ),
|
||||
array( 'id' => 2, 'target_minor' => 20000, 'title' => 'Microphone', 'description' => 'secret', 'reached_at' => null ),
|
||||
);
|
||||
$g = $this->goal( array( 'target_minor' => 20000 ) );
|
||||
$p = Progress::payload( $g, 8000, $tiers );
|
||||
$o = Payloads::goal( $g, 8000, $tiers );
|
||||
$this->assertSame( $o['percent'], $p['percent'] );
|
||||
$this->assertSame( 20000, $p['target_minor'] );
|
||||
$this->assertSame( array( 'index' => 2, 'count' => 2, 'title' => 'Microphone', 'target_minor' => 20000, 'target_display' => '$200.00' ), $p['tier'] );
|
||||
$this->assertFalse( $p['reached'] );
|
||||
$this->assertStringNotContainsString( 'secret', json_encode( $p ) );
|
||||
}
|
||||
|
||||
public function test_reached_states(): void {
|
||||
$closed = $this->goal( array( 'status' => 'complete', 'close_at_target' => 1 ) );
|
||||
$this->assertTrue( Progress::payload( $closed, 10000 )['reached'] );
|
||||
$this->assertTrue( Progress::payload( $closed, 0 )['reached'], 'closed at target wins even if numbers lag' );
|
||||
$this->assertTrue( Progress::payload( $this->goal(), 10000 )['reached'], 'raised >= target' );
|
||||
$this->assertFalse( Progress::payload( $this->goal( array( 'target_minor' => 0 ) ), 10000 )['reached'], 'no target never counts as reached' );
|
||||
$done = array( array( 'id' => 1, 'target_minor' => 5000, 'title' => 'A', 'reached_at' => 'x' ) );
|
||||
$p = Progress::payload( $this->goal( array( 'target_minor' => 5000 ) ), 5000, $done );
|
||||
$this->assertTrue( $p['reached'] );
|
||||
$this->assertNull( $p['tier'] );
|
||||
}
|
||||
|
||||
public function test_public_payload_has_exactly_the_whitelisted_non_pii_keys(): void {
|
||||
$goal = $this->goal() + array( 'paypal_secret' => 'x', 'notes' => 'private' );
|
||||
$p = Progress::payload( $goal, 100 );
|
||||
$this->assertSame(
|
||||
array( 'currency', 'goal_id', 'percent', 'raised_display', 'raised_minor', 'reached', 'target_display', 'target_minor', 'tier', 'title' ),
|
||||
( static function ( array $a ): array { ksort( $a ); return array_keys( $a ); } )( $p )
|
||||
);
|
||||
$json = json_encode( $p );
|
||||
foreach ( array( 'paypal', 'notes', 'email', 'donor', 'message', 'display_name' ) as $bad ) {
|
||||
$this->assertStringNotContainsString( $bad, $json );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_html_is_accessible_and_escaped(): void {
|
||||
$p = Progress::payload( $this->goal( array( 'title' => '<b>Mic</b>' ) ), 2500 );
|
||||
$html = Progress::html( $p, array( 'reached' => 'Goal reached', 'of' => '%1$s of %2$s', 'tier' => 'Tier: %1$s (%2$s)', 'label' => 'Progress: %s' ) );
|
||||
$this->assertStringContainsString( 'role="progressbar"', $html );
|
||||
$this->assertStringContainsString( 'aria-valuenow="25"', $html );
|
||||
$this->assertStringContainsString( 'aria-valuemin="0"', $html );
|
||||
$this->assertStringContainsString( 'aria-valuemax="100"', $html );
|
||||
$this->assertStringContainsString( 'aria-label="Progress: <b>Mic</b>"', $html );
|
||||
$this->assertStringContainsString( '$25.00 of $100.00', $html );
|
||||
$this->assertStringContainsString( 'width:25%', $html );
|
||||
$this->assertStringNotContainsString( '<b>', $html );
|
||||
}
|
||||
|
||||
public function test_html_reached_and_tier_lines(): void {
|
||||
$labels = array( 'reached' => 'Goal reached', 'of' => '%1$s of %2$s', 'tier' => 'Tier: %1$s (%2$s)', 'label' => 'Progress: %s' );
|
||||
$closed = Progress::html( Progress::payload( $this->goal( array( 'status' => 'complete', 'close_at_target' => 1 ) ), 10000 ), $labels );
|
||||
$this->assertStringContainsString( 'Goal reached', $closed );
|
||||
$this->assertStringContainsString( 'sg-progress-reached', $closed );
|
||||
$this->assertStringContainsString( 'aria-valuenow="100"', $closed );
|
||||
$tiers = array( array( 'id' => 2, 'target_minor' => 20000, 'title' => 'Mic', 'reached_at' => null ) );
|
||||
$t = Progress::html( Progress::payload( $this->goal( array( 'target_minor' => 20000 ) ), 100, $tiers ), $labels );
|
||||
$this->assertStringContainsString( 'Tier: Mic ($200.00)', $t );
|
||||
}
|
||||
|
||||
public function test_assets_support_reduced_motion_and_polling_rules(): void {
|
||||
$root = dirname( __DIR__, 2 ) . '/assets/donate/';
|
||||
$css = (string) file_get_contents( $root . 'donate.css' );
|
||||
$js = (string) file_get_contents( $root . 'donate.js' );
|
||||
$this->assertStringContainsString( 'prefers-reduced-motion', $css );
|
||||
$this->assertStringContainsString( 'visibilityState', $js );
|
||||
$this->assertStringContainsString( '30000', $js );
|
||||
$this->assertStringNotContainsString( 'innerHTML', $js );
|
||||
}
|
||||
|
||||
public function test_route_and_shortcodes_are_registered(): void {
|
||||
$php = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Rest/DonateController.php' );
|
||||
$this->assertStringContainsString( "'/progress'", $php );
|
||||
$this->assertStringContainsString( "add_shortcode( 'streamgoals_progress'", $php );
|
||||
$this->assertStringContainsString( "'show_progress' => 'yes'", $php );
|
||||
$this->assertMatchesRegularExpression( "/function progress_route.*self::limit\( 'progress'/s", $php );
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user