Compare commits

..
Author SHA1 Message Date
shadowdaoandClaude Sonnet 5.5 473fe192cd Security review fixes: keep pending-capture ids, ship uninstall.php (+verify step), webhook guard, IPv6 /64 + global order throttle, token-safe redirects, honest refund wording, request-id and overlay-token hardening
Test and Release / test (push) Successful in 1m23s
Test and Release / release (push) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 14:07:44 -08:00
shadowdaoandClaude Sonnet 5.5 68bd917660 LICENSE, clean uninstall (opt-in data removal), privacy policy text, Update URI header
Test and Release / test (push) Successful in 1m28s
Test and Release / release (push) Successful in 4s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 14:00:04 -08:00
shadowdaoandClaude Sonnet 5.5 fb200594ce Admin tables: scroll containers and phone cards; Alerts list flags missing media
Test and Release / test (push) Successful in 1m26s
Test and Release / release (push) Successful in 5s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-15 13:59:20 -08:00
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
56 changed files with 1889 additions and 101 deletions

No files matched your search

+13
View File
@@ -93,6 +93,7 @@ jobs:
PKG=/tmp/streamgoals-donate
mkdir -p "$PKG"
cp streamgoals-donate.php "$PKG"/
cp uninstall.php "$PKG"/
cp -r includes assets "$PKG"/
[ -d languages ] && cp -r languages "$PKG"/ || true
[ -f LICENSE ] && cp LICENSE "$PKG"/ || true
@@ -101,6 +102,18 @@ jobs:
(cd /tmp && zip -r -q "$GITHUB_WORKSPACE/streamgoals-donate.zip" streamgoals-donate)
unzip -l streamgoals-donate.zip | tail -n 15
- name: Verify package contents
run: |
set -e
LIST=$(unzip -l streamgoals-donate.zip)
for f in streamgoals-donate/streamgoals-donate.php streamgoals-donate/uninstall.php streamgoals-donate/includes/Core/Uninstaller.php streamgoals-donate/LICENSE; do
if ! echo "$LIST" | grep -qE "[[:space:]]${f}\$"; then
echo "::error::release zip is missing $f"
exit 1
fi
done
echo "package contents verified"
- name: Create release
uses: softprops/action-gh-release@v2
with:
+339
View File
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
+24 -2
View File
@@ -76,8 +76,21 @@ server sees.
- Optional message approval queue and a streamer-controlled profanity filter (whole-word, your own word list).
## Not supported
- **Refunds and chargebacks are not tracked.** If you refund someone in PayPal, goal totals, timers and
counters are not adjusted.
- **Refunds and chargebacks are not tracked.** Refunds and chargebacks done in PayPal are NOT reflected in goal
totals, timers, counters or tiers. The donation keeps counting as if it had been paid.
## 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
@@ -93,3 +106,12 @@ vendor/bin/phpunit
```
Architecture notes are in `docs/ARCHITECTURE.md`. Every push to `main` runs the tests and, if they pass,
publishes a versioned zip release via Gitea Actions.
## License
StreamGoals Donate is free software, released under the GNU General Public License, version 2 or (at your option)
any later version (GPL-2.0-or-later). See the `LICENSE` file for the full text.
## Uninstalling
Deleting the plugin from the Plugins screen always removes its scheduled task and cached data. Your donations, goals,
rules, rewards, alerts, tiers and settings are kept unless you first tick "Delete all data when the plugin is deleted"
in StreamGoals > Settings > Advanced (off by default; deleting cannot be undone).
+31 -1
View File
@@ -46,7 +46,6 @@
@media (max-width: 782px) { .sg-admin .sg-copy { flex-direction: column; align-items: stretch; } }
/* Phones: wide tables scroll inside their own box instead of pushing the page; controls never exceed the card. */
@media (max-width: 782px) {
.sg-admin table.sg-table { display: block; max-width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; }
.sg-admin .sg-table th, .sg-admin .sg-table td { min-width: 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; }
@@ -56,3 +55,34 @@
.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; }
}
/* Table wrapper: scrolls sideways inside itself, never the page. Desktop look is unchanged. */
.sg-admin .sg-scroll { max-width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; }
.sg-admin .sg-scroll:focus-visible { outline: 2px solid #2271b1; outline-offset: 1px; }
.sg-admin .sg-swipe-hint { display: none; }
.sg-admin .sg-table code { overflow-wrap: anywhere; }
@media (max-width: 782px) {
.sg-admin .sg-table code { word-break: normal; overflow-wrap: anywhere; white-space: normal; }
/* Scroll tables: edge fades (scroll shadows) plus a one-line hint. */
.sg-admin .sg-swipe-hint { display: block; margin: 4px 0; font-size: 12px; color: #50575e; }
.sg-admin .sg-scroll:not(.sg-scroll-cards) {
background: linear-gradient(to right, #fff 30%, rgba(255,255,255,0)) 0 0 / 40px 100% no-repeat local,
linear-gradient(to left, #fff 30%, rgba(255,255,255,0)) 100% 0 / 40px 100% no-repeat local,
linear-gradient(to right, rgba(0,0,0,.22), rgba(0,0,0,0)) 0 0 / 14px 100% no-repeat scroll,
linear-gradient(to left, rgba(0,0,0,.22), rgba(0,0,0,0)) 100% 0 / 14px 100% no-repeat scroll;
}
.sg-admin .sg-scroll:not(.sg-scroll-cards) .sg-table { min-width: 560px; }
/* Card tables: each row becomes a labelled card. */
.sg-admin .sg-scroll-cards { overflow-x: visible; }
.sg-admin table.sg-cards, .sg-admin table.sg-cards tbody, .sg-admin table.sg-cards tr, .sg-admin table.sg-cards td { display: block; width: auto; box-sizing: border-box; }
.sg-admin table.sg-cards { border: 0; background: none; box-shadow: none; }
.sg-admin table.sg-cards thead { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
.sg-admin table.sg-cards tr { margin: 0 0 12px; padding: 4px 0; border: 1px solid #c3c4c7; border-radius: 4px; background: #fff; }
.sg-admin table.sg-cards td { display: flex; gap: 10px; justify-content: space-between; align-items: baseline; padding: 6px 12px; font-size: 14px; border: 0; overflow-wrap: anywhere; text-align: right; }
.sg-admin table.sg-cards td::before { content: attr(data-label); flex: 0 0 34%; font-weight: 600; color: #50575e; text-align: left; }
.sg-admin table.sg-cards td:first-child { display: block; font-size: 15px; text-align: left; border-bottom: 1px solid #f0f0f1; padding-bottom: 8px; }
.sg-admin table.sg-cards td:first-child::before, .sg-admin table.sg-cards td[data-label=""]::before, .sg-admin table.sg-cards td.sg-actions::before { display: none; }
.sg-admin table.sg-cards td.sg-actions, .sg-admin table.sg-cards td[data-label=""] { display: flex; flex-direction: column; align-items: stretch; gap: 8px; padding: 10px 12px 8px; text-align: center; }
.sg-admin table.sg-cards td.sg-actions .button, .sg-admin table.sg-cards td[data-label=""] .button { display: block; width: 100%; min-height: 44px; line-height: 42px; margin: 0; padding: 0 12px; box-sizing: border-box; text-align: center; }
.sg-admin table.sg-cards td.sg-actions form, .sg-admin table.sg-cards td[data-label=""] form { display: block; margin: 0; }
}
+13
View File
@@ -21,3 +21,16 @@
.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}
/* Alerts list: media that was deleted from the Media Library */
.sga-missing{color:#8a2424;background:#fcf0f0;border:1px solid #d63638;border-radius:3px;padding:0 6px;font-weight:600;display:inline-block}
+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".' ) );
}() );
+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 -1
View File
@@ -32,7 +32,7 @@ Money::fromDecimalString(string $amount, string $currency): Money; // "10.50" -
FeeCalculator::grossUp(int $baseMinor, FeeRates $rates): int; // total so recipient nets base
// total = ceil((base + fixed) / (1 - pct)) — rates configurable, default US 3.49% + 49c
```
Rules engine entry point (Agent 2 implements, Agent 1 calls after a capture is recorded and on refund):
Rules engine entry point (Agent 2 implements, Agent 1 calls after a capture is recorded; refunds/chargebacks are NOT tracked - nothing calls reverseDonation, and refunds done in PayPal are not reflected in goal totals, timers, counters or tiers):
```php
Rules\Engine::applyDonation(Donation $d): void; // idempotent via sg_rule_events UNIQUE
Rules\Engine::reverseDonation(Donation $d): void; // honors per-rule "reverse on refund"
+14 -14
View File
@@ -55,17 +55,17 @@ final class ActionsPage {
if ( ! $queued ) {
echo '<p>Nothing in the queue. When a donation triggers a reward, it shows up here.</p>';
} else {
echo '<table class="widefat striped sg-table"><thead><tr><th>Donor</th><th>Amount</th><th>Reward</th><th>Time</th><th>Message</th><th></th></tr></thead><tbody>';
echo Admin::tableOpen( array( 'Donor', 'Amount', 'Reward', 'Time', 'Message', '' ), 'Reward queue' );
foreach ( $queued as $e ) {
echo '<tr><td>' . esc_html( Format::donorName( $e ) ) . '</td>';
echo '<td>' . esc_html( Format::money( (int) ( $e['base_minor'] ?? 0 ), Format::currency( $e['currency'] ?? $cur ) ) ) . '</td>';
echo '<td><strong>' . esc_html( (string) $e['title'] ) . '</strong> &times; ' . (int) $e['times'] . '</td>';
echo '<td>' . esc_html( self::when( (string) $e['created_at'] ) ) . '</td>';
echo '<td>' . esc_html( (string) ( $e['message'] ?? '' ) ) . '</td><td>';
echo '<tr>' . Admin::td( 'Donor' ) . esc_html( Format::donorName( $e ) ) . '</td>';
echo Admin::td( 'Amount' ) . esc_html( Format::money( (int) ( $e['base_minor'] ?? 0 ), Format::currency( $e['currency'] ?? $cur ) ) ) . '</td>';
echo Admin::td( 'Reward' ) . '<strong>' . esc_html( (string) $e['title'] ) . '</strong> &times; ' . (int) $e['times'] . '</td>';
echo Admin::td( 'Time' ) . esc_html( self::when( (string) $e['created_at'] ) ) . '</td>';
echo Admin::td( 'Message' ) . esc_html( (string) ( $e['message'] ?? '' ) ) . '</td>' . Admin::td( '', 'sg-actions' );
Admin::form( 'sg_event_done', array( 'event_id' => (int) $e['id'] ), 'sg-inline' );
echo '<button class="button button-primary">Mark done</button></form></td></tr>';
}
echo '</tbody></table>';
echo Admin::tableClose();
Admin::form( 'sg_event_done_all' );
echo '<p><button class="button">Mark all done</button></p></form>';
}
@@ -104,17 +104,17 @@ final class ActionsPage {
echo '<p>No rewards yet.</p></div>';
return;
}
echo '<table class="widefat striped sg-table"><thead><tr><th>Reward</th><th>Amount</th><th>Triggers</th><th>Applies to</th><th>Order</th><th>Actions</th></tr></thead><tbody>';
echo Admin::tableOpen( array( 'Reward', 'Amount', 'Triggers', 'Applies to', 'Order', 'Actions' ), 'Reward menu' );
foreach ( $actions as $a ) {
$id = (int) $a['id'];
echo '<tr' . ( $a['enabled'] ? '' : ' class="sg-off"' ) . '><td><strong>' . esc_html( $a['title'] ) . '</strong>';
echo '<tr' . ( $a['enabled'] ? '' : ' class="sg-off"' ) . '>' . Admin::td( 'Reward' ) . '<strong>' . esc_html( $a['title'] ) . '</strong>';
if ( '' !== $a['description'] ) {
echo '<br><span class="description">' . esc_html( $a['description'] ) . '</span>';
}
echo '</td><td>' . esc_html( Format::money( $a['amount_minor'], $cur ) ) . '</td>';
echo '<td>' . esc_html( Matcher::EVERY === $a['mode'] ? 'Every time it adds up' : 'Exactly this amount' ) . '</td>';
echo '<td>' . esc_html( 0 === $a['goal_id'] ? 'All goals' : ( $goals[ $a['goal_id'] ] ?? 'Goal #' . $a['goal_id'] ) ) . '</td>';
echo '<td>' . (int) $a['sort'] . '</td><td class="sg-actions">';
echo '</td>' . Admin::td( 'Amount' ) . esc_html( Format::money( $a['amount_minor'], $cur ) ) . '</td>';
echo Admin::td( 'Triggers' ) . esc_html( Matcher::EVERY === $a['mode'] ? 'Every time it adds up' : 'Exactly this amount' ) . '</td>';
echo Admin::td( 'Applies to' ) . esc_html( 0 === $a['goal_id'] ? 'All goals' : ( $goals[ $a['goal_id'] ] ?? 'Goal #' . $a['goal_id'] ) ) . '</td>';
echo Admin::td( 'Order' ) . (int) $a['sort'] . '</td>' . Admin::td( 'Actions', 'sg-actions' );
echo '<a class="button" href="' . esc_url( self::url( array( 'edit' => $id ) ) ) . '">Edit</a> ';
Admin::form( 'sg_action_toggle', array( 'action_id' => $id, 'enabled' => $a['enabled'] ? 0 : 1 ), 'sg-inline' );
echo '<button class="button">' . ( $a['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
@@ -122,7 +122,7 @@ final class ActionsPage {
echo '<button class="button button-link-delete" data-confirm="Delete this reward? Rewards already waiting in the queue stay there.">Delete</button></form>';
echo '</td></tr>';
}
echo '</tbody></table></div>';
echo Admin::tableClose() . '</div>';
}
private static function renderForm( int $id ): void {
+29 -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' ),
);
@@ -170,10 +171,37 @@ final class Admin {
echo '<div class="wrap sg-admin"><h1>' . esc_html( $title ) . '</h1>';
self::notices();
if ( PayPalConnector::isConnected() && '' === (string) Settings::get( 'paypal_webhook_id', '' ) ) {
echo '<div class="notice notice-warning"><p>' . esc_html( 'PayPal is connected, but the webhook is not set up yet, so refunds/reversals will not be noticed. Open Settings and press "Save and test connection" to register it.' ) . '</p></div>';
echo '<div class="notice notice-warning"><p>' . esc_html( 'PayPal is connected, but the webhook is not set up yet, so payments that PayPal confirms later (for example under review) will not be completed automatically. Note that refunds and chargebacks done in PayPal are NOT reflected in goal totals, timers, counters or tiers, with or without the webhook. Open Settings and press "Save and test connection" to register it.' ) . '</p></div>';
}
}
/**
* Open a table inside a keyboard-focusable scroll region. $headers is a list of column labels (an empty
* label is a visually hidden column). $cards=true turns rows into labelled cards on phones (cells need
* td() labels); false keeps sideways scrolling and shows a swipe hint on phones.
*
* @param string[] $headers
*/
public static function tableOpen( array $headers, string $label, bool $cards = true ): string {
$h = static fn( string $s ): string => htmlspecialchars( $s, ENT_QUOTES, 'UTF-8' );
$out = $cards ? '' : '<p class="sg-swipe-hint">Swipe sideways to see more</p>';
$out .= '<div class="sg-scroll' . ( $cards ? ' sg-scroll-cards' : '' ) . '" tabindex="0" role="region" aria-label="' . $h( $label ) . '">';
$out .= '<table class="widefat striped sg-table' . ( $cards ? ' sg-cards' : '' ) . '"><thead><tr>';
foreach ( $headers as $t ) {
$out .= '' === $t ? '<th><span class="screen-reader-text">Actions</span></th>' : '<th>' . $h( $t ) . '</th>';
}
return $out . '</tr></thead><tbody>';
}
public static function tableClose(): string {
return '</tbody></table></div>';
}
/** Opening <td> carrying the column label that phone cards print before the value. */
public static function td( string $label, string $class = '' ): string {
return '<td' . ( '' !== $class ? ' class="' . htmlspecialchars( $class, ENT_QUOTES, 'UTF-8' ) . '"' : '' ) . ' data-label="' . htmlspecialchars( $label, ENT_QUOTES, 'UTF-8' ) . '">';
}
public static function close(): void {
echo '</div>';
}
+52 -13
View File
@@ -48,6 +48,44 @@ final class AlertsPage {
);
}
/**
* Media column parts for one alert. $existing maps attachment id => true for ids still in the Media Library.
*
* @param array<string,mixed> $d
* @param array<int,bool> $existing
* @return array<int,array{0:string,1:bool}> list of [label, missing]
*/
public static function mediaParts( array $d, array $existing ): array {
$parts = array();
$vid = (int) ( $d['visual_id'] ?? 0 );
if ( $vid > 0 ) {
$video = 'video' === ( $d['visual_type'] ?? '' );
$parts[] = isset( $existing[ $vid ] ) ? array( $video ? 'Video' : 'Picture/GIF', false ) : array( $video ? 'Video missing' : 'Picture missing', true );
}
$sid = (int) ( $d['sound_id'] ?? 0 );
if ( $sid > 0 ) {
$parts[] = isset( $existing[ $sid ] ) ? array( 'Sound', false ) : array( 'Sound missing', true );
}
return $parts;
}
/** One query: which of the alerts' attachments still exist. @return array<int,bool> */
private static function existingAttachments( array $defs ): array {
$ids = array();
foreach ( $defs as $d ) {
foreach ( array( 'visual_id', 'sound_id' ) as $k ) {
if ( (int) ( $d[ $k ] ?? 0 ) > 0 ) {
$ids[ (int) $d[ $k ] ] = true;
}
}
}
if ( ! $ids ) {
return array();
}
$found = get_posts( array( 'post_type' => 'attachment', 'post_status' => 'any', 'post__in' => array_keys( $ids ), 'posts_per_page' => count( $ids ), 'fields' => 'ids', 'orderby' => 'none', 'no_found_rows' => true, 'update_post_meta_cache' => false, 'update_post_term_cache' => false ) );
return array_fill_keys( array_map( 'intval', $found ), true );
}
/* ---------------------------------------------------------------- render */
public static function render(): void {
@@ -89,24 +127,22 @@ final class AlertsPage {
echo '<p>No custom alerts yet.</p></div>';
return;
}
echo '<table class="widefat striped sg-table"><thead><tr><th>Name</th><th>Plays when</th><th>Applies to</th><th>Media</th><th>Order</th><th>Actions</th></tr></thead><tbody>';
echo Admin::tableOpen( array( 'Name', 'Plays when', 'Applies to', 'Media', 'Order', 'Actions' ), 'Your alerts' );
$existing = self::existingAttachments( $defs );
foreach ( $defs as $d ) {
$id = (int) $d['id'];
$when = 'reward' === $d['trigger_type']
? 'Reward: ' . ( $rewards[ $d['action_id'] ] ?? 'a reward that was deleted' )
: 'Donation of at least ' . Format::money( (int) $d['min_minor'], $cur );
$media = array();
if ( $d['visual_id'] ) {
$media[] = 'video' === $d['visual_type'] ? 'Video' : 'Picture/GIF';
foreach ( self::mediaParts( $d, $existing ) as [ $mLabel, $mMissing ] ) {
$media[] = $mMissing ? '<span class="sga-missing">' . esc_html( $mLabel ) . '</span>' : esc_html( $mLabel );
}
if ( $d['sound_id'] ) {
$media[] = 'Sound';
}
echo '<tr' . ( $d['enabled'] ? '' : ' class="sg-off"' ) . '><td><strong>' . esc_html( $d['title'] ) . '</strong></td>';
echo '<td>' . esc_html( $when ) . '</td>';
echo '<td>' . esc_html( 0 === $d['goal_id'] ? 'All goals' : ( $goals[ $d['goal_id'] ] ?? 'Goal #' . $d['goal_id'] ) ) . '</td>';
echo '<td>' . esc_html( $media ? implode( ', ', $media ) : 'Text only' ) . '</td>';
echo '<td>' . (int) $d['sort'] . '</td><td class="sg-actions">';
echo '<tr' . ( $d['enabled'] ? '' : ' class="sg-off"' ) . '>' . Admin::td( 'Name' ) . '<strong>' . esc_html( $d['title'] ) . '</strong></td>';
echo Admin::td( 'Plays when' ) . esc_html( $when ) . '</td>';
echo Admin::td( 'Applies to' ) . esc_html( 0 === $d['goal_id'] ? 'All goals' : ( $goals[ $d['goal_id'] ] ?? 'Goal #' . $d['goal_id'] ) ) . '</td>';
echo Admin::td( 'Media' ) . ( $media ? implode( ', ', $media ) : 'Text only' ) . '</td>';
echo Admin::td( 'Order' ) . (int) $d['sort'] . '</td>' . Admin::td( 'Actions', 'sg-actions' );
echo '<a class="button" href="' . esc_url( self::url( array( 'edit' => $id ) ) ) . '">Edit</a> ';
Admin::form( 'sg_alert_toggle', array( 'alert_id' => $id, 'enabled' => $d['enabled'] ? 0 : 1 ), 'sg-inline' );
echo '<button class="button">' . ( $d['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
@@ -114,7 +150,7 @@ final class AlertsPage {
echo '<button class="button button-link-delete" data-confirm="Delete this alert? Your media files stay in the Media Library.">Delete</button></form>';
echo '</td></tr>';
}
echo '</tbody></table></div>';
echo Admin::tableClose() . '</div>';
}
private static function mediaField( string $name, string $label, string $kind, int $id, string $help ): void {
@@ -178,6 +214,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 +225,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 -12
View File
@@ -44,18 +44,18 @@ final class DonationsPage {
foreach ( Store::goals()->all() as $g ) {
$goals[ (int) $g['id'] ] = (string) $g['title'];
}
echo '<table class="widefat striped sg-table"><thead><tr><th>Date</th><th>Donor</th><th>Amount</th><th>Fee</th><th>Total paid</th><th>Goal</th><th>Status</th><th>Message</th></tr></thead><tbody>';
echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Fee', 'Total paid', 'Goal', 'Status', 'Message' ), 'Donations', false );
foreach ( $res['rows'] as $r ) {
$cur = Format::currency( $r['currency'] );
$test = Format::isTest( $r );
echo '<tr><td>' . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '</td>';
echo '<td>' . esc_html( Format::donorName( $r ) ) . ( $test ? ' <span class="sg-badge sg-test">TEST</span>' : '' ) . '</td>';
echo '<td>' . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td><td>' . esc_html( Format::money( (int) $r['fee_minor'], $cur ) ) . '</td><td>' . esc_html( Format::money( (int) $r['total_minor'], $cur ) ) . '</td>';
echo '<td>' . esc_html( $test ? '(test)' : ( $goals[ (int) $r['goal_id'] ] ?? '#' . (int) $r['goal_id'] ) ) . '</td>';
echo '<td>' . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' <span class="sg-badge sg-' . esc_attr( (string) $r['moderation'] ) . '">message ' . esc_html( (string) $r['moderation'] ) . '</span>' ) . '</td>';
echo '<td>' . esc_html( (string) $r['message'] ) . '</td></tr>';
echo '<tr>' . Admin::td( 'Date' ) . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '</td>';
echo Admin::td( 'Donor' ) . esc_html( Format::donorName( $r ) ) . ( $test ? ' <span class="sg-badge sg-test">TEST</span>' : '' ) . '</td>';
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'] ) . '">message ' . esc_html( (string) $r['moderation'] ) . '</span>' ) . '</td>';
echo Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '</td></tr>';
}
echo '</tbody></table>';
echo Admin::tableClose();
$pages = (int) ceil( $res['total'] / self::PER_PAGE );
if ( $pages > 1 ) {
echo '<div class="tablenav"><div class="tablenav-pages">' . wp_kses_post( (string) paginate_links( array(
@@ -83,18 +83,18 @@ final class DonationsPage {
Admin::close();
return;
}
echo '<table class="widefat striped sg-table"><thead><tr><th>Date</th><th>Donor</th><th>Amount</th><th>Message</th><th>Decision</th></tr></thead><tbody>';
echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Message', 'Decision' ), 'Messages waiting for review' );
foreach ( $res['rows'] as $r ) {
$cur = Format::currency( $r['currency'] );
echo '<tr><td>' . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '</td><td>' . esc_html( Format::donorName( $r ) ) . '</td>';
echo '<td>' . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td><td>' . esc_html( (string) $r['message'] ) . '</td><td class="sg-actions">';
echo '<tr>' . Admin::td( 'Date' ) . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '</td>' . Admin::td( 'Donor' ) . esc_html( Format::donorName( $r ) ) . '</td>';
echo Admin::td( 'Amount' ) . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '</td>' . Admin::td( 'Message' ) . esc_html( (string) $r['message'] ) . '</td>' . Admin::td( 'Decision', 'sg-actions' );
foreach ( array( 'approved' => 'Approve', 'rejected' => 'Reject' ) as $to => $lbl ) {
Admin::form( 'sg_moderate', array( 'donation_id' => (int) $r['id'], 'decision' => $to ), 'sg-inline' );
echo '<button class="button' . ( 'approved' === $to ? ' button-primary' : '' ) . '">' . esc_html( $lbl ) . '</button></form> ';
}
echo '</td></tr>';
}
echo '</tbody></table>';
echo Admin::tableClose();
Admin::close();
}
+15 -15
View File
@@ -40,17 +40,17 @@ final class GoalsPage {
Admin::close();
return;
}
echo '<table class="widefat striped sg-table"><thead><tr><th>Goal</th><th>Status</th><th>Raised</th><th>Dates</th><th>Actions</th></tr></thead><tbody>';
echo Admin::tableOpen( array( 'Goal', 'Status', 'Raised', 'Dates', 'Actions' ), 'Goals' );
foreach ( $goals as $g ) {
$gid = (int) $g['id'];
$cur = Format::currency( $g['currency'] );
$raised = Store::goals()->raised_minor( $gid );
$target = (int) $g['target_minor'];
$pct = $target > 0 ? min( 100, intdiv( $raised * 100, $target ) ) : 0;
echo '<tr><td><strong>' . esc_html( (string) $g['title'] ) . '</strong><br><span class="description">ID ' . $gid . ' &middot; <code>[streamgoals_donate goal="' . $gid . '"]</code></span></td>';
echo '<td><span class="sg-badge sg-' . esc_attr( (string) $g['status'] ) . '">' . esc_html( self::STATUSES[ $g['status'] ] ?? (string) $g['status'] ) . '</span></td>';
echo '<td>' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div>' . ( ! empty( $g['close_at_target'] ) ? '<span class="description">Closes at target</span>' : '' ) . '</td>';
echo '<td>' . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '<br>' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '</td><td class="sg-actions">';
echo '<tr>' . Admin::td( 'Goal' ) . '<strong>' . esc_html( (string) $g['title'] ) . '</strong><br><span class="description">ID ' . $gid . ' &middot; <code>[streamgoals_donate goal="' . $gid . '"]</code></span></td>';
echo Admin::td( 'Status' ) . '<span class="sg-badge sg-' . esc_attr( (string) $g['status'] ) . '">' . esc_html( self::STATUSES[ $g['status'] ] ?? (string) $g['status'] ) . '</span></td>';
echo Admin::td( 'Raised' ) . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div>' . ( ! empty( $g['close_at_target'] ) ? '<span class="description">Closes at target</span>' : '' ) . '</td>';
echo Admin::td( 'Dates' ) . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '<br>' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '</td>' . Admin::td( 'Actions', 'sg-actions' );
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'edit', 'goal' => $gid ) ) ) . '">Edit</a> ';
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ) ) . '">Rules</a> ';
$nt = $tierCounts[ $gid ] ?? 0;
@@ -69,7 +69,7 @@ final class GoalsPage {
echo '<button class="button button-link-delete" data-confirm="Delete this goal and its rules? This cannot be undone.">Delete</button></form>';
echo '</td></tr>';
}
echo '</tbody></table>';
echo Admin::tableClose();
Admin::close();
}
@@ -216,22 +216,22 @@ final class GoalsPage {
if ( ! $tiers ) {
echo '<p>No tiers yet. This goal works as a single target until you add one.</p>';
} else {
echo '<table class="widefat striped sg-table"><thead><tr><th>#</th><th>Unlock</th><th>Target</th><th>Status</th><th>Actions</th></tr></thead><tbody>';
echo Admin::tableOpen( array( '#', 'Unlock', 'Target', 'Status', 'Actions' ), 'Tiers' );
foreach ( TierPolicy::sorted( $tiers ) as $i => $t ) {
$tid = (int) $t['id'];
$status = TierPolicy::status( $tiers, $t );
$label = 'reached' === $status ? 'Reached on ' . get_date_from_gmt( (string) $t['reached_at'], 'Y-m-d H:i' ) : ( 'current' === $status ? 'Current' : 'Upcoming' );
echo '<tr><td>' . (int) ( $i + 1 ) . '</td><td><strong>' . esc_html( $t['title'] ) . '</strong>';
echo '<tr>' . Admin::td( '#' ) . (int) ( $i + 1 ) . '</td>' . Admin::td( 'Unlock' ) . '<strong>' . esc_html( $t['title'] ) . '</strong>';
if ( '' !== $t['description'] ) {
echo '<br><span class="description">' . esc_html( $t['description'] ) . '</span>';
}
echo '</td><td>' . esc_html( Format::money( (int) $t['target_minor'], $cur ) ) . '</td>';
echo '<td><span class="sg-badge sg-' . ( 'reached' === $status ? 'complete' : ( 'current' === $status ? 'active' : 'paused' ) ) . '">' . esc_html( $label ) . '</span></td><td class="sg-actions">';
echo '</td>' . Admin::td( 'Target' ) . esc_html( Format::money( (int) $t['target_minor'], $cur ) ) . '</td>';
echo Admin::td( 'Status' ) . '<span class="sg-badge sg-' . ( 'reached' === $status ? 'complete' : ( 'current' === $status ? 'active' : 'paused' ) ) . '">' . esc_html( $label ) . '</span></td>' . Admin::td( 'Actions', 'sg-actions' );
echo '<a class="button" href="' . esc_url( self::tiersUrl( $goalId, array( 'tier' => $tid ) ) ) . '#sg-tier-form">Edit</a> ';
Admin::form( 'sg_tier_delete', array( 'goal_id' => $goalId, 'tier_id' => $tid ), 'sg-inline sg-confirm' );
echo '<button class="button button-link-delete" data-confirm="Delete this tier?">Delete</button></form></td></tr>';
}
echo '</tbody></table>';
echo Admin::tableClose();
}
echo '</div>';
@@ -331,24 +331,24 @@ final class GoalsPage {
if ( ! $rules ) {
echo '<p>No rules yet. The goal bar works without any rules.</p>';
} else {
echo '<table class="widefat striped sg-table"><thead><tr><th>Rule</th><th>What it does</th><th>Actions</th></tr></thead><tbody>';
echo Admin::tableOpen( array( 'Rule', 'What it does', 'Actions' ), 'Rules' );
foreach ( $rules as $r ) {
$rid = (int) $r['id'];
echo '<tr class="' . ( $r['enabled'] ? '' : 'sg-off' ) . '"><td>' . esc_html( RuleConfig::TYPES[ $r['type'] ] ?? (string) $r['type'] ) . ( $r['enabled'] ? '' : ' <em>(off)</em>' ) . '</td>';
echo '<tr class="' . ( $r['enabled'] ? '' : 'sg-off' ) . '">' . Admin::td( 'Rule' ) . esc_html( RuleConfig::TYPES[ $r['type'] ] ?? (string) $r['type'] ) . ( $r['enabled'] ? '' : ' <em>(off)</em>' ) . '</td>';
try {
$summary = RuleConfig::summary( (string) $r['type'], $r['config'], $cur );
} catch ( \Throwable $e ) {
// One unreadable rule must not take down the whole screen; say what is wrong so it can be fixed or deleted.
$summary = 'Could not read this rule (' . $e->getMessage() . '). You can delete it and add it again.';
}
echo '<td>' . esc_html( $summary ) . '</td><td class="sg-actions">';
echo Admin::td( 'What it does' ) . esc_html( $summary ) . '</td>' . Admin::td( 'Actions', 'sg-actions' );
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId, 'rule' => $rid ) ) ) . '#sg-rule-form">Edit</a> ';
Admin::form( 'sg_rule_toggle', array( 'goal_id' => $goalId, 'rule_id' => $rid, 'enabled' => $r['enabled'] ? 0 : 1 ), 'sg-inline' );
echo '<button class="button">' . ( $r['enabled'] ? 'Turn off' : 'Turn on' ) . '</button></form> ';
Admin::form( 'sg_rule_delete', array( 'goal_id' => $goalId, 'rule_id' => $rid ), 'sg-inline sg-confirm' );
echo '<button class="button button-link-delete" data-confirm="Delete this rule?">Delete</button></form></td></tr>';
}
echo '</tbody></table>';
echo Admin::tableClose();
}
echo '</div>';
+13 -1
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;
@@ -20,7 +21,7 @@ final class OverlaysPage {
/** @return array{url:string,base:string,sep:string} */
public static function widgetUrl( string $widget ): array {
$token = OverlayController::token();
$token = OverlayController::ensure_token();
if ( get_option( 'permalink_structure' ) ) {
$base = home_url( '/streamgoals-overlay/' . rawurlencode( $token ) . '/' . rawurlencode( $widget ) . '/' );
return array( 'url' => $base, 'base' => $base, 'sep' => '?' );
@@ -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 ) ) ) );
+4 -1
View File
@@ -59,7 +59,9 @@ final class SettingsPage {
}
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). Behind a proxy, every visitor can look like the same address, and a busy moment, like a raid, could block donations. <strong>Automatic</strong> recognises Cloudflare by its published addresses and counts each visitor separately; it ignores forged headers from anywhere else. For another kind of proxy, choose its option here, but only if <em>all</em> traffic to your site really goes through it.</p>';
self::ipDiagnostics( (string) $s['visitor_ip_header'] );
echo '</td></tr></table></div>';
echo '</td></tr>';
echo '<tr><th scope="row">Uninstall</th><td><label><input type="checkbox" name="delete_data_on_uninstall" value="1"' . checked( ! empty( $s['delete_data_on_uninstall'] ), true, false ) . '> Delete all data when the plugin is deleted</label>';
echo '<p class="description"><strong>When you delete the plugin from the Plugins screen, also delete ALL donations, goals, rules, rewards, alerts, tiers and settings. This cannot be undone. Leave off to keep your data if you reinstall later.</strong></p></td></tr></table></div>';
$rel = \StreamGoals\Update\Updater::latest();
echo '<div class="sg-card"><h2>Plugin updates</h2><table class="form-table" role="presentation">';
@@ -148,6 +150,7 @@ final class SettingsPage {
}
$upd['funding_card'] = ! empty( $post['funding_card'] );
$upd['funding_paylater'] = ! empty( $post['funding_paylater'] );
$upd['delete_data_on_uninstall'] = ! empty( $post['delete_data_on_uninstall'] );
$upd['donation_notice'] = Input::text( $post['donation_notice'] ?? '', 200 );
$upd['moderate_messages'] = ! empty( $post['moderate_messages'] );
$upd['profanity_filter'] = ! empty( $post['profanity_filter'] );
+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 ) ) {
+23
View File
@@ -54,6 +54,29 @@ final class ClientIp {
return $fromHeader ?? $remote ?? 'unknown';
}
/**
* Rate-limit BUCKET KEY for a resolved address (never use it as the "real" IP): IPv4 unchanged, IPv4-mapped IPv6
* becomes its IPv4, any other IPv6 collapses to its /64 (one subscriber/host can rotate freely inside a /64),
* 'unknown' stays, anything unparsable becomes 'unknown'.
*/
public static function bucketKey( string $ip ): string {
$ip = trim( $ip );
if ( 'unknown' === $ip || false === filter_var( $ip, FILTER_VALIDATE_IP ) ) {
return 'unknown';
}
if ( false === filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6 ) ) {
return $ip;
}
$bin = inet_pton( $ip );
if ( false === $bin || 16 !== strlen( $bin ) ) {
return 'unknown';
}
if ( str_repeat( "\0", 10 ) . "\xff\xff" === substr( $bin, 0, 12 ) ) {
return (string) inet_ntop( substr( $bin, 12 ) );
}
return bin2hex( substr( $bin, 0, 8 ) ) . '/64';
}
private static function valid( mixed $v ): ?string {
if ( ! is_string( $v ) ) {
return null;
+3 -1
View File
@@ -8,13 +8,14 @@ namespace StreamGoals\Core;
*/
final class Installer {
public const DB_VERSION = '4';
public const DB_VERSION = '5';
public static function activate(): void {
self::install_schema();
if ( false === get_option( 'sg_settings' ) ) {
add_option( 'sg_settings', Settings::defaults(), '', false );
}
Settings::ensure_overlay_token(); // never generated by a public request (see OverlayController)
}
/** Run on plugins_loaded so upgrades apply without re-activation. */
@@ -138,6 +139,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)
+19
View File
@@ -25,6 +25,25 @@ final class Maintenance {
wp_clear_scheduled_hook( self::HOOK );
}
/**
* The single definition of "abandoned checkout", mirrored by the DELETE below (MaintenancePurgeTest checks both).
* Never purgeable: not pending, younger than MAX_AGE_DAYS, a test row (goal_id 0), or ANY row carrying PayPal capture
* evidence (a capture id, even from a PENDING/under-review capture: PayPal may still finalize it by webhook).
*
* @param array|object $row status, goal_id, paypal_capture_id, created_at (UTC 'Y-m-d H:i:s')
*/
public static function isPurgeable( array|object $row, int $now ): bool {
$r = (array) $row;
if ( 'pending' !== (string) ( $r['status'] ?? '' ) || (int) ( $r['goal_id'] ?? 0 ) <= 0 ) {
return false;
}
if ( '' !== trim( (string) ( $r['paypal_capture_id'] ?? '' ) ) ) {
return false;
}
$created = strtotime( (string) ( $r['created_at'] ?? '' ) . ' UTC' );
return false !== $created && $created < $now - self::MAX_AGE_DAYS * DAY_IN_SECONDS;
}
/** @return int Number of rows removed. */
public static function purge_abandoned(): int {
global $wpdb;
+1
View File
@@ -20,6 +20,7 @@ final class Plugin {
public static function boot(): void {
Installer::maybe_upgrade();
Maintenance::register();
Privacy::register();
foreach ( self::MODULES as $module ) {
if ( class_exists( $module ) && method_exists( $module, 'register' ) ) {
$module::register();
+47
View File
@@ -0,0 +1,47 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/** Suggested privacy-policy text (Settings > Privacy > Policy Guide). Describes only what the code actually does. */
final class Privacy {
public const DOMAIN = 'streamgoals-donate';
public static function register(): void {
add_action( 'admin_init', array( self::class, 'add_policy_content' ) );
}
public static function add_policy_content(): void {
if ( ! function_exists( 'wp_add_privacy_policy_content' ) ) {
return;
}
wp_add_privacy_policy_content( 'StreamGoals Donate', self::content() );
}
/** @param callable|null $t Translator taking one string (defaults to WordPress' __ with this text domain). */
public static function content( ?callable $t = null ): string {
$t ??= static fn( string $s ): string => __( $s, self::DOMAIN ); // phpcs:ignore WordPress.WP.I18n.NonSingularStringLiteralText
$html = '<div class="wp-suggested-text">';
$html .= '<p class="privacy-policy-tutorial">' . $t( 'Suggested text for your privacy policy. Review it and adjust it to how you use the plugin, and to the laws that apply to you.' ) . '</p>';
$html .= '<strong class="privacy-policy-tutorial">' . $t( 'Suggested text:' ) . '</strong> ';
$html .= '<h2>' . $t( 'Donations' ) . '</h2>';
$html .= '<p>' . $t( 'When you make a donation on this site, we store the amount, the currency, the date and time, the PayPal order and capture identifiers, and the display name you entered, unless you chose to donate anonymously. The name of an anonymous donor is never stored. If you write a message with your donation, we store that message too, so please do not put personal details in it.' ) . '</p>';
$html .= '<p>' . $t( 'We do not store your email address, postal address or payment card details. Payments are processed by PayPal, which collects and handles those details under its own privacy statement:' ) . ' <a href="https://www.paypal.com/webapps/mpp/ua/privacy-full" target="_blank" rel="noopener noreferrer">https://www.paypal.com/webapps/mpp/ua/privacy-full</a></p>';
$html .= '<p>' . $t( 'The donation form loads PayPal\'s payment script from paypal.com, so PayPal receives your IP address and browser information when the form is shown.' ) . '</p>';
$html .= '<h2>' . $t( 'How long we keep data' ) . '</h2>';
$html .= '<p>' . $t( 'Donation records are kept until the site owner deletes them. The site owner can export them as a CSV file. Checkouts that were started but never paid are removed automatically after a week.' ) . '</p>';
$html .= '<h2>' . $t( 'Abuse protection' ) . '</h2>';
$html .= '<p>' . $t( 'To stop abuse, the number of donation requests from one visitor is limited. For this, a one-way hash of the visitor\'s IP address is used as the name of a temporary cache entry (a WordPress transient) that expires after a few minutes. The IP address itself is not written to the donation records. Expired entries can remain in the database until WordPress cleans them up, and on sites with a persistent object cache they are kept in that cache instead.' ) . '</p>';
$html .= '<h2>' . $t( 'Stream overlays' ) . '</h2>';
$html .= '<p>' . $t( 'The overlay pages shown in broadcasting software load no third-party scripts, fonts or services. They show donor display names and messages (not the names of anonymous donors) and any images or sounds the site owner chose from the Media Library.' ) . '</p>';
$html .= '</div>';
return $html;
}
}
+11
View File
@@ -40,6 +40,7 @@ final class Settings {
'funding_paylater' => false, // show PayPal "Pay Later" button
'update_token' => '', // optional Gitea read token (only while the update repo is private)
'funding_card' => true, // show the Debit/Credit Card button
'delete_data_on_uninstall' => false, // when the plugin is deleted, also drop all tables/options (see Core\Uninstaller)
);
}
@@ -58,6 +59,16 @@ final class Settings {
update_option( 'sg_settings', array_merge( self::all(), $allowed ), false );
}
/** Generates the overlay token if none is stored (a DB write: only from activation or an authenticated admin screen). */
public static function ensure_overlay_token(): string {
$token = (string) self::get( 'overlay_token', '' );
if ( strlen( $token ) < 32 ) {
$token = bin2hex( random_bytes( 16 ) );
self::update( array( 'overlay_token' => $token ) );
}
return $token;
}
public static function fee_calculator(): FeeCalculator {
return new FeeCalculator( (int) self::get( 'fee_percent_bps' ), (int) self::get( 'fee_fixed_minor' ) );
}
+110
View File
@@ -0,0 +1,110 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Core;
/**
* Removes what the plugin created. Dependency-free on purpose: uninstall.php loads this single file with
* require_once, without the plugin's autoloader or constants.
*
* Always removed on uninstall: the cron event and all transients (they are only caches/notices).
* Removed ONLY when the owner ticked "delete data on uninstall": every sg_ table and option.
*
* Keep the lists below in sync with Installer (tables) and every add/update_option call; UninstallerTest fails
* when something is missing.
*/
final class Uninstaller {
public const CRON_HOOK = 'sg_purge_abandoned';
/** @return string[] Table names without the WordPress prefix. */
public static function tables(): array {
return array(
'sg_goals',
'sg_donations',
'sg_rules',
'sg_rule_events',
'sg_state',
'sg_actions',
'sg_action_events',
'sg_alert_defs',
'sg_goal_tiers',
);
}
/** @return string[] Option names (per site). */
public static function options(): array {
return array(
'sg_settings',
'sg_db_version',
'sg_overlay_epoch',
'sg_overlay_rules_version',
'sg_currency',
'sg_paypal_verified',
'sg_donate_page_id',
'sg_wizard_goal_id',
);
}
/** @return string[] Fixed-name site transients. */
public static function site_transients(): array {
return array( 'sg_update_release' );
}
/** @return string[] Prefixes of transients whose names carry a suffix (rate limiter hashes, per-user notices, cached PayPal access token, webhook de-dupe markers). */
public static function transient_prefixes(): array {
return array( 'sg_rl_', 'sg_notice_', 'sg_pp_token_', 'sg_wh_' );
}
/** Whether this site's saved settings ask for all data to be deleted. */
public static function wants_data_deleted( mixed $settings ): bool {
return is_array( $settings ) && ! empty( $settings['delete_data_on_uninstall'] );
}
/** Drops every plugin table for the current site prefix. @param object $wpdb wpdb-like (prefix, query). */
public static function drop_tables( object $wpdb ): void {
foreach ( self::tables() as $t ) {
$wpdb->query( 'DROP TABLE IF EXISTS `' . $wpdb->prefix . $t . '`' ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared
}
}
/** Deletes the dynamically named transients (and their timeouts) straight from the options table. @param object $wpdb wpdb-like (options, esc_like, prepare, query). */
public static function delete_dynamic_transients( object $wpdb ): void {
foreach ( self::transient_prefixes() as $prefix ) {
foreach ( array( '_transient_', '_transient_timeout_' ) as $kind ) {
$like = $wpdb->esc_like( $kind . $prefix ) . '%';
$wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $like ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
}
}
}
/** Uninstall for the current site (call inside switch_to_blog on multisite). */
public static function run_site( object $wpdb ): void {
$delete = self::wants_data_deleted( get_option( 'sg_settings', array() ) );
wp_clear_scheduled_hook( self::CRON_HOOK );
self::delete_dynamic_transients( $wpdb );
if ( $delete ) {
self::drop_tables( $wpdb );
foreach ( self::options() as $o ) {
delete_option( $o );
}
}
}
/** Entry point for uninstall.php. */
public static function run(): void {
global $wpdb;
if ( function_exists( 'is_multisite' ) && is_multisite() ) {
foreach ( get_sites( array( 'fields' => 'ids', 'number' => 0 ) ) as $id ) {
switch_to_blog( (int) $id );
self::run_site( $wpdb );
restore_current_blog();
}
} else {
self::run_site( $wpdb );
}
foreach ( self::site_transients() as $t ) {
delete_site_transient( $t );
}
}
}
+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;
+13 -3
View File
@@ -23,17 +23,20 @@ final class CaptureFinalizer {
* @param object|array $row Donation row (status, total_minor, currency).
* @param callable $markCompleted fn(int $id, string $captureId): bool atomic pending->completed
* @param callable $notifyApplied fn(int $id): void
* @param callable|null $recordCapture fn(int $id, string $captureId): void Called when PayPal returned a capture id but the
* donation is NOT finalized (PENDING/under review/amount mismatch). Persists the id so the
* row is never mistaken for an abandoned checkout and the later webhook can find it.
*/
public static function finalize( object|array $row, string $paypalStatus, string $captureId, ?Money $amount, callable $markCompleted, callable $notifyApplied ): string {
public static function finalize( object|array $row, string $paypalStatus, string $captureId, ?Money $amount, callable $markCompleted, callable $notifyApplied, ?callable $recordCapture = null ): string {
$r = (object) $row;
if ( 'pending' !== (string) $r->status ) {
return self::DUPLICATE;
}
if ( 'COMPLETED' !== $paypalStatus || '' === $captureId ) {
return self::PENDING;
return self::pendingWith( $r, $captureId, $recordCapture );
}
if ( ! $amount || $amount->minor !== (int) $r->total_minor || $amount->currency !== (string) $r->currency ) {
return self::PENDING;
return self::pendingWith( $r, $captureId, $recordCapture );
}
if ( $markCompleted( (int) $r->id, $captureId ) ) {
$notifyApplied( (int) $r->id );
@@ -41,4 +44,11 @@ final class CaptureFinalizer {
}
return self::DUPLICATE;
}
private static function pendingWith( object $r, string $captureId, ?callable $recordCapture ): string {
if ( '' !== $captureId && null !== $recordCapture ) {
$recordCapture( (int) $r->id, $captureId );
}
return self::PENDING;
}
}
+4 -3
View File
@@ -116,9 +116,10 @@ final class Client {
* @param array<string,mixed> $headers Incoming webhook request headers (any case; '-' or '_').
*/
public function verifyWebhook( array $headers, string $rawBody, string $webhookId ): bool {
$h = array();
foreach ( $headers as $k => $v ) {
$h[ strtolower( str_replace( '-', '_', (string) $k ) ) ] = is_array( $v ) ? (string) ( $v[0] ?? '' ) : (string) $v;
$h = WebhookGuard::normalizeHeaders( $headers );
// Local pre-checks (headers present, paypal.com cert_url, replay window, size): never spend an outbound call on junk.
if ( null !== WebhookGuard::check( $headers, $rawBody, time() ) ) {
return false;
}
$event = json_decode( $rawBody );
if ( ! is_object( $event ) || '' === $webhookId ) {
+14
View File
@@ -84,6 +84,20 @@ final class DonationStore {
return 1 === $n;
}
/**
* Remember the PayPal capture id of a capture that is not final yet (PENDING / under review). Only touches a
* still-pending row that has no capture id; never changes the status. This is the "PayPal took the money" evidence
* that keeps Maintenance::purge_abandoned away and lets the COMPLETED webhook find the row by capture id.
*/
public static function record_capture_id( int $id, string $captureId ): bool {
global $wpdb;
if ( '' === $captureId ) {
return false;
}
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET paypal_capture_id = %s WHERE id = %d AND status = 'pending' AND (paypal_capture_id IS NULL OR paypal_capture_id = '')", $captureId, $id ) );
return 1 === $n;
}
/** Hand a freshly completed donation to the rules engine (if present). Never throws. */
public static function notify_applied( int $id ): void {
self::call_engine( 'applyDonation', $id );
+20
View File
@@ -0,0 +1,20 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/**
* PayPal-Request-Id (idempotency key) builder. Not derivable from the reusable auto-increment id alone: it is an HMAC
* keyed with the site's secret salt over kind + donation id + created_at, so a re-used id (after rows are deleted and
* AUTO_INCREMENT resets) gets a different key, while a retry for the SAME donation stays identical.
*/
final class RequestId {
public const MAX_LENGTH = 108;
public static function make( string $kind, int $donationId, string $createdAt, string $salt ): string {
$kind = preg_replace( '/[^a-z]/', '', strtolower( $kind ) ) ?: 'req';
$h = hash_hmac( 'sha256', $kind . '|' . $donationId . '|' . $createdAt, $salt );
return substr( 'sg-' . $kind . '-' . $h, 0, self::MAX_LENGTH );
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\PayPal;
/**
* Cheap, local, pure pre-checks for the public webhook endpoint. They run BEFORE any outbound PayPal call so an
* anonymous flood cannot make this site hit PayPal's API. They are only a filter: PayPal's own
* verify-webhook-signature call stays the authority on whether an event is genuine.
*/
final class WebhookGuard {
public const MAX_BODY_BYTES = 65536;
public const MAX_SKEW_SECONDS = 3600;
public const IP_LIMIT = 120; // per visitor bucket per minute (PayPal retries and uses several IPs)
public const GLOBAL_LIMIT = 600; // whole site per minute
public const WINDOW = 60;
public const REQUIRED = array( 'paypal_transmission_id', 'paypal_transmission_time', 'paypal_transmission_sig', 'paypal_cert_url', 'paypal_auth_algo' );
/** Per-bucket then global fixed-window limit. True when the request may proceed. */
public static function admit( RateLimiter $limiter, string $ipBucket ): bool {
return $limiter->allow( 'webhook|' . $ipBucket, self::IP_LIMIT, self::WINDOW )
&& $limiter->allow( 'webhook|*global*', self::GLOBAL_LIMIT, self::WINDOW );
}
/** Lower-cases header names and maps '-' to '_'. @param array<string,mixed> $headers @return array<string,string> */
public static function normalizeHeaders( array $headers ): array {
$h = array();
foreach ( $headers as $k => $v ) {
$h[ strtolower( str_replace( '-', '_', (string) $k ) ) ] = is_array( $v ) ? (string) ( $v[0] ?? '' ) : (string) $v;
}
return $h;
}
/**
* @param array<string,mixed> $headers
* @return array{status:int,code:string}|null Null when the request may be sent on to PayPal for verification.
*/
public static function check( array $headers, string $rawBody, int $now ): ?array {
if ( strlen( $rawBody ) > self::MAX_BODY_BYTES ) {
return array( 'status' => 413, 'code' => 'sg_webhook_too_large' );
}
$h = self::normalizeHeaders( $headers );
foreach ( self::REQUIRED as $n ) {
if ( '' === trim( $h[ $n ] ?? '' ) ) {
return array( 'status' => 401, 'code' => 'sg_webhook_headers' );
}
}
if ( ! self::isPayPalCertUrl( $h['paypal_cert_url'] ) ) {
return array( 'status' => 401, 'code' => 'sg_webhook_cert_url' );
}
if ( ! self::timeWithinWindow( $h['paypal_transmission_time'], $now ) ) {
return array( 'status' => 401, 'code' => 'sg_webhook_time' );
}
return null;
}
/** https, no credentials/odd port, host is paypal.com or a subdomain of it. */
public static function isPayPalCertUrl( string $url ): bool {
$p = parse_url( trim( $url ) );
if ( ! is_array( $p ) || 'https' !== strtolower( (string) ( $p['scheme'] ?? '' ) ) || isset( $p['user'] ) || isset( $p['pass'] ) ) {
return false;
}
if ( isset( $p['port'] ) && 443 !== (int) $p['port'] ) {
return false;
}
$host = strtolower( (string) ( $p['host'] ?? '' ) );
return 'paypal.com' === $host || ( strlen( $host ) > 11 && str_ends_with( $host, '.paypal.com' ) );
}
/** ISO-8601 timestamp within +-MAX_SKEW_SECONDS of $now; unparsable is rejected. */
public static function timeWithinWindow( string $iso, int $now ): bool {
$iso = trim( $iso );
if ( 1 !== preg_match( '/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:?\d{2})$/', $iso ) ) {
return false;
}
$t = strtotime( $iso );
return false !== $t && abs( $now - $t ) <= self::MAX_SKEW_SECONDS;
}
}
+32 -7
View File
@@ -12,6 +12,7 @@ use StreamGoals\PayPal\DonationStore;
use StreamGoals\PayPal\OrderValidator;
use StreamGoals\PayPal\PayPalException;
use StreamGoals\PayPal\RateLimiter;
use StreamGoals\PayPal\RequestId;
use StreamGoals\PayPal\ValidationException;
use StreamGoals\PayPal\WpCache;
@@ -20,6 +21,9 @@ final class DonateController {
private const NS = 'streamgoals/v1';
/** Generous site-wide ceiling for POST /orders (all visitors together). */
public const GLOBAL_ORDERS_PER_MIN = 120;
public static function register(): void {
add_action( 'rest_api_init', array( self::class, 'routes' ) );
add_shortcode( 'streamgoals_donate', array( self::class, 'shortcode' ) );
@@ -61,6 +65,11 @@ final class DonateController {
if ( $limited = self::limit( 'order', 10, 300 ) ) {
return $limited;
}
// Site-wide ceiling (checked after the per-visitor limit so one noisy visitor cannot burn it): rotating addresses
// (botnet, IPv6) still cannot flood the pending table or PayPal.
if ( ! ( new RateLimiter( new WpCache() ) )->allow( 'order|*global*', self::GLOBAL_ORDERS_PER_MIN, 60 ) ) {
return new \WP_Error( 'sg_rate_limited', __( 'Too many requests. Please wait a moment.', 'streamgoals-donate' ), array( 'status' => 429 ) );
}
$goal = DonationStore::goal( (int) $req->get_param( 'goal_id' ) );
if ( ! $goal ) {
return new \WP_Error( 'sg_goal_not_found', __( 'Goal not found.', 'streamgoals-donate' ), array( 'status' => 404 ) );
@@ -76,7 +85,7 @@ final class DonateController {
return new \WP_Error( 'sg_db', __( 'Could not start the donation. Please try again.', 'streamgoals-donate' ), array( 'status' => 500 ) );
}
try {
$orderId = Client::fromSettings()->createOrder( new Money( $v['total_minor'], $v['currency'] ), (string) $id, 'sg-order-' . $id );
$orderId = Client::fromSettings()->createOrder( new Money( $v['total_minor'], $v['currency'] ), (string) $id, self::request_id( 'order', $id ) );
} catch ( PayPalException $e ) {
DonationStore::delete( $id );
error_log( 'StreamGoals: create order failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
@@ -104,7 +113,7 @@ final class DonateController {
}
try {
$cap = Client::fromSettings()->captureOrder( $orderId, 'sg-capture-' . $row->id );
$cap = Client::fromSettings()->captureOrder( $orderId, self::request_id( 'capture', (int) $row->id, (string) $row->created_at ) );
} catch ( PayPalException $e ) {
if ( 'ORDER_ALREADY_CAPTURED' === $e->paypalName ) {
$fresh = DonationStore::find( (int) $row->id );
@@ -120,7 +129,8 @@ final class DonateController {
(string) $cap['capture_id'],
$cap['amount'],
array( DonationStore::class, 'mark_completed' ),
array( DonationStore::class, 'notify_applied' )
array( DonationStore::class, 'notify_applied' ),
array( DonationStore::class, 'record_capture_id' )
);
if ( CaptureFinalizer::PENDING === $res ) {
// PENDING capture (e-check/review) or amount mismatch: stay pending; the COMPLETED webhook finalizes it.
@@ -302,7 +312,25 @@ final class DonateController {
);
}
/** Idempotency key, stable per donation (created_at is stored), not derivable from the id alone. */
private static function request_id( string $kind, int $id, ?string $createdAt = null ): string {
if ( null === $createdAt ) {
$row = DonationStore::find( $id );
$createdAt = $row ? (string) $row->created_at : '';
}
return RequestId::make( $kind, $id, $createdAt, wp_salt( 'auth' ) );
}
private static function limit( string $bucket, int $max, int $window ): ?\WP_Error {
$ip = self::visitor_bucket();
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
return null;
}
return new \WP_Error( 'sg_rate_limited', __( 'Too many requests. Please wait a moment.', 'streamgoals-donate' ), array( 'status' => 429 ) );
}
/** Rate-limit bucket for the current visitor (resolved IP, IPv6 collapsed to its /64). */
public static function visitor_bucket(): string {
$server = array();
foreach ( array( 'REMOTE_ADDR', 'HTTP_CF_CONNECTING_IP', 'HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR' ) as $k ) {
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
@@ -310,9 +338,6 @@ final class DonateController {
}
}
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', 'auto' ), (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
return null;
}
return new \WP_Error( 'sg_rate_limited', __( 'Too many requests. Please wait a moment.', 'streamgoals-donate' ), array( 'status' => 429 ) );
return \StreamGoals\Core\ClientIp::bucketKey( $ip );
}
}
+19 -9
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;
@@ -29,18 +30,27 @@ final class OverlayController {
) );
}
/** Lazily generates the token (32 hex chars) on first use. */
public static function token(): string {
/** Read-only. The stored token, or '' when none is configured. Safe for public requests. */
public static function current_token(): string {
$token = (string) Settings::get( 'overlay_token', '' );
if ( strlen( $token ) < 32 ) {
$token = bin2hex( random_bytes( 16 ) );
Settings::update( array( 'overlay_token' => $token ) );
}
return $token;
return strlen( $token ) >= 32 ? $token : '';
}
/**
* Token for the admin screens; generates one (a DB write) if missing, but ONLY for a user who can manage options.
* Public requests must never reach this; they use verify_token(), which never writes.
*/
public static function ensure_token(): string {
if ( ! current_user_can( 'manage_options' ) ) {
return '';
}
return Settings::ensure_overlay_token();
}
/** Read-only compare; with no token configured nothing matches (callers answer 404). */
public static function verify_token( string $given ): bool {
return hash_equals( self::token(), $given );
$token = self::current_token();
return '' !== $token && hash_equals( $token, $given );
}
public static function handle( \WP_REST_Request $req ): \WP_REST_Response|\WP_Error {
@@ -56,7 +66,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 );
+9
View File
@@ -7,7 +7,9 @@ use StreamGoals\Core\Settings;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\Client;
use StreamGoals\PayPal\DonationStore;
use StreamGoals\PayPal\RateLimiter;
use StreamGoals\PayPal\WebhookEvent;
use StreamGoals\PayPal\WebhookGuard;
use StreamGoals\PayPal\WpCache;
/** PayPal webhook receiver. Signature is verified through PayPal's API before anything is trusted. */
@@ -34,7 +36,14 @@ final class WebhookController {
if ( '' === $webhookId ) {
return new \WP_Error( 'sg_webhook_unconfigured', 'Webhook is not configured.', array( 'status' => 503 ) );
}
if ( ! WebhookGuard::admit( new RateLimiter( new WpCache() ), DonateController::visitor_bucket() ) ) {
return new \WP_Error( 'sg_rate_limited', 'Too many requests.', array( 'status' => 429 ) );
}
$raw = $req->get_body();
$bad = WebhookGuard::check( $req->get_headers(), $raw, time() );
if ( null !== $bad ) {
return new \WP_Error( $bad['code'], 'Rejected.', array( 'status' => $bad['status'] ) );
}
if ( ! Client::fromSettings()->verifyWebhook( $req->get_headers(), $raw, $webhookId ) ) {
return new \WP_Error( 'sg_webhook_signature', 'Invalid signature.', array( 'status' => 401 ) );
}
+60
View File
@@ -0,0 +1,60 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Update;
/**
* Pure decisions for redirects of token-bearing update requests. The access token may only ever travel to the pinned
* host over https; a redirect is followed (by Updater) only when it stays on that host, with a small hop limit.
*/
final class RedirectPolicy {
public const MAX_HOPS = 3;
/**
* @param string $current URL that answered with a 3xx.
* @param string $location Its Location header (absolute or relative).
* @param string $pinnedHost Configured update host (lower case).
* @param int $hop Redirects already followed (0 for the first 3xx).
* @return string|null Absolute URL to follow with the token, or null to stop and NOT follow.
*/
public static function nextUrl( string $current, string $location, string $pinnedHost, int $hop ): ?string {
if ( $hop >= self::MAX_HOPS || '' === trim( $location ) || preg_match( '/[\x00-\x1f\x7f]/', $location ) ) {
return null;
}
$abs = self::resolve( $current, trim( $location ) );
if ( null === $abs || ! ReleaseParser::isAllowedUrl( $abs, $pinnedHost ) ) {
return null;
}
$port = parse_url( $abs, PHP_URL_PORT );
return null === $port || 443 === (int) $port ? $abs : null;
}
/** Whether the token may be attached to a request for $url. */
public static function tokenAllowed( string $url, string $pinnedHost ): bool {
if ( ! ReleaseParser::isAllowedUrl( $url, $pinnedHost ) ) {
return false;
}
$port = parse_url( $url, PHP_URL_PORT );
return null === $port || 443 === (int) $port;
}
private static function resolve( string $base, string $loc ): ?string {
if ( 1 === preg_match( '#^[a-z][a-z0-9+.\-]*://#i', $loc ) ) {
return $loc;
}
$b = parse_url( $base );
if ( ! is_array( $b ) || ! isset( $b['scheme'], $b['host'] ) ) {
return null;
}
if ( str_starts_with( $loc, '//' ) ) {
return $b['scheme'] . ':' . $loc;
}
$origin = $b['scheme'] . '://' . $b['host'] . ( isset( $b['port'] ) ? ':' . $b['port'] : '' );
if ( str_starts_with( $loc, '/' ) ) {
return $origin . $loc;
}
$dir = preg_replace( '#/[^/]*$#', '/', (string) ( $b['path'] ?? '/' ) );
return $origin . $dir . $loc;
}
}
+46 -1
View File
@@ -29,6 +29,7 @@ final class Updater {
add_filter( 'pre_set_site_transient_update_plugins', array( self::class, 'inject' ) );
add_filter( 'plugins_api', array( self::class, 'pluginInfo' ), 10, 3 );
add_filter( 'http_request_args', array( self::class, 'authorize' ), 10, 2 );
add_filter( 'pre_http_request', array( self::class, 'followSafely' ), 10, 3 );
add_action( 'upgrader_process_complete', array( self::class, 'afterUpgrade' ), 10, 2 );
add_action( 'admin_post_' . self::ACTION_CHECK, array( self::class, 'handleCheck' ) );
}
@@ -170,7 +171,7 @@ final class Updater {
}
$token = trim( (string) Settings::get( 'update_token', '' ) );
$host = self::repo()['host'];
if ( '' === $token || ! ReleaseParser::isAllowedUrl( $url, $host ) ) {
if ( '' === $token || ! RedirectPolicy::tokenAllowed( $url, $host ) ) {
return $args;
}
$args['headers'] = is_array( $args['headers'] ?? null ) ? $args['headers'] : array();
@@ -181,6 +182,50 @@ final class Updater {
return $args;
}
private static bool $following = false;
/**
* Token-bearing requests never let HTTP redirect handling carry the Authorization header anywhere: we send the
* request with redirection disabled and follow a 3xx ourselves ONLY while it stays on the pinned host (max 3 hops).
* A redirect to any other host is not followed at all, so the token cannot leak and the update fails closed.
*/
public static function followSafely( mixed $pre, mixed $args, mixed $url ): mixed {
if ( false !== $pre || self::$following || ! is_array( $args ) || ! is_string( $url ) ) {
return $pre;
}
$headers = is_array( $args['headers'] ?? null ) ? $args['headers'] : array();
$has = false;
foreach ( array_keys( $headers ) as $k ) {
$has = $has || 'authorization' === strtolower( (string) $k );
}
$host = self::repo()['host'];
if ( ! $has || ! RedirectPolicy::tokenAllowed( $url, $host ) ) {
return $pre;
}
self::$following = true;
try {
$current = $url;
$resp = null;
for ( $hop = 0; $hop <= RedirectPolicy::MAX_HOPS; $hop++ ) {
$a = $args;
$a['redirection'] = 0;
$resp = wp_remote_request( $current, $a );
$code = is_wp_error( $resp ) ? 0 : (int) wp_remote_retrieve_response_code( $resp );
if ( $code < 300 || $code >= 400 || is_wp_error( $resp ) ) {
return $resp;
}
$next = RedirectPolicy::nextUrl( $current, (string) wp_remote_retrieve_header( $resp, 'location' ), $host, $hop );
if ( null === $next ) {
return $resp; // not followed: the caller sees the 3xx and fails
}
$current = $next;
}
return $resp;
} finally {
self::$following = false;
}
}
public static function afterUpgrade( mixed $upgrader, mixed $options ): void {
if ( is_array( $options ) && ( $options['type'] ?? '' ) === 'plugin' ) {
self::clearCache();
+3
View File
@@ -6,7 +6,10 @@
* Requires at least: 6.8
* Requires PHP: 8.1
* License: GPL-2.0-or-later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Update URI: https://repo.anhonesthost.net/wp-plugins/wp-donations
* Text Domain: streamgoals-donate
* Domain Path: /languages
*/
defined( 'ABSPATH' ) || exit;
+40
View File
@@ -0,0 +1,40 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Admin\Admin;
use StreamGoals\Admin\AlertsPage;
final class AdminTableAlertMediaTest extends TestCase {
public function test_media_parts_present_and_missing(): void {
$d = array( 'visual_id' => 5, 'visual_type' => 'image', 'sound_id' => 6 );
$this->assertSame( array( array( 'Picture/GIF', false ), array( 'Sound', false ) ), AlertsPage::mediaParts( $d, array( 5 => true, 6 => true ) ) );
$this->assertSame( array( array( 'Picture missing', true ), array( 'Sound', false ) ), AlertsPage::mediaParts( $d, array( 6 => true ) ) );
$this->assertSame( array( array( 'Picture missing', true ), array( 'Sound missing', true ) ), AlertsPage::mediaParts( $d, array() ) );
}
public function test_media_parts_video_and_text_only(): void {
$this->assertSame( array( array( 'Video missing', true ) ), AlertsPage::mediaParts( array( 'visual_id' => 9, 'visual_type' => 'video', 'sound_id' => 0 ), array() ) );
$this->assertSame( array( array( 'Video', false ) ), AlertsPage::mediaParts( array( 'visual_id' => 9, 'visual_type' => 'video', 'sound_id' => 0 ), array( 9 => true ) ) );
$this->assertSame( array(), AlertsPage::mediaParts( array( 'visual_id' => 0, 'sound_id' => 0 ), array() ) );
}
public function test_table_open_is_focusable_region_with_hint_only_when_scrolling(): void {
$cards = Admin::tableOpen( array( 'Goal', '' ), 'Goals "x"' );
$this->assertStringContainsString( 'tabindex="0" role="region" aria-label="Goals &quot;x&quot;"', $cards );
$this->assertStringContainsString( 'sg-cards', $cards );
$this->assertStringNotContainsString( 'Swipe sideways', $cards );
$this->assertStringContainsString( 'screen-reader-text', $cards );
$scroll = Admin::tableOpen( array( 'A' ), 'Donations', false );
$this->assertStringContainsString( 'Swipe sideways to see more', $scroll );
$this->assertStringNotContainsString( 'sg-cards', $scroll );
$this->assertSame( '</tbody></table></div>', Admin::tableClose() );
}
public function test_td_escapes_label(): void {
$this->assertSame( '<td class="sg-actions" data-label="A&amp;&quot;">', Admin::td( 'A&"', 'sg-actions' ) );
}
}
+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 ) );
}
}
}
+25 -1
View File
@@ -79,5 +79,29 @@ final class ClientIpTest extends TestCase {
$this->assertSame( '198.18.0.5', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO, array( '198.18.0.0/15' ) ) );
}
}
public function test_bucket_key_ipv4_unchanged_and_unknown_stays(): void {
$this->assertSame( '203.0.113.9', ClientIp::bucketKey( '203.0.113.9' ) );
$this->assertSame( 'unknown', ClientIp::bucketKey( 'unknown' ) );
}
public function test_bucket_key_ipv6_collapses_to_slash_64(): void {
$a = ClientIp::bucketKey( '2001:db8:abcd:12::1' );
$b = ClientIp::bucketKey( '2001:0db8:abcd:0012:ffff:eeee:dddd:cccc' );
$this->assertSame( $a, $b, 'same /64 must share a bucket' );
$this->assertSame( '20010db8abcd0012/64', $a );
$this->assertNotSame( $a, ClientIp::bucketKey( '2001:db8:abcd:13::1' ), 'different /64 must differ' );
$this->assertNotSame( $a, ClientIp::bucketKey( '203.0.113.9' ) );
}
public function test_bucket_key_ipv4_mapped_ipv6_maps_to_the_ipv4(): void {
$this->assertSame( '203.0.113.9', ClientIp::bucketKey( '::ffff:203.0.113.9' ) );
$this->assertSame( '203.0.113.9', ClientIp::bucketKey( '::ffff:cb00:7109' ) );
}
public function test_bucket_key_garbage_becomes_unknown(): void {
foreach ( array( '', 'garbage', '999.1.1.1', '<script>', 'fe80::1%eth0' ) as $g ) {
$this->assertSame( 'unknown', ClientIp::bucketKey( $g ), $g );
}
}
}
+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 );
}
}
+61
View File
@@ -0,0 +1,61 @@
<?php
declare( strict_types=1 );
namespace {
if ( ! function_exists( 'get_option' ) ) {
function get_option( $k, $d = false ) { return array_key_exists( $k, $GLOBALS['sg_test_opts'] ) ? $GLOBALS['sg_test_opts'][ $k ] : $d; }
}
if ( ! function_exists( 'update_option' ) ) {
function update_option( $k, $v, $a = null ) { $GLOBALS['sg_test_opts'][ $k ] = $v; $GLOBALS['sg_test_writes'] = ( $GLOBALS['sg_test_writes'] ?? 0 ) + 1; return true; }
}
if ( ! function_exists( 'current_user_can' ) ) {
function current_user_can( $cap ) { return (bool) ( $GLOBALS['sg_test_can'] ?? false ); }
}
}
namespace StreamGoals\Tests\Unit {
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\Settings;
use StreamGoals\Rest\OverlayController;
/** L5: the overlay token is never created by an unauthenticated request. */
final class OverlayTokenTest extends TestCase {
protected function setUp(): void {
$GLOBALS['sg_test_opts'] = array();
$GLOBALS['sg_test_writes'] = 0;
$GLOBALS['sg_test_can'] = false;
}
public function test_public_verify_with_no_token_is_false_and_writes_nothing(): void {
$this->assertFalse( OverlayController::verify_token( 'anything' ) );
$this->assertFalse( OverlayController::verify_token( '' ) );
$this->assertSame( 0, $GLOBALS['sg_test_writes'], 'unauthenticated request must not write' );
$this->assertSame( '', OverlayController::current_token() );
}
public function test_ensure_token_refuses_without_capability(): void {
$this->assertSame( '', OverlayController::ensure_token() );
$this->assertSame( 0, $GLOBALS['sg_test_writes'] );
}
public function test_admin_generates_once_and_public_compare_then_works(): void {
$GLOBALS['sg_test_can'] = true;
$t = OverlayController::ensure_token();
$this->assertSame( 32, strlen( $t ) );
$this->assertSame( $t, OverlayController::ensure_token(), 'stable' );
$this->assertSame( 1, $GLOBALS['sg_test_writes'] );
$GLOBALS['sg_test_can'] = false;
$this->assertTrue( OverlayController::verify_token( $t ) );
$this->assertFalse( OverlayController::verify_token( str_repeat( 'a', 32 ) ) );
}
public function test_activation_helper_generates_when_missing_and_keeps_existing(): void {
$t = Settings::ensure_overlay_token();
$this->assertSame( 32, strlen( $t ) );
$this->assertSame( $t, Settings::ensure_overlay_token() );
$this->assertSame( 1, $GLOBALS['sg_test_writes'] );
}
}
}
+41 -2
View File
@@ -131,7 +131,7 @@ final class PayPalClientTest extends TestCase {
public function test_verify_webhook_success_and_failure(): void {
$headers = array(
'paypal_transmission_id' => array( 'T1' ), 'PAYPAL-TRANSMISSION-TIME' => '2026-01-01T00:00:00Z',
'paypal_transmission_id' => array( 'T1' ), 'PAYPAL-TRANSMISSION-TIME' => gmdate( 'Y-m-d\TH:i:s\Z' ),
'paypal_transmission_sig' => 'SIG', 'paypal_cert_url' => 'https://api.paypal.com/cert', 'paypal_auth_algo' => 'SHA256withRSA',
);
$raw = '{"id":"WH-1","event_type":"PAYMENT.CAPTURE.COMPLETED"}';
@@ -156,10 +156,49 @@ final class PayPalClientTest extends TestCase {
$c = $this->client();
$this->http->queue = array( new TransportException( 'boom' ) );
$headers['paypal_cert_url'] = 'x';
$headers['paypal_cert_url'] = 'https://api.paypal.com/cert';
$this->assertFalse( $c->verifyWebhook( $headers, $raw, 'WHID' ) );
}
/** @return array<string,string> */
private function goodWebhookHeaders(): array {
return array(
'paypal-transmission-id' => 'T1', 'paypal-transmission-time' => gmdate( 'Y-m-d\TH:i:s\Z' ),
'paypal-transmission-sig' => 'SIG', 'paypal-cert-url' => 'https://api.paypal.com/v1/notifications/certs/CERT-1', 'paypal-auth-algo' => 'SHA256withRSA',
);
}
/** M2: every locally rejectable request must be refused WITHOUT any outbound call (not even the OAuth token). */
public function test_verify_webhook_makes_no_outbound_call_for_locally_rejectable_requests(): void {
$raw = '{"id":"WH-1","event_type":"PAYMENT.CAPTURE.COMPLETED"}';
$cases = array();
foreach ( array_keys( $this->goodWebhookHeaders() ) as $missing ) {
$h = $this->goodWebhookHeaders();
unset( $h[ $missing ] );
$cases[ 'missing ' . $missing ] = array( $h, $raw );
}
foreach ( array( 'http://api.paypal.com/c', 'https://evil.example/c', 'https://paypal.com.evil.example/c', 'https://evilpaypal.com/c', 'https://api.paypal.com@evil.example/c', 'https://user@api.paypal.com/c', 'https://api.paypal.com:8443/c', 'ftp://api.paypal.com/c', 'not a url' ) as $u ) {
$cases[ 'cert ' . $u ] = array( array( 'paypal-cert-url' => $u ) + $this->goodWebhookHeaders(), $raw );
}
foreach ( array( gmdate( 'Y-m-d\TH:i:s\Z', time() - 7200 ), gmdate( 'Y-m-d\TH:i:s\Z', time() + 7200 ), 'yesterday', '', '0' ) as $t ) {
$cases[ 'time ' . $t ] = array( array( 'paypal-transmission-time' => $t ) + $this->goodWebhookHeaders(), $raw );
}
$cases['body too large'] = array( $this->goodWebhookHeaders(), '{"x":"' . str_repeat( 'a', 70000 ) . '"}' );
foreach ( $cases as $name => [ $headers, $body ] ) {
$c = $this->client();
$this->assertFalse( $c->verifyWebhook( $headers, $body, 'WHID' ), $name );
$this->assertCount( 0, $this->http->calls, "outbound call made for: $name" );
}
}
public function test_verify_webhook_still_calls_paypal_for_a_well_formed_request(): void {
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 200, array( 'verification_status' => 'SUCCESS' ) ) );
$this->assertTrue( $c->verifyWebhook( $this->goodWebhookHeaders(), '{"id":"WH-1"}', 'WHID' ) );
$this->assertCount( 2, $this->http->calls );
}
public function test_create_webhook_registers_only_completed_event(): void {
$c = $this->client();
$this->http->queue = array( $this->token(), FakeTransport::json( 201, array( 'id' => 'WH77' ) ) );
+126
View File
@@ -0,0 +1,126 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\Maintenance;
use StreamGoals\Core\Money;
use StreamGoals\PayPal\CaptureFinalizer;
use StreamGoals\PayPal\WebhookEvent;
/** M5: a PENDING PayPal capture must keep its capture id, survive the purge, and be finalized exactly once by the webhook. */
final class PendingCaptureFlowTest extends TestCase {
/** @var array<int,array<string,mixed>> */
private array $rows = array();
private int $notified = 0;
protected function setUp(): void {
foreach ( array( 'HOUR_IN_SECONDS' => 3600, 'DAY_IN_SECONDS' => 86400 ) as $k => $v ) {
if ( ! defined( $k ) ) {
define( $k, $v );
}
}
$this->notified = 0;
$this->rows = array(
1 => array( 'id' => 1, 'goal_id' => 3, 'status' => 'pending', 'total_minor' => 1099, 'currency' => 'USD', 'paypal_order_id' => 'ORD1', 'paypal_capture_id' => null, 'created_at' => gmdate( 'Y-m-d H:i:s', time() - 30 * 86400 ) ),
);
}
private function record(): callable {
return function ( int $id, string $cap ): bool {
if ( 'pending' === $this->rows[ $id ]['status'] && empty( $this->rows[ $id ]['paypal_capture_id'] ) ) {
$this->rows[ $id ]['paypal_capture_id'] = $cap;
return true;
}
return false;
};
}
private function mark(): callable {
return function ( int $id, string $cap ): bool {
if ( 'pending' !== $this->rows[ $id ]['status'] ) {
return false;
}
$this->rows[ $id ]['status'] = 'completed';
$this->rows[ $id ]['paypal_capture_id'] = $cap;
return true;
};
}
private function notify(): callable {
return function ( int $id ): void { ++$this->notified; };
}
private function purge(): void {
foreach ( $this->rows as $id => $r ) {
if ( Maintenance::isPurgeable( $r, time() ) ) {
unset( $this->rows[ $id ] );
}
}
}
private function webhook(): string {
$ev = WebhookEvent::fromArray( array(
'id' => 'WH-1', 'event_type' => 'PAYMENT.CAPTURE.COMPLETED',
'resource' => array( 'id' => 'CAP1', 'custom_id' => '1', 'amount' => array( 'value' => '10.99', 'currency_code' => 'USD' ), 'supplementary_data' => array( 'related_ids' => array( 'order_id' => 'ORD1' ) ) ),
) );
$row = $this->rows[ (int) $ev->customId ] ?? null;
if ( ! $row ) {
foreach ( $this->rows as $r ) {
if ( $r['paypal_capture_id'] === $ev->captureId || $r['paypal_order_id'] === $ev->orderId ) {
$row = $r;
}
}
}
return $row ? CaptureFinalizer::finalize( $row, 'COMPLETED', $ev->captureId, $ev->amount, $this->mark(), $this->notify() ) : 'ignored';
}
public function test_pending_capture_is_stored_survives_purge_and_webhook_finalizes_once(): void {
$res = CaptureFinalizer::finalize( $this->rows[1], 'PENDING', 'CAP1', new Money( 1099, 'USD' ), $this->mark(), $this->notify(), $this->record() );
$this->assertSame( CaptureFinalizer::PENDING, $res );
$this->assertSame( 'CAP1', $this->rows[1]['paypal_capture_id'], 'PENDING capture id must be persisted' );
$this->assertSame( 'pending', $this->rows[1]['status'] );
$this->purge();
$this->assertArrayHasKey( 1, $this->rows, 'row with capture evidence must survive the purge even when old' );
$this->assertSame( CaptureFinalizer::COMPLETED, $this->webhook() );
$this->assertSame( 'completed', $this->rows[1]['status'] );
$this->assertSame( CaptureFinalizer::DUPLICATE, $this->webhook(), 'replayed webhook is a no-op' );
$this->assertSame( 1, $this->notified, 'side effects exactly once' );
}
public function test_without_recording_the_old_behaviour_would_lose_the_row(): void {
CaptureFinalizer::finalize( $this->rows[1], 'PENDING', 'CAP1', new Money( 1099, 'USD' ), $this->mark(), $this->notify() );
$this->assertNull( $this->rows[1]['paypal_capture_id'] );
$this->purge();
$this->assertArrayNotHasKey( 1, $this->rows );
}
public function test_amount_mismatch_also_records_capture_id(): void {
CaptureFinalizer::finalize( $this->rows[1], 'COMPLETED', 'CAP1', new Money( 5, 'USD' ), $this->mark(), $this->notify(), $this->record() );
$this->assertSame( 'CAP1', $this->rows[1]['paypal_capture_id'] );
$this->assertSame( 'pending', $this->rows[1]['status'] );
}
public function test_no_capture_id_means_nothing_recorded(): void {
$called = false;
CaptureFinalizer::finalize( $this->rows[1], 'PENDING', '', null, $this->mark(), $this->notify(), function () use ( &$called ) { $called = true; return true; } );
$this->assertFalse( $called );
}
public function test_is_purgeable_rules(): void {
$old = gmdate( 'Y-m-d H:i:s', time() - 8 * 86400 );
$new = gmdate( 'Y-m-d H:i:s', time() - 6 * 86400 );
$b = array( 'status' => 'pending', 'goal_id' => 1, 'paypal_capture_id' => null, 'created_at' => $old );
$this->assertTrue( Maintenance::isPurgeable( $b, time() ) );
$this->assertTrue( Maintenance::isPurgeable( array( 'paypal_capture_id' => '' ) + $b, time() ) );
$this->assertFalse( Maintenance::isPurgeable( array( 'created_at' => $new ) + $b, time() ) );
$this->assertFalse( Maintenance::isPurgeable( array( 'paypal_capture_id' => 'X' ) + $b, time() ) );
$this->assertFalse( Maintenance::isPurgeable( array( 'status' => 'completed' ) + $b, time() ) );
$this->assertFalse( Maintenance::isPurgeable( array( 'goal_id' => 0 ) + $b, time() ) );
$this->assertFalse( Maintenance::isPurgeable( array( 'created_at' => 'garbage' ) + $b, time() ) );
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\Privacy;
final class PrivacyTest extends TestCase {
public function test_text_covers_the_required_disclosures(): void {
$t = Privacy::content( static fn( string $s ): string => $s );
$this->assertStringContainsString( 'Suggested text:', $t );
$this->assertStringContainsString( 'PayPal', $t );
$this->assertStringContainsString( 'paypal.com/webapps/mpp/ua/privacy-full', $t );
$this->assertStringContainsString( 'anonymous', $t );
$this->assertStringContainsString( 'never stored', $t );
$this->assertStringContainsString( 'IP address', $t );
$this->assertStringContainsString( 'CSV', $t );
$this->assertStringContainsString( 'overlay', $t );
$this->assertStringContainsString( 'do not store your email address', $t );
}
public function test_translator_is_applied_to_every_sentence(): void {
$t = Privacy::content( static fn( string $s ): string => '[' . $s . ']' );
$this->assertStringContainsString( '[Suggested text:]', $t );
$this->assertStringContainsString( '[Donations]', $t );
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\PayPal\RequestId;
final class RequestIdTest extends TestCase {
public function test_stable_per_donation_and_within_paypal_limit(): void {
$a = RequestId::make( 'order', 42, '2026-01-01 10:00:00', 'salt' );
$this->assertSame( $a, RequestId::make( 'order', 42, '2026-01-01 10:00:00', 'salt' ) );
$this->assertLessThanOrEqual( 108, strlen( $a ) );
$this->assertMatchesRegularExpression( '/^sg-order-[0-9a-f]{64}$/', $a );
}
public function test_reused_auto_increment_id_gets_a_different_key(): void {
$this->assertNotSame( RequestId::make( 'order', 42, '2026-01-01 10:00:00', 's' ), RequestId::make( 'order', 42, '2026-01-02 10:00:00', 's' ) );
}
public function test_not_derivable_without_the_salt_and_kinds_differ(): void {
$this->assertNotSame( RequestId::make( 'order', 42, 't', 'salt1' ), RequestId::make( 'order', 42, 't', 'salt2' ) );
$this->assertNotSame( RequestId::make( 'order', 42, 't', 's' ), RequestId::make( 'capture', 42, 't', 's' ) );
$this->assertStringNotContainsString( 'sg-order-42', RequestId::make( 'order', 42, 't', 's' ) );
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Core\Maintenance;
use StreamGoals\Core\Settings;
use StreamGoals\Core\Uninstaller;
/** Guards the uninstall lists so a newly added table/option/transient/cron cannot be forgotten. */
final class UninstallerTest extends TestCase {
private const ROOT = __DIR__ . '/../../';
/** @return string[] contents of every PHP file under includes/ plus the main file, keyed by path */
private function sources(): array {
$out = array( 'streamgoals-donate.php' => (string) file_get_contents( self::ROOT . 'streamgoals-donate.php' ) );
$it = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( self::ROOT . 'includes', \FilesystemIterator::SKIP_DOTS ) );
foreach ( $it as $f ) {
if ( 'php' === $f->getExtension() && 'Uninstaller.php' !== $f->getFilename() ) {
$out[ $f->getPathname() ] = (string) file_get_contents( $f->getPathname() );
}
}
return $out;
}
public function test_every_installer_table_is_dropped(): void {
$src = (string) file_get_contents( self::ROOT . 'includes/Core/Installer.php' );
preg_match_all( '/CREATE TABLE \{\$p\}(\w+)/', $src, $m );
$this->assertNotEmpty( $m[1] );
$created = array_map( static fn( $t ) => 'sg_' . $t, $m[1] );
$this->assertSame( array(), array_diff( $created, Uninstaller::tables() ), 'table created by Installer but not dropped on uninstall' );
$this->assertSame( array(), array_diff( Uninstaller::tables(), $created ), 'uninstall drops a table Installer does not create' );
}
public function test_every_option_used_in_code_is_deleted(): void {
$found = array();
foreach ( $this->sources() as $src ) {
preg_match_all( "/(?:add|update|delete)_option\(\s*'(sg_\w+)'/", $src, $a );
preg_match_all( "/const\s+(?:OPTION|VERIFIED)\s*=\s*'(sg_\w+)'/", $src, $b );
$found = array_merge( $found, $a[1], $b[1] );
}
$found = array_unique( $found );
$this->assertContains( 'sg_settings', $found, 'scan sanity check' );
$this->assertContains( 'sg_overlay_epoch', $found );
$this->assertContains( 'sg_paypal_verified', $found );
$this->assertSame( array(), array_values( array_diff( $found, Uninstaller::options() ) ), 'option written by the plugin but not removed on uninstall' );
}
public function test_every_transient_and_cron_hook_is_cleaned(): void {
$fixed = array();
$dyn = array();
foreach ( $this->sources() as $src ) {
preg_match_all( "/(?:CACHE_KEY\s*=\s*|(?:set|get|delete)_site_transient\(\s*)'(sg_\w+)'/", $src, $a );
$fixed = array_merge( $fixed, $a[1] );
preg_match_all( "/(?:set|get|delete)_transient\(\s*'(sg_\w+?_)'\s*\./", $src, $b );
$dyn = array_merge( $dyn, $b[1] );
preg_match_all( "/'(sg_rl_)'\s*\./", $src, $c );
$dyn = array_merge( $dyn, $c[1] );
// Cache-seam keys (WpCache -> transients): $key = 'sg_xxx_' . md5(...)
preg_match_all( "/'(sg_\w+?_)'\s*\.\s*md5/", $src, $d );
$dyn = array_merge( $dyn, $d[1] );
}
$this->assertContains( 'sg_update_release', $fixed, 'scan sanity check' );
$this->assertSame( array(), array_values( array_diff( array_unique( $fixed ), Uninstaller::site_transients() ) ) );
$this->assertSame( array(), array_values( array_diff( array_unique( $dyn ), Uninstaller::transient_prefixes() ) ) );
$this->assertContains( 'sg_rl_', Uninstaller::transient_prefixes() );
$this->assertContains( 'sg_notice_', Uninstaller::transient_prefixes() );
$this->assertContains( 'sg_pp_token_', Uninstaller::transient_prefixes(), 'cached PayPal access token' );
$this->assertContains( 'sg_wh_', Uninstaller::transient_prefixes(), 'webhook de-dupe markers' );
$this->assertContains( 'sg_pp_token_', $dyn, 'scan sanity check' );
$this->assertContains( 'sg_wh_', $dyn, 'scan sanity check' );
$this->assertSame( Maintenance::HOOK, Uninstaller::CRON_HOOK );
}
public function test_deactivation_unschedules_the_cron_event(): void {
$main = (string) file_get_contents( self::ROOT . 'streamgoals-donate.php' );
$this->assertMatchesRegularExpression( '/register_deactivation_hook\([^;]*Maintenance::class,\s*\'unschedule\'/', $main );
}
public function test_uninstall_is_opt_in_and_off_by_default(): void {
$this->assertFalse( Settings::defaults()['delete_data_on_uninstall'] );
$this->assertFalse( Uninstaller::wants_data_deleted( false ) );
$this->assertFalse( Uninstaller::wants_data_deleted( array() ) );
$this->assertFalse( Uninstaller::wants_data_deleted( array( 'delete_data_on_uninstall' => false ) ) );
$this->assertTrue( Uninstaller::wants_data_deleted( array( 'delete_data_on_uninstall' => true ) ) );
}
private function fakeDb(): object {
return new class() {
public string $prefix = 'wp7_';
public string $options = 'wp7_options';
public array $queries = array();
public function query( string $q ): int { $this->queries[] = $q; return 0; }
public function esc_like( string $s ): string { return addcslashes( $s, '_%\\' ); }
public function prepare( string $q, ...$a ): string { return str_replace( '%s', "'" . $a[0] . "'", $q ); }
};
}
public function test_drop_tables_issues_one_drop_per_table_with_prefix(): void {
$db = $this->fakeDb();
Uninstaller::drop_tables( $db );
$this->assertCount( count( Uninstaller::tables() ), $db->queries );
$this->assertContains( 'DROP TABLE IF EXISTS `wp7_sg_donations`', $db->queries );
foreach ( $db->queries as $q ) {
$this->assertMatchesRegularExpression( '/^DROP TABLE IF EXISTS `wp7_sg_\w+`$/', $q );
}
}
public function test_dynamic_transient_cleanup_only_targets_plugin_prefixes(): void {
$db = $this->fakeDb();
Uninstaller::delete_dynamic_transients( $db );
$this->assertCount( 2 * count( Uninstaller::transient_prefixes() ), $db->queries );
foreach ( $db->queries as $q ) {
$this->assertStringStartsWith( 'DELETE FROM wp7_options WHERE option_name LIKE', $q );
$this->assertMatchesRegularExpression( '/_transient_(timeout_)?sg_(rl|notice|pp_token|wh)_%/', str_replace( '\\', '', $q ) );
}
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\Update\RedirectPolicy;
final class UpdateRedirectPolicyTest extends TestCase {
private const H = 'repo.example.net';
public function test_same_host_redirects_are_followed_relative_and_absolute(): void {
$cur = 'https://repo.example.net/a/b/c.zip';
$this->assertSame( 'https://repo.example.net/x/y.zip', RedirectPolicy::nextUrl( $cur, 'https://repo.example.net/x/y.zip', self::H, 0 ) );
$this->assertSame( 'https://repo.example.net/x/y.zip', RedirectPolicy::nextUrl( $cur, '/x/y.zip', self::H, 0 ) );
$this->assertSame( 'https://repo.example.net/a/b/d.zip', RedirectPolicy::nextUrl( $cur, 'd.zip', self::H, 1 ) );
$this->assertSame( 'https://repo.example.net/q', RedirectPolicy::nextUrl( $cur, '//repo.example.net/q', self::H, 0 ) );
}
public function test_other_hosts_and_downgrades_are_never_followed(): void {
$cur = 'https://repo.example.net/a.zip';
foreach ( array( 'https://evil.example/a.zip', 'http://repo.example.net/a.zip', '//evil.example/a', 'https://repo.example.net.evil.example/a', 'https://repo.example.net@evil.example/a', 'https://user@repo.example.net/a', 'https://repo.example.net:8443/a', 'ftp://repo.example.net/a', '', "/ok\r\nX: y" ) as $loc ) {
$this->assertNull( RedirectPolicy::nextUrl( $cur, $loc, self::H, 0 ), $loc );
}
}
public function test_hop_limit(): void {
$this->assertNotNull( RedirectPolicy::nextUrl( 'https://repo.example.net/a', '/b', self::H, 2 ) );
$this->assertNull( RedirectPolicy::nextUrl( 'https://repo.example.net/a', '/b', self::H, 3 ) );
}
public function test_token_allowed_only_for_https_pinned_host_default_port(): void {
$this->assertTrue( RedirectPolicy::tokenAllowed( 'https://repo.example.net/x', self::H ) );
$this->assertTrue( RedirectPolicy::tokenAllowed( 'https://REPO.example.net:443/x', self::H ) );
$this->assertFalse( RedirectPolicy::tokenAllowed( 'https://repo.example.net:8443/x', self::H ) );
$this->assertFalse( RedirectPolicy::tokenAllowed( 'http://repo.example.net/x', self::H ) );
$this->assertFalse( RedirectPolicy::tokenAllowed( 'https://cdn.example.net/x', self::H ) );
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
declare( strict_types=1 );
namespace StreamGoals\Tests\Unit;
use PHPUnit\Framework\TestCase;
use StreamGoals\PayPal\ArrayCache;
use StreamGoals\PayPal\RateLimiter;
use StreamGoals\PayPal\WebhookGuard;
final class WebhookGuardTest extends TestCase {
public function test_per_ip_limit_then_429_and_other_ips_unaffected(): void {
$l = new RateLimiter( new ArrayCache() );
for ( $i = 0; $i < WebhookGuard::IP_LIMIT; $i++ ) {
$this->assertTrue( WebhookGuard::admit( $l, '203.0.113.1' ) );
}
$this->assertFalse( WebhookGuard::admit( $l, '203.0.113.1' ), 'over the per-IP limit' );
$this->assertTrue( WebhookGuard::admit( $l, '203.0.113.2' ), 'PayPal\'s other addresses keep working' );
}
public function test_global_cap(): void {
$l = new RateLimiter( new ArrayCache() );
$ok = 0;
for ( $i = 0; $i < WebhookGuard::GLOBAL_LIMIT + 50; $i++ ) {
$ok += WebhookGuard::admit( $l, '10.0.' . intdiv( $i, 100 ) . '.' . ( $i % 100 ) ) ? 1 : 0; // every request from a fresh bucket
}
$this->assertSame( WebhookGuard::GLOBAL_LIMIT, $ok );
}
public function test_rejections_have_the_expected_status(): void {
$good = array( 'paypal-transmission-id' => 'T', 'paypal-transmission-time' => gmdate( 'Y-m-d\TH:i:s\Z' ), 'paypal-transmission-sig' => 'S', 'paypal-cert-url' => 'https://api.sandbox.paypal.com/c', 'paypal-auth-algo' => 'A' );
$this->assertNull( WebhookGuard::check( $good, '{}', time() ) );
$this->assertSame( 413, WebhookGuard::check( $good, str_repeat( 'a', 65537 ), time() )['status'] );
$this->assertNull( WebhookGuard::check( $good, str_repeat( 'a', 65536 ), time() ) );
$this->assertSame( 401, WebhookGuard::check( array_diff_key( $good, array( 'paypal-auth-algo' => 1 ) ), '{}', time() )['status'] );
$this->assertSame( 401, WebhookGuard::check( array( 'paypal-cert-url' => 'https://evil.test/' ) + $good, '{}', time() )['status'] );
$this->assertSame( 401, WebhookGuard::check( array( 'paypal-transmission-time' => '2020-01-01T00:00:00Z' ) + $good, '{}', time() )['status'] );
$this->assertSame( 401, WebhookGuard::check( array( 'paypal-transmission-time' => 'garbage' ) + $good, '{}', time() )['status'] );
}
public function test_time_window_boundaries_and_offsets(): void {
$now = 1800000000;
$this->assertTrue( WebhookGuard::timeWithinWindow( gmdate( 'Y-m-d\TH:i:s\Z', $now - 3600 ), $now ) );
$this->assertFalse( WebhookGuard::timeWithinWindow( gmdate( 'Y-m-d\TH:i:s\Z', $now - 3601 ), $now ) );
$this->assertFalse( WebhookGuard::timeWithinWindow( gmdate( 'Y-m-d\TH:i:s\Z', $now + 3601 ), $now ) );
$this->assertTrue( WebhookGuard::timeWithinWindow( gmdate( 'Y-m-d\TH:i:s', $now + 3600 ) . '+01:00', $now ) );
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
/**
* Runs when the plugin is deleted from the Plugins screen.
*
* Always removes the scheduled event and cached transients. Deletes donations, goals and settings only if the
* owner enabled "delete data on uninstall" in StreamGoals > Settings > Advanced.
*/
defined( 'WP_UNINSTALL_PLUGIN' ) || exit;
require_once __DIR__ . '/includes/Core/Uninstaller.php';
\StreamGoals\Core\Uninstaller::run();