Compare commits
17
Commits
No files matched your search
@@ -48,7 +48,20 @@ jobs:
|
||||
|
||||
- name: Compute version
|
||||
id: ver
|
||||
run: echo "version=$(date -u +'%Y.%m.%d-%H%M')" >> "$GITHUB_OUTPUT"
|
||||
run: |
|
||||
# Date-based version to the minute. Two pushes in the same minute would collide on the tag,
|
||||
# so keep moving to the next minute until the tag is unused (format stays YYYY.MM.DD-HHMM).
|
||||
git fetch --tags --quiet origin || true
|
||||
TS=$(date -u +%s)
|
||||
while true; do
|
||||
V=$(date -u -d "@$TS" +'%Y.%m.%d-%H%M')
|
||||
if git rev-parse -q --verify "refs/tags/$V" >/dev/null || git ls-remote --exit-code --tags origin "refs/tags/$V" >/dev/null 2>&1; then
|
||||
TS=$((TS + 60))
|
||||
else
|
||||
break
|
||||
fi
|
||||
done
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Generate release notes
|
||||
id: notes
|
||||
@@ -80,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
|
||||
@@ -88,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:
|
||||
|
||||
@@ -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.
|
||||
@@ -30,6 +30,28 @@ You need two values from PayPal: a **Client ID** and a **Secret**.
|
||||
Start in **Sandbox**, make a test donation using a PayPal sandbox buyer account, then repeat the steps
|
||||
with the Live credentials and switch the mode to Live in Settings.
|
||||
|
||||
### Going live
|
||||
1. In the PayPal developer dashboard (Apps & Credentials), switch to **Live** and create a Live app (type Merchant).
|
||||
2. In StreamGoals > Settings, paste the Live **Client ID** and **Secret**.
|
||||
3. Switch the mode to **Live**, then **Save and test connection**.
|
||||
4. Webhook: the plugin registers it for you when the test succeeds (changing mode or credentials clears the old one, so
|
||||
the Live webhook is created fresh). It points to `https://YOUR-SITE/wp-json/streamgoals/v1/webhook` and listens for
|
||||
`PAYMENT.CAPTURE.COMPLETED`. If the message says it could not register it (needs a public https site, or a webhook
|
||||
for that address already exists), add it by hand in your Live app in the PayPal dashboard with that URL and that event.
|
||||
5. Make a small real donation and check it appears under Donations and on your goal, then refund yourself in PayPal if you like.
|
||||
6. Set the visitor IP header if needed (Settings > Advanced; Cloudflare is detected automatically).
|
||||
7. Add the overlays in OBS as Browser Sources (StreamGoals > Overlays).
|
||||
8. Turn on two-factor authentication for both your PayPal and WordPress accounts.
|
||||
|
||||
### Chargebacks and refunds
|
||||
Chargebacks and refunds are handled manually in PayPal. The plugin does not track them, so totals, timers, counters
|
||||
and tiers are not reduced. If you need to compensate, adjust the goal or its rules yourself by editing them.
|
||||
|
||||
### Behind Cloudflare?
|
||||
Nothing to do: the plugin recognises Cloudflare automatically (by its published addresses) so each visitor is rate
|
||||
limited separately. For another proxy, choose it in StreamGoals > Settings > Advanced; the panel there shows what your
|
||||
server sees.
|
||||
|
||||
### Notes on fees and currency
|
||||
- "Cover the processing fees" adds an estimate based on the rates in Settings (default: US domestic,
|
||||
3.49% + $0.49). Your actual PayPal rate depends on your account, country and payment method.
|
||||
@@ -40,6 +62,12 @@ with the Live credentials and switch the mode to Live in Settings.
|
||||
|
||||
## Using it
|
||||
- **Donation page:** add the shortcode `[streamgoals_donate]` to a page (or `[streamgoals_donate goal="ID"]` to pin one goal).
|
||||
- `show_progress="no"` hides the progress bar above the form (default `yes`; also accepts `true/false/1/0`).
|
||||
- `[streamgoals_progress]` (or `[streamgoals_progress goal="ID"]`) shows just the progress bar, e.g. in a sidebar or a stream page.
|
||||
The bar shows raised / target, the percentage and, for tiered goals, the current tier and its target, using the same
|
||||
numbers as the overlay (base amounts, or including fees only if the goal counts fees). It refreshes after a donation and
|
||||
about every 30 seconds while the tab is visible, from the public `GET /wp-json/streamgoals/v1/progress?goal=ID` (totals only).
|
||||
The first render is server-side HTML, so page caches and Cloudflare are fine.
|
||||
- **Goals:** StreamGoals → Goals. Create as many as you like; each can have its own rules.
|
||||
- **Rules (time and counters):** per goal, e.g. "+60 seconds per $1" (subathon timer), "+1 per $10" (counter),
|
||||
or a bonus event above a minimum amount. Amounts can be measured on the base donation or including fee cover.
|
||||
@@ -51,15 +79,48 @@ with the Live credentials and switch the mode to Live in Settings.
|
||||
form, as a **Rewards menu** overlay for OBS, and as a highlighted line in the donation alert. Triggered rewards land in a
|
||||
**queue** on the Rewards screen so you can tick them off as you do them. Rewards count the donation amount, not the
|
||||
optional fee cover, and must be at least your minimum donation.
|
||||
- **Alerts with pictures, GIFs, videos and sounds:** StreamGoals > Alerts. Pick files from your WordPress Media Library
|
||||
(PNG, JPEG, GIF, WebP, MP4, WebM for the picture/video; MP3, OGG, WAV for sound). Tie an alert to **a donation size**
|
||||
("any donation of at least $5": the highest matching amount wins) or to **a reward** (a reward alert beats an amount
|
||||
alert). Set the volume, how long a picture stays, and a message using `{name}`, `{amount}` and `{reward}`. In OBS media
|
||||
plays automatically; in an ordinary browser tab click the page once before sound is allowed. Keep files small (videos
|
||||
under about 25 MB). If a file is deleted the alert still shows, just without it.
|
||||
- **Tiers (milestones):** on the Goals screen use **Tiers** to turn one goal into a ladder, for example $100 "Giveaway",
|
||||
$250 "New microphone", $500 "24-hour stream". The goal bar shows the current tier and fills within it; unlocking a tier
|
||||
shows a **TIER UNLOCKED** line in the alert and the bar moves on to the next one. The goal's final target is your highest
|
||||
tier. The donation form shows "Next unlock: ... to go".
|
||||
- **End at target:** tick "Close this goal to donations when the target is reached" on a goal. When the total reaches or
|
||||
passes the target (for a tiered goal, the final tier) the goal closes and the donation page says so. Donations already
|
||||
in checkout still go through. Use **Reopen** after raising the target.
|
||||
- **Test:** "Send test donation" on the Overlays screen shows an alert without touching real totals.
|
||||
|
||||
## Privacy and moderation
|
||||
- Donors choose a name or "Anonymous". For anonymous donors the **name is never stored**.
|
||||
- Optional message approval queue and a streamer-controlled profanity filter (whole-word, your own word list).
|
||||
- The filter masks bad words in messages and in donor names (anonymous donors have no stored name). If a **donor name**
|
||||
trips the filter, the donation still completes and counts towards the goal, timer, counters, rewards and tiers, but it
|
||||
is **held on the Moderation screen** (flagged "Name", "Message" or "Name and message") even when message moderation is
|
||||
off. A held donation shows no alert (name or message) and no public donor-feed entry until you approve it; approving
|
||||
shows the already-masked name. Rejecting it means it is never shown.
|
||||
- If the server dies right after a payment is recorded, a five-minute background job re-applies any timer, counter,
|
||||
reward and tier effects that were missed (never twice).
|
||||
|
||||
## 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
|
||||
@@ -75,3 +136,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).
|
||||
@@ -44,3 +44,45 @@
|
||||
.sg-admin .sg-filter { display: inline-block; margin: 8px 8px 8px 0; }
|
||||
.sg-admin .sg-table { max-width: 100%; }
|
||||
@media (max-width: 782px) { .sg-admin .sg-copy { flex-direction: column; align-items: stretch; } }
|
||||
/* Phones: wide tables scroll inside their own box instead of pushing the page; controls never exceed the card. */
|
||||
@media (max-width: 782px) {
|
||||
.sg-admin .sg-table th, .sg-admin .sg-table td { min-width: 3em; padding: 8px 6px; font-size: 13px; }
|
||||
.sg-admin .sg-table code { overflow-wrap: anywhere; word-break: break-all; font-size: 12px; }
|
||||
.sg-admin .sg-table td:last-child .button { margin: 0 4px 4px 0; }
|
||||
.sg-admin .sg-card details > summary { min-height: 44px; display: flex; align-items: center; cursor: pointer; }
|
||||
.sg-admin .sg-card label > input[type="radio"], .sg-admin .sg-card label > input[type="checkbox"] { margin-right: 6px; }
|
||||
.sg-admin .sg-card p > label + .description, .sg-admin .sg-card p > label { display: inline-block; margin: 4px 0; }
|
||||
.sg-admin select, .sg-admin input[type="text"], .sg-admin input[type="url"], .sg-admin input[type="number"], .sg-admin textarea { max-width: 100%; box-sizing: border-box; }
|
||||
.sg-admin .sg-card { padding-left: 14px; padding-right: 14px; }
|
||||
}
|
||||
|
||||
/* 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; }
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
.sga-help{list-style:disc;margin-left:1.4em}
|
||||
.sga-media{display:flex;flex-wrap:wrap;align-items:center;gap:8px}
|
||||
.sga-media-name{font-weight:600;overflow-wrap:anywhere}
|
||||
.sga-media-warn{flex-basis:100%;margin:0;color:#996800}
|
||||
.sga-media-warn:empty{display:none}
|
||||
.sga-form input[type=range]{vertical-align:middle;width:220px;max-width:100%}
|
||||
.sga-stage{min-height:140px;display:flex;align-items:flex-end;justify-content:center;padding:16px;background:repeating-conic-gradient(#2b2b33 0 25%,#34343d 0 50%) 0 0/20px 20px;border-radius:6px;font-size:18px;color:#fff;line-height:1.2}
|
||||
.sga-alert{width:100%;max-width:560px;text-align:center;background:rgba(0,0,0,.45);border:2px solid #7c5cff;border-radius:12px;padding:10px 14px}
|
||||
.sga-alert-media{display:flex;justify-content:center;margin-bottom:6px}
|
||||
.sga-alert-media img,.sga-alert-media video{display:block;max-width:100%;max-height:260px;object-fit:contain;border-radius:6px}
|
||||
.sga-alert-head{font-weight:800;font-size:1.2em}
|
||||
.sga-alert-head b{color:#22d3ee}
|
||||
.sga-idle{color:#bbb;font-size:14px;align-self:center}
|
||||
|
||||
/* Phones: radio rows breathe, slider fills the width, preview stage scales and never overflows. */
|
||||
@media (max-width:782px){
|
||||
.sga-form label{display:inline-block;margin:6px 0;min-height:32px}
|
||||
.sga-form input[type=range]{width:100%;min-height:32px}
|
||||
.sga-stage{min-height:120px;padding:10px;font-size:16px;overflow:hidden;box-sizing:border-box;max-width:100%}
|
||||
.sga-alert{box-sizing:border-box}
|
||||
.sga-alert-media img,.sga-alert-media video{max-height:180px}
|
||||
.sga-media .button{min-height:40px}
|
||||
}
|
||||
|
||||
/* Frameless alerts: preview backdrops and card without the box */
|
||||
.sga-bg-light{background:repeating-conic-gradient(#e8e8ee 0 25%,#fff 0 50%) 0 0/20px 20px;color:#111}
|
||||
.sga-bg-scene{background:linear-gradient(135deg,#1e6f3c 0 33%,#c2410c 33% 66%,#1d4ed8 66%)}
|
||||
.sga-alert.sga-frameless{background:none;border:0;padding:0}
|
||||
.sga-frameless .sga-alert-head{text-shadow:0 0 3px #000,0 0 6px #000,0 1px 4px #000}
|
||||
.sga-bg-light .sga-frameless .sga-alert-head{text-shadow:0 0 3px #fff,0 0 6px #fff;color:#111}
|
||||
.sga-howto{margin-top:8px}
|
||||
.sga-howto pre{overflow-x:auto;max-width:100%;padding:8px;background:#f0f0f1}
|
||||
.sga-bg-pick{margin-left:12px}
|
||||
|
||||
/* 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}
|
||||
@@ -0,0 +1,155 @@
|
||||
/* StreamGoals alert editor: Media Library pickers (wp.media) and a live preview that mirrors the overlay. */
|
||||
( function () {
|
||||
'use strict';
|
||||
var form = document.querySelector( '.sga-form' );
|
||||
var dataEl = document.getElementById( 'sga-data' );
|
||||
var stage = document.getElementById( 'sga-stage' );
|
||||
var playBtn = document.getElementById( 'sga-play' );
|
||||
if ( ! form || ! dataEl || ! stage || ! playBtn ) { return; }
|
||||
var cfg = { currency: 'USD', exp: 2, rewards: [], videoCap: 30000, warnBytes: 26214400, allowed: {} };
|
||||
try { cfg = JSON.parse( dataEl.textContent ); } catch ( e ) { /* defaults */ }
|
||||
var timers = [], media = [];
|
||||
|
||||
function el( tag, cls, text ) {
|
||||
var e = document.createElement( tag );
|
||||
if ( cls ) { e.className = cls; }
|
||||
if ( text != null ) { e.textContent = text; }
|
||||
return e;
|
||||
}
|
||||
|
||||
/* ---- Media Library pickers ---- */
|
||||
Array.prototype.forEach.call( form.querySelectorAll( '.sga-media' ), function ( box ) {
|
||||
var input = box.querySelector( 'input[type=hidden]' );
|
||||
var nameEl = box.querySelector( '.sga-media-name' );
|
||||
var warnEl = box.querySelector( '.sga-media-warn' );
|
||||
var kind = box.getAttribute( 'data-kind' );
|
||||
var frame = null;
|
||||
|
||||
function set( id, url, mime, name, size ) {
|
||||
input.value = String( id || 0 );
|
||||
input.setAttribute( 'data-url', url || '' );
|
||||
input.setAttribute( 'data-mime', mime || '' );
|
||||
nameEl.textContent = id ? name : 'Nothing chosen';
|
||||
var msg = '';
|
||||
if ( id && size > cfg.warnBytes ) {
|
||||
msg = 'This file is over 25 MB. Big files load slowly' + ( /^video\//.test( mime ) ? ' and large videos can make OBS stutter. A short, compressed clip is much better.' : '.' );
|
||||
}
|
||||
warnEl.textContent = msg;
|
||||
input.dispatchEvent( new Event( 'change', { bubbles: true } ) );
|
||||
}
|
||||
function accepts( mime ) {
|
||||
var k = cfg.allowed[ String( mime ).toLowerCase() ];
|
||||
return kind === 'sound' ? k === 'audio' : ( k === 'image' || k === 'video' );
|
||||
}
|
||||
box.querySelector( '.sga-pick' ).addEventListener( 'click', function () {
|
||||
if ( ! window.wp || ! wp.media ) { nameEl.textContent = 'The Media Library could not be loaded. Reload the page.'; return; }
|
||||
if ( ! frame ) {
|
||||
frame = wp.media( {
|
||||
title: kind === 'sound' ? 'Choose a sound' : 'Choose a picture, GIF or video',
|
||||
button: { text: 'Use this file' },
|
||||
library: { type: kind === 'sound' ? [ 'audio' ] : [ 'image', 'video' ] },
|
||||
multiple: false
|
||||
} );
|
||||
frame.on( 'select', function () {
|
||||
var a = frame.state().get( 'selection' ).first().toJSON();
|
||||
if ( ! accepts( a.mime ) ) {
|
||||
warnEl.textContent = 'That file type is not allowed (' + a.mime + '). ' + ( kind === 'sound' ? 'Use MP3, OGG or WAV.' : 'Use PNG, JPEG, GIF, WebP, MP4 or WebM.' );
|
||||
return;
|
||||
}
|
||||
set( a.id, a.url, a.mime, a.filename || a.title || ( 'File ' + a.id ), a.filesizeInBytes || 0 );
|
||||
} );
|
||||
}
|
||||
frame.open();
|
||||
} );
|
||||
box.querySelector( '.sga-clear' ).addEventListener( 'click', function () { set( 0, '', '', '', 0 ); } );
|
||||
} );
|
||||
|
||||
var vol = form.elements.volume, volOut = document.getElementById( 'sga_volume_out' );
|
||||
if ( vol && volOut ) { vol.addEventListener( 'input', function () { volOut.textContent = vol.value; } ); }
|
||||
|
||||
/* ---- preview ---- */
|
||||
function toMinor( raw ) {
|
||||
var s = String( raw == null ? '' : raw ).replace( /[,\s$€£¥]/g, '' );
|
||||
var m = /^(\d+)(?:\.(\d+))?$/.exec( s );
|
||||
if ( ! m ) { return null; }
|
||||
var frac = m[ 2 ] || '';
|
||||
if ( frac.length > cfg.exp ) { return null; }
|
||||
while ( frac.length < cfg.exp ) { frac += '0'; }
|
||||
return parseInt( m[ 1 ] + frac, 10 );
|
||||
}
|
||||
function money( minor ) {
|
||||
var s = String( minor );
|
||||
if ( cfg.exp === 0 ) { return cfg.currency + ' ' + s; }
|
||||
while ( s.length <= cfg.exp ) { s = '0' + s; }
|
||||
return cfg.currency + ' ' + s.slice( 0, -cfg.exp ) + '.' + s.slice( -cfg.exp );
|
||||
}
|
||||
function clean( s ) { return String( s ).replace( /<[^>]*>/g, '' ).replace( /[<>\u0000-\u001f\u007f]/g, ' ' ).replace( /\s+/g, ' ' ).trim(); }
|
||||
function render( tpl, vals ) {
|
||||
var t = clean( tpl );
|
||||
if ( ! t ) { return ''; }
|
||||
return t.replace( /\{([A-Za-z_]{1,20})\}/g, function ( m, k ) { return vals[ k.toLowerCase() ] || ''; } ).replace( /\s+/g, ' ' ).trim().slice( 0, 200 );
|
||||
}
|
||||
function stop() {
|
||||
timers.forEach( clearTimeout ); timers = [];
|
||||
media.forEach( function ( m ) { try { m.pause(); } catch ( e ) { /* ignore */ } } ); media = [];
|
||||
}
|
||||
function inp( name ) { return form.querySelector( '[name="' + name + '"]' ); }
|
||||
|
||||
function play() {
|
||||
stop();
|
||||
stage.textContent = '';
|
||||
var vis = inp( 'visual_id' ), snd = inp( 'sound_id' );
|
||||
var visUrl = vis.value !== '0' ? vis.getAttribute( 'data-url' ) : '', visMime = vis.getAttribute( 'data-mime' ) || '';
|
||||
var sndUrl = snd.value !== '0' ? snd.getAttribute( 'data-url' ) : '';
|
||||
var volume = Math.max( 0, Math.min( 100, parseInt( form.elements.volume.value, 10 ) || 0 ) ) / 100;
|
||||
var dur = Math.max( 1, Math.min( 60, parseFloat( form.elements.duration.value ) || 6 ) ) * 1000;
|
||||
var trig = form.querySelector( 'input[name="trigger_type"]:checked' );
|
||||
var amt = trig && trig.value === 'amount' ? toMinor( form.elements.amount.value ) : null;
|
||||
var rewardSel = form.elements.action_id;
|
||||
var reward = rewardSel && rewardSel.value !== '0' && rewardSel.selectedIndex > 0 ? rewardSel.options[ rewardSel.selectedIndex ].text.replace( / \(turned off\)$/, '' ) : 'Your reward';
|
||||
var vals = { name: 'Alex', amount: money( amt || 500 ), reward: reward };
|
||||
var msg = render( form.elements.message.value, vals );
|
||||
|
||||
var 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' );
|
||||
if ( isVideo ) {
|
||||
video = document.createElement( 'video' );
|
||||
video.playsInline = true; video.setAttribute( 'playsinline', '' );
|
||||
video.muted = !! sndUrl || volume === 0; video.volume = volume;
|
||||
video.src = visUrl; box.appendChild( video );
|
||||
} else {
|
||||
var img = new Image(); img.alt = ''; img.src = visUrl; box.appendChild( img );
|
||||
}
|
||||
card.appendChild( box );
|
||||
}
|
||||
var head = el( 'div', 'sga-alert-head' );
|
||||
if ( msg ) { head.textContent = msg; }
|
||||
else { head.appendChild( el( 'b', null, vals.name ) ); head.appendChild( document.createTextNode( ' donated ' ) ); head.appendChild( el( 'b', null, vals.amount ) ); }
|
||||
card.appendChild( head );
|
||||
stage.appendChild( card );
|
||||
|
||||
if ( sndUrl ) {
|
||||
var au = new Audio( sndUrl ); au.volume = volume; media.push( au );
|
||||
var p = au.play(); if ( p && p.catch ) { p.catch( function () { head.appendChild( el( 'div', 'sga-idle', 'Sound was blocked by the browser.' ) ); } ); }
|
||||
}
|
||||
var end = function () { stop(); stage.textContent = ''; stage.appendChild( el( 'span', 'sga-idle', 'Preview finished.' ) ); };
|
||||
if ( video ) {
|
||||
media.push( video );
|
||||
video.onended = end;
|
||||
var vp = video.play();
|
||||
if ( vp && vp.catch ) { vp.catch( function () { video.muted = true; var again = video.play(); if ( again && again.catch ) { again.catch( function () {} ); } } ); }
|
||||
timers.push( setTimeout( end, cfg.videoCap ) );
|
||||
} else {
|
||||
timers.push( setTimeout( end, dur ) );
|
||||
}
|
||||
}
|
||||
/* 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".' ) );
|
||||
}() );
|
||||
@@ -1,4 +1,4 @@
|
||||
.sg-donate{max-width:28rem;font:inherit}
|
||||
.sg-donate{max-width:min(100%,440px);font:inherit}
|
||||
.sg-donate .sg-row{margin:0 0 .9rem}
|
||||
.sg-donate label{display:block;font-weight:600;margin-bottom:.25rem}
|
||||
.sg-donate label.sg-inline{display:flex;gap:.5rem;align-items:center;font-weight:400}
|
||||
@@ -16,7 +16,8 @@
|
||||
.sg-donate label.sg-sub{font-weight:400;margin:.2rem 0 .25rem}
|
||||
.sg-donate .sg-hint{font-size:.85em;opacity:.75;margin-top:.25rem}
|
||||
.sg-donate .sg-cover{display:flex;align-items:center;gap:.5rem}
|
||||
.sg-donate .sg-info{flex:none;width:1.4rem;height:1.4rem;padding:0;border-radius:50%;border:1.5px solid currentColor;background:transparent;color:inherit;font:italic 700 .85rem/1 Georgia,serif;cursor:pointer;display:inline-flex;align-items:center;justify-content:center}
|
||||
.sg-donate .sg-info{flex:none;width:44px;height:44px;margin:-12px -12px -12px -8px;padding:0;position:relative;border:0;border-radius:50%;background:transparent;color:inherit;font:italic 700 14px/1 Georgia,serif;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;touch-action:manipulation}
|
||||
.sg-donate .sg-info::before{content:"";position:absolute;top:50%;left:50%;width:20px;height:20px;margin:-11px 0 0 -11px;border:1.5px solid currentColor;border-radius:50%;box-sizing:content-box}
|
||||
.sg-donate .sg-info:focus-visible{outline:2px solid currentColor;outline-offset:2px}
|
||||
.sg-donate .sg-tip{margin-top:.4rem;padding:.6rem .75rem;border:1px solid rgba(128,128,128,.5);border-radius:.4rem;font-size:.9em;line-height:1.4}
|
||||
.sg-donate .sg-presets.sg-actions{flex-direction:column;flex-wrap:nowrap;align-items:stretch}
|
||||
@@ -24,3 +25,31 @@
|
||||
.sg-donate .sg-act-title{font-weight:600}
|
||||
.sg-donate .sg-act-desc{font-size:.85em;font-weight:400;opacity:.8}
|
||||
.sg-donate .sg-presets button.sg-action:focus-visible{outline:2px solid currentColor;outline-offset:2px}
|
||||
|
||||
/* Mobile: 44px tap targets and 16px inputs (stops iOS Safari auto-zoom). px units on purpose: some themes shrink the root rem. */
|
||||
.sg-donate input[type=text],.sg-donate input[type=number],.sg-donate select,.sg-donate textarea{font-size:16px;min-height:44px}
|
||||
.sg-donate textarea{min-height:88px}
|
||||
.sg-donate .sg-presets button{min-height:44px}
|
||||
.sg-donate .sg-presets button.sg-action{min-height:44px}
|
||||
.sg-donate label.sg-inline{min-height:44px}
|
||||
.sg-donate label.sg-inline input[type=checkbox]{flex:none;width:22px;height:22px;margin:0}
|
||||
.sg-donate .sg-cover{gap:.25rem}
|
||||
.sg-donate .sg-act-title,.sg-donate .sg-act-desc,.sg-donate .sg-tip,.sg-donate .sg-msg,.sg-donate .sg-total{overflow-wrap:anywhere}
|
||||
|
||||
.sg-donate .sg-next-unlock{margin:0 0 .9rem;padding:.5rem .75rem;border:1px solid rgba(128,128,128,.5);border-left-width:4px;border-radius:.4rem;font-weight:600;line-height:1.4;overflow-wrap:anywhere}
|
||||
.sg-donate .sg-next-unlock[hidden]{display:none}
|
||||
.sg-donate .sg-presets button.sg-action{padding-right:2.2em}
|
||||
.sg-donate .sg-presets.sg-actions{padding:0 5px}
|
||||
|
||||
.sg-donate .sg-notice{margin:.6rem 0 0;font-size:.9em;line-height:1.4;opacity:.85;overflow-wrap:anywhere}
|
||||
|
||||
/* Progress bar (theme-neutral: inherits text colour; fill uses currentColor so it follows the theme). */
|
||||
.sg-donate .sg-progress{margin:0 0 .9rem;max-width:100%;box-sizing:border-box}
|
||||
.sg-donate .sg-progress-bar{position:relative;height:14px;border:1px solid rgba(128,128,128,.45);border-radius:999px;background:rgba(128,128,128,.22);overflow:hidden;box-shadow:inset 0 1px 2px rgba(0,0,0,.18)}
|
||||
.sg-donate .sg-progress-fill{display:block;height:100%;width:0;background:linear-gradient(90deg,var(--sg-accent,#7c5cff),var(--sg-accent2,#22d3ee));min-width:0;border-radius:999px;transition:width .6s ease}
|
||||
.sg-donate .sg-progress-text{display:flex;flex-wrap:wrap;justify-content:space-between;gap:.25rem .75rem;margin-top:.35rem;font-weight:600;line-height:1.4;overflow-wrap:anywhere}
|
||||
.sg-donate .sg-progress-tier,.sg-donate .sg-progress-done{margin:.25rem 0 0;font-size:.9em;line-height:1.4;overflow-wrap:anywhere}
|
||||
.sg-donate .sg-progress-done{font-weight:700}
|
||||
.sg-donate .sg-progress [hidden]{display:none}
|
||||
.sg-donate.sg-progress-only .sg-progress{margin-bottom:0}
|
||||
@media (prefers-reduced-motion:reduce){.sg-donate .sg-progress-fill{transition:none}}
|
||||
+76
-7
@@ -1,9 +1,12 @@
|
||||
/* StreamGoals donate form (vanilla JS). Config comes from window.StreamGoalsDonate. */
|
||||
(function () {
|
||||
'use strict';
|
||||
var C = window.StreamGoalsDonate;
|
||||
if (!C) { return; }
|
||||
var T = C.i18n || {};
|
||||
var C = window.StreamGoalsDonate; // donate form config (absent on pages with only [streamgoals_progress])
|
||||
var PC = window.StreamGoalsProgress; // progress bar config (rest url, labels, poll interval)
|
||||
if (!C && !PC) { return; }
|
||||
var T = (C && C.i18n) || {};
|
||||
var PT = (PC && PC.i18n) || {};
|
||||
var REST = (C && C.restUrl) || (PC && PC.restUrl) || '';
|
||||
var sdkPromise = null, sdkCurrency = null;
|
||||
|
||||
function el(tag, attrs, children) {
|
||||
@@ -18,7 +21,7 @@
|
||||
|
||||
function api(path, opts) {
|
||||
opts = opts || {};
|
||||
return fetch(C.restUrl + path, {
|
||||
return fetch(REST + path, {
|
||||
method: opts.method || 'GET',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: opts.body ? JSON.stringify(opts.body) : undefined,
|
||||
@@ -62,12 +65,60 @@
|
||||
}
|
||||
function sprintf1(tpl, v) { return String(tpl || '%s').replace('%s', v); }
|
||||
|
||||
/* ---- Progress bar: server renders the markup, this keeps it fresh (same code for form and [streamgoals_progress]). ---- */
|
||||
function tpl(str, a, b) {
|
||||
return String(str || '').replace('%1$s', function () { return a; }).replace('%2$s', function () { return b; });
|
||||
}
|
||||
function applyBar(box, p) {
|
||||
if (!box || !p) { return; }
|
||||
var pct = Math.max(0, Math.min(100, parseInt(p.percent, 10) || 0));
|
||||
var bar = box.querySelector('.sg-progress-bar');
|
||||
var of = tpl(PT['of'] || '%1$s / %2$s', p.raised_display, p.target_display);
|
||||
box.setAttribute('data-goal', String(p.goal_id));
|
||||
box.className = 'sg-progress' + (p.reached ? ' sg-progress-reached' : '');
|
||||
bar.setAttribute('aria-valuenow', String(pct));
|
||||
bar.setAttribute('aria-valuetext', p.reached ? (PT.reached || '') : of + ' (' + pct + '%)');
|
||||
bar.setAttribute('aria-label', String(PT.label || '%s').replace('%s', function () { return p.title; }));
|
||||
bar.firstChild.style.width = pct + '%';
|
||||
box.querySelector('.sg-progress-amounts').textContent = of;
|
||||
box.querySelector('.sg-progress-pct').textContent = pct + '%';
|
||||
var tier = box.querySelector('.sg-progress-tier'), done = box.querySelector('.sg-progress-done');
|
||||
tier.hidden = !p.tier;
|
||||
tier.textContent = p.tier ? tpl(PT.tier, p.tier.title, p.tier.target_display) : '';
|
||||
done.hidden = !p.reached;
|
||||
done.textContent = p.reached ? (PT.reached || '') : '';
|
||||
}
|
||||
function refreshGoal(id, bust) {
|
||||
return api('/progress?goal=' + encodeURIComponent(id) + (bust ? '&t=' + Date.now() : '')).then(function (p) {
|
||||
Array.prototype.forEach.call(document.querySelectorAll('.sg-progress'), function (b) {
|
||||
if (b.getAttribute('data-goal') === String(p.goal_id)) { applyBar(b, p); }
|
||||
});
|
||||
}, function () { /* keep showing the last known numbers */ });
|
||||
}
|
||||
function refreshAll(bust) {
|
||||
var seen = {};
|
||||
Array.prototype.forEach.call(document.querySelectorAll('.sg-progress'), function (b) {
|
||||
var id = b.getAttribute('data-goal');
|
||||
if (id && id !== '0' && !seen[id]) { seen[id] = true; refreshGoal(id, bust); }
|
||||
});
|
||||
}
|
||||
function startPolling() {
|
||||
if (!REST || !document.querySelector('.sg-progress')) { return; }
|
||||
var every = Math.max(15000, (PC && PC.pollMs) || 30000);
|
||||
setInterval(function () { if (document.visibilityState !== 'hidden') { refreshAll(false); } }, every);
|
||||
document.addEventListener('visibilitychange', function () { if (document.visibilityState === 'visible') { refreshAll(true); } });
|
||||
refreshAll(true); // a cached page may hold old numbers
|
||||
}
|
||||
// After a successful donation: refresh now, and again shortly (a pending capture can finalize a moment later).
|
||||
function afterDonation() { refreshAll(true); setTimeout(function () { refreshAll(true); }, 5000); }
|
||||
|
||||
function init(root) {
|
||||
var pinned = parseInt(root.getAttribute('data-goal'), 10) || 0;
|
||||
var goals = C.goals.filter(function (g) { return !pinned || g.id === pinned; });
|
||||
if (!goals.length) { return; }
|
||||
var uid = 'sg' + Math.random().toString(36).slice(2, 8);
|
||||
var state = { goal: goals[0], renderToken: 0, quote: null };
|
||||
var barBox = root.querySelector('.sg-progress');
|
||||
|
||||
var goalSel = el('select', { id: uid + '-goal' });
|
||||
goals.forEach(function (g) { goalSel.appendChild(el('option', { value: g.id, text: g.title + ' (' + g.currency + ')' })); });
|
||||
@@ -82,6 +133,18 @@
|
||||
var status = el('div', { 'class': 'sg-msg', role: 'status' });
|
||||
var buttons = el('div', { 'class': 'sg-buttons' });
|
||||
|
||||
// "Next unlock" line for tiered goals (server computes title + remaining minor units per goal).
|
||||
var nextLine = el('p', { 'class': 'sg-next-unlock', 'aria-live': 'polite' });
|
||||
nextLine.hidden = true;
|
||||
function showNext() {
|
||||
var n = state.goal.nextUnlock;
|
||||
if (!n || !n.title || !(n.remaining_minor > 0)) { nextLine.hidden = true; nextLine.textContent = ''; return; }
|
||||
nextLine.textContent = String(T.nextUnlock || 'Next unlock: %1$s \u2014 %2$s to go')
|
||||
.replace('%1$s', function () { return n.title; })
|
||||
.replace('%2$s', function () { return fmt(n.remaining_minor, state.goal.exp, state.goal.currency); });
|
||||
nextLine.hidden = false;
|
||||
}
|
||||
root.appendChild(nextLine);
|
||||
if (goals.length > 1) { root.appendChild(row([el('label', { 'for': uid + '-goal', text: T.goal }), goalSel])); }
|
||||
root.appendChild(row([el('label', { text: T.amount }), presetBox, el('label', { 'class': 'sg-sub', 'for': uid + '-amt', text: T.customAmount || 'Or enter your own amount' }), amount, hint]));
|
||||
var nameRow = row([el('label', { 'for': uid + '-name', text: T.name }), name]);
|
||||
@@ -109,6 +172,7 @@
|
||||
root.appendChild(row([total]));
|
||||
root.appendChild(status); // messages sit above the PayPal buttons, next to the form fields
|
||||
root.appendChild(buttons);
|
||||
if (C.notice) { root.appendChild(el('p', { 'class': 'sg-notice', text: String(C.notice) })); } // e.g. "Donations are non-refundable." right where the donor pays
|
||||
|
||||
function say(text, cls) { status.textContent = text || ''; status.className = 'sg-msg' + (cls ? ' ' + cls : ''); }
|
||||
function amountStr() { return amount.value.trim().replace(',', '.'); }
|
||||
@@ -214,6 +278,7 @@
|
||||
onApprove: function (data) {
|
||||
return api('/orders/' + encodeURIComponent(data.orderID) + '/capture', { method: 'POST' }).then(function (r) {
|
||||
say(r.status === 'completed' ? T.thanks : T.processing, 'sg-ok');
|
||||
afterDonation();
|
||||
});
|
||||
},
|
||||
onError: function (err) { say((err && err.message) || T.error, 'sg-error'); }
|
||||
@@ -223,11 +288,15 @@
|
||||
|
||||
goalSel.addEventListener('change', function () {
|
||||
state.goal = goals.filter(function (g) { return String(g.id) === goalSel.value; })[0] || goals[0];
|
||||
buildPresets(); refresh(); renderButtons();
|
||||
if (barBox && state.goal.progress) { applyBar(barBox, state.goal.progress); refreshGoal(state.goal.id, true); }
|
||||
showNext(); buildPresets(); refresh(); renderButtons();
|
||||
});
|
||||
buildPresets(); refresh(); renderButtons();
|
||||
showNext(); buildPresets(); refresh(); renderButtons();
|
||||
}
|
||||
|
||||
function boot() { Array.prototype.forEach.call(document.querySelectorAll('.sg-donate'), init); }
|
||||
function boot() {
|
||||
if (C) { Array.prototype.forEach.call(document.querySelectorAll('.sg-donate:not(.sg-progress-only)'), init); }
|
||||
startPolling();
|
||||
}
|
||||
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot); } else { boot(); }
|
||||
})();
|
||||
@@ -24,6 +24,8 @@ body.sg-offline #sg-root{opacity:.6}
|
||||
.sg-w-alerts #sg-root{align-items:flex-end}
|
||||
.sg-alert{width:100%;text-align:center;background:var(--sg-bg);border:.1em solid var(--sg-accent);border-radius:.7em;padding:.6em .9em;animation:sg-in .6s cubic-bezier(.22,1,.36,1) both}
|
||||
.sg-alert.sg-out{animation:sg-out .5s ease-in both}
|
||||
.sg-alert-media{display:flex;justify-content:center;margin-bottom:.4em}
|
||||
.sg-alert-media img,.sg-alert-media video{display:block;max-width:100%;max-height:45vh;object-fit:contain;border-radius:.4em;background:transparent}
|
||||
.sg-alert-head{font-weight:800;font-size:1.2em}
|
||||
.sg-alert-head b{color:var(--sg-accent2)}
|
||||
.sg-alert-msg{margin-top:.3em;font-size:.85em;overflow-wrap:anywhere;max-height:5.2em;overflow:hidden}
|
||||
@@ -38,8 +40,8 @@ body.sg-offline #sg-root{opacity:.6}
|
||||
@media (prefers-reduced-motion:reduce){.sg-fill{transition:none}.sg-alert,.sg-alert.sg-out,.sg-alert.sg-bonus,.sg-alert.sg-bonus.sg-out{animation:none}.sg-alert.sg-bonus{box-shadow:0 0 .8em var(--sg-accent2)}}
|
||||
.sg-w-actions #sg-root{align-items:flex-start}
|
||||
.sg-w-actions #sg-root:empty{display:none}
|
||||
.sg-menu{height:100%;display:flex;flex-direction:column;overflow:hidden}
|
||||
.sg-menu-view{flex:1;min-height:0;overflow:hidden}
|
||||
.sg-menu{height:auto;display:flex;flex-direction:column;overflow:hidden;font-size:calc(1em * var(--sg-menu-scale,1))}
|
||||
.sg-menu-view{flex:none;min-height:0;overflow:hidden}
|
||||
.sg-menu-list{list-style:none;margin:0;padding:0}
|
||||
.sg-menu-item{padding:.3em 0;font-weight:600;overflow-wrap:anywhere}
|
||||
.sg-menu-item b{color:var(--sg-accent2);font-weight:800}
|
||||
@@ -47,3 +49,23 @@ body.sg-offline #sg-root{opacity:.6}
|
||||
.sg-menu-track.sg-scrolling{animation:sg-scroll var(--sg-scroll-s,20s) linear infinite}
|
||||
@keyframes sg-scroll{from{transform:translateY(0)}to{transform:translateY(-50%)}}
|
||||
@media (prefers-reduced-motion:reduce){.sg-menu-track.sg-scrolling{animation:none}}
|
||||
|
||||
/* Tiered goals */
|
||||
.sg-tier{font-size:.85em;font-weight:600;margin-bottom:.3em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--sg-accent2)}
|
||||
.sg-tier[hidden]{display:none}
|
||||
.sg-card.sg-tiers-done .sg-tier{font-weight:800}
|
||||
.sg-card.sg-tier-up{animation:sg-tier-pop 1.1s cubic-bezier(.22,1,.36,1) 2,sg-tier-glow 1.3s ease-in-out 2}
|
||||
.sg-bonus-line.sg-tier-line{background:linear-gradient(90deg,#f59e0b,#ef4444);color:#fff;border-radius:.3em;letter-spacing:.04em}
|
||||
@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}}
|
||||
+223
-22
@@ -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;
|
||||
|
||||
@@ -16,26 +17,52 @@
|
||||
}
|
||||
|
||||
// ---- goal ----
|
||||
var goal = null, shownRaised = 0, raf = 0;
|
||||
var goal = null, shownRaised = 0, raf = 0, lastTierKey = null, celebrateTimer = 0;
|
||||
function renderGoal(d) {
|
||||
if (!d.active) { root.textContent = ''; goal = null; return; }
|
||||
if (!d.active) { root.textContent = ''; goal = null; lastTierKey = null; return; }
|
||||
if (!goal) {
|
||||
root.textContent = '';
|
||||
var card = el('div', 'sg-card');
|
||||
goal = { title: el('div', 'sg-title'), fill: el('div', 'sg-fill'), pct: el('div', 'sg-pct'),
|
||||
goal = { card: card, tier: el('div', 'sg-tier'), title: el('div', 'sg-title'), fill: el('div', 'sg-fill'), pct: el('div', 'sg-pct'),
|
||||
raised: el('span'), target: el('span') };
|
||||
var track = el('div', 'sg-track');
|
||||
track.appendChild(goal.fill); track.appendChild(goal.pct);
|
||||
var nums = el('div', 'sg-nums'); nums.appendChild(goal.raised); nums.appendChild(goal.target);
|
||||
card.appendChild(goal.title); card.appendChild(track); card.appendChild(nums);
|
||||
goal.tier.hidden = true;
|
||||
card.appendChild(goal.title); card.appendChild(goal.tier); card.appendChild(track); card.appendChild(nums);
|
||||
root.appendChild(card);
|
||||
}
|
||||
goal.title.textContent = d.title;
|
||||
goal.target.textContent = d.target_display;
|
||||
goal.fill.style.width = d.percent + '%';
|
||||
goal.pct.textContent = d.percent + '%';
|
||||
renderTier(d.tiers);
|
||||
tweenRaised(d);
|
||||
}
|
||||
// Tiered goals only (d.tiers present): "Tier 2 of 4 \u00b7 title" above the bar, or "All tiers unlocked!".
|
||||
// Untiered goals keep the tier line hidden, so they look exactly as before. textContent only.
|
||||
function renderTier(t) {
|
||||
var valid = t && typeof t === 'object' && isFinite(Number(t.count)) && Number(t.count) > 0;
|
||||
goal.tier.hidden = !valid;
|
||||
goal.card.classList.toggle('sg-tiered', !!valid);
|
||||
goal.card.classList.toggle('sg-tiers-done', !!(valid && t.all_reached));
|
||||
if (!valid) { goal.tier.textContent = ''; lastTierKey = null; return; }
|
||||
var cur = t.current && typeof t.current === 'object' ? t.current : null;
|
||||
goal.tier.textContent = t.all_reached || !cur
|
||||
? 'All tiers unlocked!'
|
||||
: 'Tier ' + parseInt(t.index, 10) + ' of ' + parseInt(t.count, 10) + ' \u00b7 ' + String(cur.title || '');
|
||||
// Celebrate when the current tier changed between polls (never on the first poll / after a reload).
|
||||
var key = (t.all_reached ? 'done' : String(t.index)) + '/' + t.count;
|
||||
if (lastTierKey !== null && lastTierKey !== key) {
|
||||
goal.card.classList.remove('sg-tier-up');
|
||||
void goal.card.offsetWidth; // restart the animation
|
||||
goal.card.classList.add('sg-tier-up');
|
||||
clearTimeout(celebrateTimer);
|
||||
var card = goal.card;
|
||||
celebrateTimer = setTimeout(function () { card.classList.remove('sg-tier-up'); }, 2600);
|
||||
}
|
||||
lastTierKey = key;
|
||||
}
|
||||
function tweenRaised(d) {
|
||||
cancelAnimationFrame(raf);
|
||||
var from = shownRaised, to = d.raised_minor, t0 = performance.now(), dur = 1200;
|
||||
@@ -113,16 +140,88 @@
|
||||
firstAlertPoll = false;
|
||||
next();
|
||||
}
|
||||
// Alert media (optional per alert): {visual:{type,url}|null, sound:{url}|null, volume, duration_ms, message}.
|
||||
// Everything is built with createElement + property assignment; nothing from the server is parsed as HTML.
|
||||
var MEDIA_TIMEOUT = 8000, DEFAULT_HOLD = 6500, VIDEO_CAP = 30000;
|
||||
function okUrl(u) { return typeof u === 'string' && /^(https?:\/\/|\/)/i.test(u); }
|
||||
function cleanMedia(m) {
|
||||
if (!m || typeof m !== 'object') return null;
|
||||
var v = m.visual && typeof m.visual === 'object' && okUrl(m.visual.url) && (m.visual.type === 'image' || m.visual.type === 'video') ? m.visual : null;
|
||||
var s = m.sound && typeof m.sound === 'object' && okUrl(m.sound.url) ? m.sound : null;
|
||||
var msg = typeof m.message === 'string' && m.message ? m.message : null;
|
||||
if (!v && !s && !msg) return null;
|
||||
var vol = Number(m.volume); if (!isFinite(vol)) vol = 80;
|
||||
var dur = Number(m.duration_ms); if (!isFinite(dur) || dur <= 0) dur = DEFAULT_HOLD;
|
||||
return { 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.
|
||||
function preload(m, cb) {
|
||||
var out = { visual: null, sound: null }, pending = 0, fired = false, timer = 0;
|
||||
function finish() { if (fired) return; fired = true; clearTimeout(timer); cb(out); }
|
||||
function part() { pending++; var once = false; return function (ok, set) { if (once) return; once = true; if (ok && set) set(); if (--pending <= 0) finish(); }; }
|
||||
try {
|
||||
if (m.visual) {
|
||||
var vd = part();
|
||||
if (m.visual.type === 'image') {
|
||||
var img = new Image();
|
||||
img.onload = function () { vd(true, function () { out.visual = img; }); };
|
||||
img.onerror = function () { vd(false); };
|
||||
img.src = m.visual.url;
|
||||
} else {
|
||||
var vid = document.createElement('video');
|
||||
vid.preload = 'auto'; vid.playsInline = true; vid.muted = true;
|
||||
vid.setAttribute('playsinline', ''); vid.setAttribute('muted', '');
|
||||
vid.onloadeddata = function () { vd(true, function () { out.visual = vid; }); };
|
||||
vid.onerror = function () { vd(false); };
|
||||
vid.src = m.visual.url;
|
||||
try { vid.load(); } catch (e) { vd(false); }
|
||||
}
|
||||
}
|
||||
if (m.sound) {
|
||||
var sd = part();
|
||||
var au = new Audio();
|
||||
au.preload = 'auto';
|
||||
au.oncanplaythrough = function () { sd(true, function () { out.sound = au; }); };
|
||||
au.onerror = function () { sd(false); };
|
||||
au.src = m.sound.url;
|
||||
try { au.load(); } catch (e2) { sd(false); }
|
||||
}
|
||||
} catch (e3) { /* fall through to the timeout/finish below */ }
|
||||
if (!pending) { finish(); return; }
|
||||
timer = setTimeout(finish, MEDIA_TIMEOUT);
|
||||
}
|
||||
function next() {
|
||||
if (showing || !queue.length) return;
|
||||
showing = true;
|
||||
var a = queue.shift();
|
||||
var m = null;
|
||||
try { m = cleanMedia(a.media); } catch (e) { m = null; }
|
||||
if (!m) { present(a, null, null); return; }
|
||||
var called = false;
|
||||
function go(assets) { if (called) return; called = true; try { present(a, m, assets); } catch (err) { forceDone(); } }
|
||||
try { preload(m, go); } catch (e2) { go({ visual: null, sound: null }); }
|
||||
}
|
||||
function forceDone() { root.textContent = ''; showing = false; setTimeout(next, 0); }
|
||||
function present(a, m, assets) {
|
||||
root.textContent = '';
|
||||
var card = el('div', 'sg-alert');
|
||||
var head = el('div', 'sg-alert-head');
|
||||
head.appendChild(el('b', null, a.name));
|
||||
head.appendChild(document.createTextNode(' donated '));
|
||||
head.appendChild(el('b', null, a.amount_display));
|
||||
var vis = assets && assets.visual, snd = assets && assets.sound;
|
||||
if (vis) {
|
||||
var box = el('div', 'sg-alert-media');
|
||||
box.appendChild(vis);
|
||||
card.appendChild(box);
|
||||
card.classList.add('sg-has-media');
|
||||
if (m && m.frameless) card.classList.add('sg-frameless');
|
||||
}
|
||||
if (m && m.message) {
|
||||
head.textContent = m.message;
|
||||
} else {
|
||||
head.appendChild(el('b', null, a.name));
|
||||
head.appendChild(document.createTextNode(' donated '));
|
||||
head.appendChild(el('b', null, a.amount_display));
|
||||
}
|
||||
card.appendChild(head);
|
||||
var bonuses = Array.isArray(a.bonuses) ? a.bonuses : [];
|
||||
if (bonuses.length) {
|
||||
@@ -132,28 +231,110 @@
|
||||
}
|
||||
}
|
||||
var acts = Array.isArray(a.actions) ? a.actions : [];
|
||||
if (acts.length) card.classList.add('sg-bonus');
|
||||
var tiersUnlocked = Array.isArray(a.tiers) ? a.tiers : [];
|
||||
if (acts.length || tiersUnlocked.length) card.classList.add('sg-bonus');
|
||||
for (var k = 0; k < acts.length; k++) {
|
||||
var times = parseInt(acts[k].times, 10) || 1;
|
||||
card.appendChild(el('div', 'sg-bonus-line', 'ACTION: ' + String(acts[k].title) + (times > 1 ? ' x' + times : '')));
|
||||
}
|
||||
for (var q = 0; q < tiersUnlocked.length; q++) {
|
||||
var tt = tiersUnlocked[q] && tiersUnlocked[q].title;
|
||||
if (tt) card.appendChild(el('div', 'sg-bonus-line sg-tier-line', 'TIER UNLOCKED: ' + String(tt)));
|
||||
}
|
||||
if (a.message) card.appendChild(el('div', 'sg-alert-msg', a.message));
|
||||
root.appendChild(card);
|
||||
setTimeout(function () {
|
||||
|
||||
var finished = false, holdTimer = 0, capTimer = 0;
|
||||
function stopMedia() {
|
||||
try { if (snd) snd.pause(); } catch (e) { /* ignore */ }
|
||||
try { if (vis && vis.tagName === 'VIDEO') { vis.pause(); vis.removeAttribute('src'); vis.load(); } } catch (e2) { /* ignore */ }
|
||||
}
|
||||
function exit() {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
clearTimeout(holdTimer); clearTimeout(capTimer);
|
||||
stopMedia();
|
||||
card.classList.add('sg-out');
|
||||
setTimeout(function () { root.textContent = ''; showing = false; next(); }, 500);
|
||||
}, 6500);
|
||||
}
|
||||
var hold = m ? m.duration : DEFAULT_HOLD, isVideo = false;
|
||||
if (snd) {
|
||||
try {
|
||||
snd.volume = m.volume; snd.currentTime = 0;
|
||||
var sp = snd.play();
|
||||
if (sp && typeof sp.catch === 'function') sp.catch(function () { /* autoplay blocked: silent alert */ });
|
||||
} catch (e3) { /* ignore */ }
|
||||
}
|
||||
if (vis && vis.tagName === 'VIDEO') {
|
||||
isVideo = true;
|
||||
try {
|
||||
vis.loop = false;
|
||||
vis.muted = !!snd || m.volume === 0; // a separate sound wins; otherwise the clip's own audio at the set volume
|
||||
vis.volume = m.volume;
|
||||
vis.onended = exit;
|
||||
vis.onerror = exit;
|
||||
var vp = vis.play();
|
||||
if (vp && typeof vp.catch === 'function') {
|
||||
vp.catch(function () {
|
||||
// Autoplay with sound refused: retry muted so the picture still plays; give up (text only) if that fails too.
|
||||
try {
|
||||
vis.muted = true;
|
||||
var again = vis.play();
|
||||
if (again && typeof again.catch === 'function') again.catch(function () { if (vis.parentNode) vis.parentNode.removeChild(vis); clearTimeout(capTimer); holdTimer = setTimeout(exit, DEFAULT_HOLD); });
|
||||
} catch (e4) { exit(); }
|
||||
});
|
||||
}
|
||||
} catch (e5) { isVideo = false; }
|
||||
}
|
||||
if (isVideo) capTimer = setTimeout(exit, VIDEO_CAP); // videos play to the end, never longer than 30 s
|
||||
else holdTimer = setTimeout(exit, hold);
|
||||
}
|
||||
|
||||
// ---- actions (reward menu) ----
|
||||
// Renders nothing visible when there are no actions. Long lists scroll gently via CSS (--sg-rows sets the duration).
|
||||
var actionsSig = null;
|
||||
// Renders nothing visible when there are no actions. The card hugs its content and the text is scaled to the
|
||||
// LARGEST size that still fits the browser-source window (shrinks for long lists, grows for short ones), and
|
||||
// re-fits when the window is resized. Only if even the smallest size does not fit does it fall back to a gentle scroll.
|
||||
var actionsSig = null, menuEls = null, fitTimer = 0;
|
||||
var MENU_MIN = 0.5, MENU_MAX = 1.8;
|
||||
function fitMenu() {
|
||||
if (!menuEls) return;
|
||||
var card = menuEls.card, view = menuEls.view, track = menuEls.track, ul = menuEls.ul;
|
||||
// reset any previous scroll fallback
|
||||
track.classList.remove('sg-scrolling');
|
||||
while (track.children.length > 1) track.removeChild(track.lastChild);
|
||||
view.style.height = '';
|
||||
var cs = getComputedStyle(root);
|
||||
var inner = root.clientHeight - parseFloat(cs.paddingTop) - parseFloat(cs.paddingBottom);
|
||||
if (inner <= 0) return;
|
||||
function fits(scale) {
|
||||
card.style.setProperty('--sg-menu-scale', String(scale));
|
||||
return card.offsetHeight <= inner;
|
||||
}
|
||||
var lo = MENU_MIN, hi = MENU_MAX, best = null;
|
||||
if (fits(hi)) { best = hi; }
|
||||
else if (!fits(lo)) { best = null; }
|
||||
else { for (var i = 0; i < 9; i++) { var mid = (lo + hi) / 2; if (fits(mid)) { lo = mid; } else { hi = mid; } } best = lo; }
|
||||
if (best !== null) { card.style.setProperty('--sg-menu-scale', String(best)); return; }
|
||||
// Even the smallest size overflows: use the smallest and scroll gently inside the window.
|
||||
card.style.setProperty('--sg-menu-scale', String(MENU_MIN));
|
||||
var chrome = card.offsetHeight - view.offsetHeight;
|
||||
view.style.height = Math.max(40, inner - chrome) + 'px';
|
||||
var dup = ul.cloneNode(true);
|
||||
dup.setAttribute('aria-hidden', 'true');
|
||||
track.appendChild(dup);
|
||||
track.style.setProperty('--sg-scroll-s', Math.max(8, menuEls.count * 3) + 's');
|
||||
track.classList.add('sg-scrolling');
|
||||
}
|
||||
function scheduleFit() { clearTimeout(fitTimer); fitTimer = setTimeout(fitMenu, 120); }
|
||||
window.addEventListener('resize', scheduleFit);
|
||||
if (typeof ResizeObserver === 'function') { try { new ResizeObserver(scheduleFit).observe(document.documentElement); } catch (e) { /* resize event is the fallback */ } }
|
||||
function renderActions(d) {
|
||||
var list = Array.isArray(d.actions) ? d.actions : [];
|
||||
var sig = JSON.stringify(list);
|
||||
if (sig === actionsSig) return;
|
||||
actionsSig = sig;
|
||||
root.textContent = '';
|
||||
menuEls = null;
|
||||
if (!d.active || !list.length) return;
|
||||
var card = el('div', 'sg-card sg-menu');
|
||||
var view = el('div', 'sg-menu-view');
|
||||
@@ -171,16 +352,8 @@
|
||||
view.appendChild(track);
|
||||
card.appendChild(view);
|
||||
root.appendChild(card);
|
||||
// Overflow check after layout: duplicate the list for a seamless loop and start the CSS scroll.
|
||||
requestAnimationFrame(function () {
|
||||
if (ul.scrollHeight > view.clientHeight + 2) {
|
||||
var dup = ul.cloneNode(true);
|
||||
dup.setAttribute('aria-hidden', 'true');
|
||||
track.appendChild(dup);
|
||||
track.style.setProperty('--sg-scroll-s', Math.max(8, list.length * 3) + 's');
|
||||
track.classList.add('sg-scrolling');
|
||||
}
|
||||
});
|
||||
menuEls = { card: card, view: view, track: track, ul: ul, count: list.length };
|
||||
requestAnimationFrame(fitMenu);
|
||||
}
|
||||
|
||||
// ---- polling ----
|
||||
@@ -193,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;
|
||||
@@ -201,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');
|
||||
|
||||
+29
-2
@@ -20,7 +20,7 @@ Namespace `StreamGoals\`, PSR-4 rooted at `includes/`. Text domain `streamgoals-
|
||||
|
||||
## Database (created by `Core\Installer`, version in option `sg_db_version`)
|
||||
- `sg_goals`: id, title, target_minor, currency, status(active|paused|complete), starts_at, ends_at NULL, counts_fees TINYINT(0 = base amount only), created_at
|
||||
- `sg_donations`: id, goal_id, paypal_order_id, paypal_capture_id UNIQUE, base_minor, fee_minor, total_minor, currency, donor_name, is_anonymous, message, status(pending|completed|refunded|reversed), moderation(approved|pending|rejected), created_at
|
||||
- `sg_donations`: id, goal_id, paypal_order_id, paypal_capture_id UNIQUE, base_minor, fee_minor, total_minor, currency, donor_name, is_anonymous, message, status(pending|completed|refunded|reversed), moderation(approved|pending|rejected), moderation_flags, effects_applied_at NULL (v6), created_at
|
||||
- `sg_rules`: id, goal_id, type(add_time|counter|bonus), config JSON, enabled, sort
|
||||
- `sg_rule_events`: id, rule_id, donation_id, delta (seconds or count), reversed TINYINT, created_at — UNIQUE(rule_id, donation_id) for idempotency
|
||||
- `sg_state`: goal_id, key, value — timer `ends_at`, counter totals, carry-over remainders
|
||||
@@ -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"
|
||||
@@ -47,6 +47,8 @@ Rule `config` examples (`max_total_seconds` caps what one rule has added over ti
|
||||
## Public REST (namespace `streamgoals/v1`)
|
||||
- `POST /orders` (create order; server computes total incl. optional fee cover), `POST /orders/{id}/capture`
|
||||
- `POST /webhook` (PayPal signature verified; deduped by capture id)
|
||||
- `GET /progress?goal=ID` — public, read-only, rate limited (60/min per visitor). Returns `Overlay\Progress::payload()` only: `goal_id,title,currency,raised_minor,target_minor,percent,raised_display,target_display,reached,tier|null` (`tier` = `{index,count,title,target_minor,target_display}`). No donor data. 404 unless goal status is active/complete. `Cache-Control: public, max-age=10`.
|
||||
Shortcodes `[streamgoals_donate show_progress="yes|no"]` (default yes) and `[streamgoals_progress goal=""]` server-render `Progress::html()` (role=progressbar); `donate.js` updates it in place (after a donation, every 30 s while the tab is visible, and once on load for cached pages). Numbers come from `Payloads::goal()`, so they match the overlay; reached = closed at target, all tiers reached, or raised >= target.
|
||||
- `GET /overlay/{token}/{widget}` — ETag'd JSON, polled every 2–3 s; widgets: `goal`, `timer`, `counter`, `alerts`
|
||||
|
||||
## Fee cover
|
||||
@@ -81,3 +83,28 @@ Amounts must be >= Settings::effectiveMin().
|
||||
action_id (for `reward`: applies when that reward triggered; a reward definition wins over an amount definition), title (admin label),
|
||||
visual_id + visual_type (`image` | `video` | '' none), sound_id (audio attachment, 0 none), volume 0-100, duration_ms (how long an image/GIF stays; videos play to the end, capped),
|
||||
message (template with {name} {amount} {reward}; '' = default text), enabled, sort, created_at.
|
||||
|
||||
## Goal tiers (milestones) — contract (Installer DB_VERSION 4)
|
||||
A goal may have ordered TIERS; each is a cumulative target with an item/unlock (e.g. $100 "Giveaway", $250 "New microphone", $500 "24-hour stream").
|
||||
- `sg_goal_tiers`: id, goal_id, target_minor (cumulative raised total needed), title VARCHAR(120) (the item/unlock), description VARCHAR(255), reached_at DATETIME NULL,
|
||||
reached_donation_id BIGINT UNSIGNED NULL, created_at; UNIQUE(goal_id, target_minor). Tier order = target_minor ascending.
|
||||
- A goal WITH tiers keeps `sg_goals.target_minor` equal to its HIGHEST tier target (maintained automatically when tiers change; the goal form shows the target as derived/read-only). So "end at target" closes the goal when the FINAL tier is reached, and everything that reads goal target keeps working.
|
||||
- Raised total for tiers uses the same basis as the goal (`GoalRepository::raised_minor`, base vs total per counts_fees).
|
||||
- Reaching a tier: after a donation is completed (same finalize path as rules/actions, BEFORE the close-at-target check, never throwing, idempotent): for every tier of the goal with reached_at IS NULL and target_minor <= raised, set reached_at=NOW and reached_donation_id=that donation with `UPDATE ... WHERE id=? AND reached_at IS NULL` (a big donation can unlock several tiers at once; all get its id).
|
||||
- "Current tier" = the first tier (by target) with reached_at IS NULL. Goal bar progress for a tiered goal = (raised - floor) / (target - floor) clamped 0..1, where floor = previous tier's target (0 for the first); the cumulative raised and the current tier target are still displayed.
|
||||
- Reached tiers: title/description editable, target locked; a new tier's target must be above the goal's current raised total and unique.
|
||||
- Overlay `goal` payload for a tiered goal adds `tiers: {count, index (1-based current), current:{title,description,target_minor,target_display,floor_minor}|null, all_reached}`; untiered goals are unchanged. Alert payloads gain `tiers: [{title}]` = tiers whose reached_donation_id is that donation, shown as a "TIER UNLOCKED: title" pill.
|
||||
|
||||
## Schema v6 (Installer, DB_VERSION 6): donor-name flagging + effects reconciliation
|
||||
Only our own `sg_donations` table changes (two columns, added by dbDelta):
|
||||
- `moderation_flags VARCHAR(16) NOT NULL DEFAULT ''`: why a row is held. `''` (legacy/approved), `message`, `name` or `name,message`. Display only (`Admin\Format::flaggedLabel`); `moderation` stays the single source of truth for visibility. A held row with `''` flags is shown as "Message" (before v6 only messages were held).
|
||||
- `effects_applied_at DATETIME NULL`: set (UTC) once ALL side effects of a completed donation finished without error.
|
||||
|
||||
### Donor-name flagging
|
||||
`OrderValidator::validate` runs the streamer's `ProfanityFilter` over `donor_name` (non-anonymous only; anonymous names are blanked first and never stored). `ProfanityFilter::matches()` shares the scan with `filter()`. The filter has a single mode, MASK: the stored name is already masked (`f***`), exactly like messages. A tripped name sets `moderation='pending'` and `moderation_flags` includes `name`, independent of the `moderate_messages` setting; a non-empty message with `moderate_messages` on adds `message`. The donation completes and counts for goal/timer/counter/rewards/tiers as usual (moderation never gates those).
|
||||
Alerts: `Overlay\Payloads::alerts` (and `WpdbDataSource`, `DonationRepository::recentApproved`) only emit `completed` + `approved` rows, so a held donation emits NO alert at all (the whole alert is held, same as a held message). It is never shown as "Anonymous". After Approve the alert shows the masked name; Reject = never shown.
|
||||
|
||||
### Reconciliation of "completed but side effects lost"
|
||||
`DonationStore::notify_applied($id): bool` runs engine (rules/timer/counter), `Actions\Recorder`, `Tiers\Recorder` (before the close check), then end-at-target, and only if every step succeeded calls `mark_effects_applied` (`UPDATE ... WHERE effects_applied_at IS NULL`). `CaptureFinalizer` is unchanged: `mark_completed` stays the atomic single-winner pending->completed step and both the capture endpoint and the webhook call `notify_applied` only for the winner, so a replay never re-runs it inline.
|
||||
`Maintenance::reconcile_effects` (cron `sg_reconcile_effects`, every 5 min, single-flight via `GET_LOCK`) selects up to 25 `status='completed' AND effects_applied_at IS NULL AND goal_id>0` rows created more than 2 minutes and less than 30 days ago and calls `notify_applied` again. Replay safety: rules via `sg_rule_events` UNIQUE(rule_id,donation_id) (event inserted first, state only touched if new, under the goal lock); rewards via `INSERT IGNORE` on UNIQUE(donation_id,action_id); tiers via `UPDATE ... WHERE reached_at IS NULL`; close-at-target via `UPDATE ... WHERE status='active'`.
|
||||
Upgrade: `Installer::maybe_upgrade` passes the stored version to `install_schema`; when it is < 6 (or absent) it backfills `effects_applied_at` for every already-completed row BEFORE writing `sg_db_version`, so history is never replayed and a failed backfill is retried on the next load. Known gap (unchanged): in `Engine::applyRule` the event row is recorded before state is updated, so a death between those two statements loses that single rule's effect and a replay skips it.
|
||||
@@ -6,21 +6,27 @@ namespace StreamGoals\Actions;
|
||||
/** Queues the on-stream actions a completed donation triggers. */
|
||||
final class Recorder {
|
||||
|
||||
/** Never throws. Idempotent: replays are ignored by the UNIQUE key on sg_action_events. */
|
||||
public static function forDonation( int $donationId ): void {
|
||||
/**
|
||||
* Never throws. Idempotent: replays are ignored by the UNIQUE key on sg_action_events.
|
||||
*
|
||||
* @return bool False only when something failed (so the caller must not mark the donation's effects as applied).
|
||||
*/
|
||||
public static function forDonation( int $donationId ): bool {
|
||||
try {
|
||||
global $wpdb;
|
||||
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT id, goal_id, base_minor, status FROM ' . $wpdb->prefix . 'sg_donations WHERE id = %d', $donationId ), ARRAY_A );
|
||||
if ( ! is_array( $row ) || 'completed' !== ( $row['status'] ?? '' ) ) {
|
||||
return;
|
||||
return true;
|
||||
}
|
||||
$repo = new ActionRepository( $wpdb );
|
||||
$matches = Matcher::match( (int) $row['base_minor'], $repo->enabledForGoal( (int) $row['goal_id'] ) );
|
||||
if ( $matches ) {
|
||||
$repo->recordEvents( $donationId, $matches );
|
||||
}
|
||||
return true;
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: Recorder failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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> × ' . (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> × ' . (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 {
|
||||
|
||||
@@ -25,9 +25,14 @@ final class Admin {
|
||||
'sg_rule_save' => array( GoalsPage::class, 'handleRuleSave' ),
|
||||
'sg_rule_toggle' => array( GoalsPage::class, 'handleRuleToggle' ),
|
||||
'sg_rule_delete' => array( GoalsPage::class, 'handleRuleDelete' ),
|
||||
'sg_tier_save' => array( GoalsPage::class, 'handleTierSave' ),
|
||||
'sg_tier_delete' => array( GoalsPage::class, 'handleTierDelete' ),
|
||||
'sg_action_save' => array( ActionsPage::class, 'handleSave' ),
|
||||
'sg_action_toggle' => array( ActionsPage::class, 'handleToggle' ),
|
||||
'sg_action_delete' => array( ActionsPage::class, 'handleDelete' ),
|
||||
'sg_alert_save' => array( AlertsPage::class, 'handleSave' ),
|
||||
'sg_alert_toggle' => array( AlertsPage::class, 'handleToggle' ),
|
||||
'sg_alert_delete' => array( AlertsPage::class, 'handleDelete' ),
|
||||
'sg_event_done' => array( ActionsPage::class, 'handleDone' ),
|
||||
'sg_event_done_all' => array( ActionsPage::class, 'handleDoneAll' ),
|
||||
'sg_export_csv' => array( DonationsPage::class, 'handleExport' ),
|
||||
@@ -35,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' ),
|
||||
);
|
||||
|
||||
@@ -65,6 +71,7 @@ final class Admin {
|
||||
$queued = ActionsPage::queuedCount();
|
||||
$qbadge = $queued > 0 ? ' <span class="awaiting-mod">' . (int) $queued . '</span>' : '';
|
||||
add_submenu_page( self::HOME, 'Rewards', 'Rewards' . $qbadge, self::CAP, ActionsPage::PAGE, array( ActionsPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Alerts', 'Alerts', self::CAP, AlertsPage::PAGE, array( AlertsPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Overlays', 'Overlays', self::CAP, 'streamgoals-overlays', array( OverlaysPage::class, 'render' ) );
|
||||
add_submenu_page( self::HOME, 'Settings', 'Settings', self::CAP, 'streamgoals-settings', array( SettingsPage::class, 'render' ) );
|
||||
}
|
||||
@@ -101,6 +108,11 @@ final class Admin {
|
||||
if ( ActionsPage::PAGE === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-actions', STREAMGOALS_URL . 'assets/admin/actions.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
if ( AlertsPage::PAGE === $page ) {
|
||||
wp_enqueue_media();
|
||||
wp_enqueue_style( 'streamgoals-alerts', STREAMGOALS_URL . 'assets/admin/alerts.css', array( 'streamgoals-admin' ), STREAMGOALS_VERSION );
|
||||
wp_enqueue_script( 'streamgoals-alerts', STREAMGOALS_URL . 'assets/admin/alerts.js', array( 'streamgoals-admin', 'jquery' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
if ( 'streamgoals-overlays' === $page ) {
|
||||
wp_enqueue_script( 'streamgoals-overlays', STREAMGOALS_URL . 'assets/admin/overlays.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true );
|
||||
}
|
||||
@@ -159,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>';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,277 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Actions\ActionRepository;
|
||||
use StreamGoals\Alerts\DefInput;
|
||||
use StreamGoals\Alerts\DefRepository;
|
||||
use StreamGoals\Alerts\Media;
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
/** "Alerts": pictures, GIFs, videos and sounds that play on the alerts overlay for certain donations or rewards. */
|
||||
final class AlertsPage {
|
||||
|
||||
public const PAGE = 'streamgoals-alerts';
|
||||
|
||||
private static function repo(): DefRepository {
|
||||
return new DefRepository();
|
||||
}
|
||||
|
||||
private static function minMinor(): int {
|
||||
return Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
|
||||
}
|
||||
|
||||
private static function url( array $args = array() ): string {
|
||||
return Admin::url( self::PAGE, $args );
|
||||
}
|
||||
|
||||
/** @return array<int,string> goal id => title */
|
||||
private static function goalTitles(): array {
|
||||
$out = array();
|
||||
foreach ( Store::goals()->all() as $g ) {
|
||||
$out[ (int) $g['id'] ] = (string) $g['title'];
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** Attachment lookup for validation: mime + size, null when missing. */
|
||||
public static function attachmentInfo( int $id ): ?array {
|
||||
if ( $id <= 0 || 'attachment' !== get_post_type( $id ) ) {
|
||||
return null;
|
||||
}
|
||||
$path = get_attached_file( $id );
|
||||
return array(
|
||||
'mime' => (string) get_post_mime_type( $id ),
|
||||
'size' => ( is_string( $path ) && is_file( $path ) ) ? (int) filesize( $path ) : 0,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
Admin::open( 'Alerts' );
|
||||
$edit = Admin::get_int( 'edit' );
|
||||
if ( 'new' === Admin::get_str( 'view' ) || $edit ) {
|
||||
self::renderForm( $edit );
|
||||
} else {
|
||||
self::renderHelp();
|
||||
self::renderList();
|
||||
}
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
private static function renderHelp(): void {
|
||||
echo '<div class="sg-card"><h2>Make your alerts come alive</h2>';
|
||||
echo '<p>An alert is the pop-up on your stream when someone donates. Here you can give it a picture, a GIF or a video, and a sound. Pick the donation size (or a reward) that should trigger it.</p>';
|
||||
echo '<ul class="sga-help">';
|
||||
echo '<li><strong>By amount:</strong> "Any donation of at least $X". If several match, the one with the highest $X wins.</li>';
|
||||
echo '<li><strong>By reward:</strong> plays when a donor triggers one of your rewards. A reward alert beats an amount alert.</li>';
|
||||
echo '<li>Nothing set up? Alerts look and work exactly as before.</li>';
|
||||
echo '<li><strong>In OBS media plays automatically. In a normal browser tab you must click the page once before sound is allowed.</strong></li>';
|
||||
echo '<li>Pictures and GIFs stay for the time you choose. Videos play to the end, for at most 30 seconds.</li>';
|
||||
echo '<li>Keep files small (under 25 MB). Big videos make OBS slow to load and can make your stream stutter.</li>';
|
||||
echo '</ul></div>';
|
||||
}
|
||||
|
||||
private static function renderList(): void {
|
||||
$cur = Admin::currency();
|
||||
$defs = self::repo()->all();
|
||||
$goals = self::goalTitles();
|
||||
$rewards = array();
|
||||
foreach ( ( new ActionRepository() )->all() as $a ) {
|
||||
$rewards[ $a['id'] ] = $a['title'];
|
||||
}
|
||||
echo '<div class="sg-card"><h2>Your alerts</h2>';
|
||||
echo '<p><a class="button button-primary" href="' . esc_url( self::url( array( 'view' => 'new' ) ) ) . '">Add an alert</a></p>';
|
||||
if ( ! $defs ) {
|
||||
echo '<p>No custom alerts yet.</p></div>';
|
||||
return;
|
||||
}
|
||||
echo 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();
|
||||
foreach ( self::mediaParts( $d, $existing ) as [ $mLabel, $mMissing ] ) {
|
||||
$media[] = $mMissing ? '<span class="sga-missing">' . esc_html( $mLabel ) . '</span>' : esc_html( $mLabel );
|
||||
}
|
||||
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> ';
|
||||
Admin::form( 'sg_alert_delete', array( 'alert_id' => $id ), 'sg-inline sg-confirm' );
|
||||
echo '<button class="button button-link-delete" data-confirm="Delete this alert? Your media files stay in the Media Library.">Delete</button></form>';
|
||||
echo '</td></tr>';
|
||||
}
|
||||
echo Admin::tableClose() . '</div>';
|
||||
}
|
||||
|
||||
private static function mediaField( string $name, string $label, string $kind, int $id, string $help ): void {
|
||||
$url = '';
|
||||
$mime = '';
|
||||
if ( $id > 0 && null !== self::attachmentInfo( $id ) ) {
|
||||
$url = (string) wp_get_attachment_url( $id );
|
||||
$mime = (string) get_post_mime_type( $id );
|
||||
}
|
||||
echo '<tr><th scope="row">' . esc_html( $label ) . '</th><td>';
|
||||
echo '<div class="sga-media" data-kind="' . esc_attr( $kind ) . '">';
|
||||
echo '<input type="hidden" name="' . esc_attr( $name ) . '" value="' . ( $id > 0 ? (int) $id : 0 ) . '" data-url="' . esc_attr( $url ) . '" data-mime="' . esc_attr( $mime ) . '">';
|
||||
echo '<span class="sga-media-name">' . esc_html( '' !== $url ? wp_basename( $url ) : 'Nothing chosen' ) . '</span> ';
|
||||
echo '<button type="button" class="button sga-pick">Choose from Media Library</button> ';
|
||||
echo '<button type="button" class="button sga-clear">Remove</button>';
|
||||
echo '<p class="description sga-media-warn" role="status"></p>';
|
||||
echo '</div><p class="description">' . esc_html( $help ) . '</p></td></tr>';
|
||||
}
|
||||
|
||||
private static function renderForm( int $id ): void {
|
||||
$d = $id ? self::repo()->find( $id ) : null;
|
||||
if ( $id && ! $d ) {
|
||||
echo '<p>That alert no longer exists. <a href="' . esc_url( self::url() ) . '">Back to alerts</a></p>';
|
||||
return;
|
||||
}
|
||||
$cur = Admin::currency();
|
||||
$goals = self::goalTitles();
|
||||
$val = static fn( string $k, $default = '' ) => $d[ $k ] ?? $default;
|
||||
$trigger = (string) $val( 'trigger_type', 'amount' );
|
||||
$rewards = array();
|
||||
foreach ( ( new ActionRepository() )->all() as $a ) {
|
||||
if ( $a['enabled'] || (int) $a['id'] === (int) $val( 'action_id', 0 ) ) {
|
||||
$rewards[] = array( 'id' => $a['id'], 'title' => $a['title'], 'enabled' => (bool) $a['enabled'] );
|
||||
}
|
||||
}
|
||||
$data = array(
|
||||
'currency' => $cur,
|
||||
'exp' => Money::exponent( $cur ),
|
||||
'rewards' => $rewards,
|
||||
'videoCap' => Media::VIDEO_CAP_MS,
|
||||
'warnBytes' => Media::WARN_BYTES,
|
||||
'allowed' => Media::MIMES,
|
||||
);
|
||||
|
||||
echo '<h2>' . ( $d ? 'Edit alert' : 'Add an alert' ) . '</h2>';
|
||||
Admin::form( 'sg_alert_save', array( 'alert_id' => $id ), 'sga-form' );
|
||||
echo '<table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sga_title">Name</label></th><td><input type="text" required maxlength="120" id="sga_title" name="title" class="regular-text" value="' . esc_attr( (string) $val( 'title' ) ) . '"><p class="description">Only you see this, for example "Big donation fireworks".</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sga_goal">Applies to</label></th><td><select id="sga_goal" name="goal_id"><option value="0"' . selected( (int) $val( 'goal_id', 0 ), 0, false ) . '>All goals</option>';
|
||||
foreach ( $goals as $gid => $title ) {
|
||||
echo '<option value="' . (int) $gid . '"' . selected( (int) $val( 'goal_id', 0 ), $gid, false ) . '>' . esc_html( $title ) . '</option>';
|
||||
}
|
||||
echo '</select></td></tr>';
|
||||
echo '<tr><th scope="row">Plays when</th><td>';
|
||||
echo '<label><input type="radio" name="trigger_type" value="amount"' . checked( $trigger, 'amount', false ) . '> Any donation of at least <input type="text" inputmode="decimal" name="amount" class="small-text" value="' . esc_attr( $d && 'amount' === $trigger ? Format::decimal( (int) $d['min_minor'], $cur ) : '' ) . '"> ' . esc_html( $cur ) . '</label>';
|
||||
echo '<p class="description">At least ' . esc_html( Format::money( self::minMinor(), $cur ) ) . ' (your minimum donation). If several amount alerts match, the one with the highest amount wins.</p>';
|
||||
echo '<label><input type="radio" name="trigger_type" value="reward"' . checked( $trigger, 'reward', false ) . '> When a reward is triggered:</label> <select name="action_id"><option value="0">Choose a reward</option>';
|
||||
foreach ( $rewards as $r ) {
|
||||
echo '<option value="' . (int) $r['id'] . '"' . selected( (int) $val( 'action_id', 0 ), (int) $r['id'], false ) . '>' . esc_html( $r['title'] . ( $r['enabled'] ? '' : ' (turned off)' ) ) . '</option>';
|
||||
}
|
||||
echo '</select><p class="description">A reward alert beats an amount alert. Only rewards that are turned on can be picked.</p></td></tr>';
|
||||
self::mediaField( 'visual_id', 'Picture, GIF or video', 'visual', (int) $val( 'visual_id', 0 ), 'PNG, JPEG, GIF, WebP, MP4 or WebM. Optional. Under 25 MB works best; big videos can slow OBS down.' );
|
||||
self::mediaField( 'sound_id', 'Sound', 'sound', (int) $val( 'sound_id', 0 ), 'MP3, OGG or WAV. Optional. If you also pick a video, the video is muted and this sound plays instead.' );
|
||||
echo '<tr><th scope="row">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>';
|
||||
echo '<tr><th scope="row"><label for="sga_sort">Order</label></th><td><input type="number" min="0" max="99999" id="sga_sort" name="sort" class="small-text" value="' . ( $d ? (int) $d['sort'] : '' ) . '"><p class="description">Lower numbers win when two alerts are otherwise equal. Leave empty to put it last.</p></td></tr>';
|
||||
echo '</table>';
|
||||
|
||||
echo '<div class="sg-card"><h3>Preview</h3>';
|
||||
echo '<p class="description">This is how the alert will look on stream. Press the button to play it (browsers only allow sound after you click).</p>';
|
||||
echo '<p><button type="button" class="button" id="sga-play">Play preview</button> <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>';
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- handlers */
|
||||
|
||||
public static function handleSave(): void {
|
||||
Admin::guard( 'sg_alert_save' );
|
||||
$post = Admin::post_raw();
|
||||
$id = isset( $post['alert_id'] ) ? absint( $post['alert_id'] ) : 0;
|
||||
$back = self::url( $id ? array( 'edit' => $id ) : array( 'view' => 'new' ) );
|
||||
$repo = self::repo();
|
||||
if ( $id && ! $repo->find( $id ) ) {
|
||||
Admin::redirect( self::url(), 'error', 'That alert no longer exists.' );
|
||||
}
|
||||
$enabled = array();
|
||||
foreach ( ( new ActionRepository() )->all() as $a ) {
|
||||
if ( $a['enabled'] ) {
|
||||
$enabled[] = (int) $a['id'];
|
||||
}
|
||||
}
|
||||
$res = DefInput::validate( $post, self::minMinor(), Admin::currency(), array_keys( self::goalTitles() ), $enabled, array( self::class, 'attachmentInfo' ), $repo->nextSort() );
|
||||
if ( null === $res['data'] ) {
|
||||
Admin::redirect( $back, 'error', (string) $res['error'] );
|
||||
}
|
||||
if ( $id ) {
|
||||
$repo->update( $id, $res['data'] );
|
||||
} else {
|
||||
$repo->create( $res['data'] );
|
||||
}
|
||||
$msg = 'Alert saved.' . ( $res['warnings'] ? ' Heads up: ' . implode( ' ', $res['warnings'] ) : '' );
|
||||
Admin::redirect( self::url(), $res['warnings'] ? 'warning' : 'success', $msg );
|
||||
}
|
||||
|
||||
public static function handleToggle(): void {
|
||||
Admin::guard( 'sg_alert_toggle' );
|
||||
$post = Admin::post_raw();
|
||||
self::repo()->setEnabled( isset( $post['alert_id'] ) ? absint( $post['alert_id'] ) : 0, ! empty( $post['enabled'] ) );
|
||||
Admin::redirect( self::url(), 'success', 'Alert updated.' );
|
||||
}
|
||||
|
||||
public static function handleDelete(): void {
|
||||
Admin::guard( 'sg_alert_delete' );
|
||||
$post = Admin::post_raw();
|
||||
self::repo()->delete( isset( $post['alert_id'] ) ? absint( $post['alert_id'] ) : 0 );
|
||||
Admin::redirect( self::url(), 'success', 'Alert deleted.' );
|
||||
}
|
||||
}
|
||||
@@ -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'] ) . '">' . esc_html( strtolower( Format::flaggedLabel( $r ) ) . ' ' . (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(
|
||||
@@ -72,39 +72,45 @@ final class DonationsPage {
|
||||
}
|
||||
|
||||
public static function renderModeration(): void {
|
||||
Admin::open( 'Message moderation' );
|
||||
Admin::open( 'Moderation' );
|
||||
if ( ! Settings::get( 'moderate_messages' ) ) {
|
||||
echo '<div class="notice notice-info inline"><p>Message moderation is currently off in Settings, so new messages are shown without review. Anything still waiting below was submitted while it was on.</p></div>';
|
||||
echo '<div class="notice notice-info inline"><p>Message moderation is currently off in Settings, so new messages are shown without review. A donor name that trips the profanity filter is still held here, and anything else waiting below was submitted earlier.</p></div>';
|
||||
}
|
||||
echo '<p class="description">Approved messages can appear in alerts. Rejected messages are hidden. The donation itself still counts towards your goal either way.</p>';
|
||||
echo '<p class="description">Held donations stay out of alerts (and the public donor feed) until you approve them. Rejected ones are never shown. A donor name that trips the profanity filter is held here too; it is already masked (for example f***), and approving shows it masked. The donation itself still counts towards your goal, timer and counters either way.</p>';
|
||||
$res = Store::searchDonations( array( 'status' => 'completed', 'moderation' => 'pending' ), 1, 100 );
|
||||
if ( ! $res['rows'] ) {
|
||||
echo '<div class="sg-card"><p>Nothing waiting for review.</p></div>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Date</th><th>Donor</th><th>Amount</th><th>Message</th><th>Decision</th></tr></thead><tbody>';
|
||||
echo Admin::tableOpen( array( 'Date', 'Donor', 'Amount', 'Message', 'Flagged', 'Decision' ), 'Donations 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( 'Flagged' ) . esc_html( Format::flaggedLabel( $r ) ) . '</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();
|
||||
}
|
||||
|
||||
/** Moderation submenu exists only when moderation is on or items are pending (see Admin::menu); otherwise land on Donations. */
|
||||
public static function afterModerationPage( bool $moderationOn, int $pending ): string {
|
||||
return ( $moderationOn || $pending > 0 ) ? 'streamgoals-moderation' : 'streamgoals-donations';
|
||||
}
|
||||
|
||||
public static function handleModerate(): void {
|
||||
Admin::guard( 'sg_moderate' );
|
||||
$post = Admin::post_raw();
|
||||
$id = isset( $post['donation_id'] ) ? absint( $post['donation_id'] ) : 0;
|
||||
$to = isset( $post['decision'] ) && is_string( $post['decision'] ) ? $post['decision'] : '';
|
||||
$ok = $id && Store::setModeration( $id, $to );
|
||||
Admin::redirect( Admin::url( 'streamgoals-moderation' ), $ok ? 'success' : 'error', $ok ? ( 'approved' === $to ? 'Message approved.' : 'Message rejected.' ) : 'That message could not be updated (it may already be reviewed).' );
|
||||
$page = self::afterModerationPage( (bool) Settings::get( 'moderate_messages' ), Store::pendingModerationCount() );
|
||||
Admin::redirect( Admin::url( $page ), $ok ? 'success' : 'error', $ok ? ( 'approved' === $to ? 'Donation approved.' : 'Donation rejected.' ) : 'That donation could not be updated (it may already be reviewed).' );
|
||||
}
|
||||
|
||||
public static function handleExport(): void {
|
||||
|
||||
@@ -61,4 +61,15 @@ final class Format {
|
||||
}
|
||||
return (string) $row['donor_name'];
|
||||
}
|
||||
|
||||
/**
|
||||
* What is being held for review, from sg_donations.moderation_flags: 'Name', 'Message' or 'Name and message'.
|
||||
* Rows held before flags existed (empty value) were always held for their message.
|
||||
*/
|
||||
public static function flaggedLabel( array $row ): string {
|
||||
$flags = array_filter( array_map( 'trim', explode( ',', (string) ( $row['moderation_flags'] ?? '' ) ) ) );
|
||||
$name = in_array( 'name', $flags, true );
|
||||
$msg = in_array( 'message', $flags, true ) || ! $name;
|
||||
return $name && $msg ? 'Name and message' : ( $name ? 'Name' : 'Message' );
|
||||
}
|
||||
}
|
||||
+151
-13
@@ -4,6 +4,9 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Admin;
|
||||
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Tiers\TierPolicy;
|
||||
use StreamGoals\Tiers\TierRepository;
|
||||
|
||||
/** Goals list/create/edit/status/delete, plus the per-goal rules editor. */
|
||||
final class GoalsPage {
|
||||
@@ -17,6 +20,8 @@ final class GoalsPage {
|
||||
self::renderForm( 'edit' === $view ? $id : 0 );
|
||||
} elseif ( 'rules' === $view && $id ) {
|
||||
self::renderRules( $id );
|
||||
} elseif ( 'tiers' === $view && $id ) {
|
||||
self::renderTiers( $id );
|
||||
} else {
|
||||
self::renderList();
|
||||
}
|
||||
@@ -29,24 +34,27 @@ final class GoalsPage {
|
||||
echo '<p><a class="page-title-action" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'new' ) ) ) . '">Add new goal</a></p>';
|
||||
echo '<p class="description">Overlays and the donation form use your newest <strong>active</strong> goal(s). Pause a goal to stop accepting donations; mark it complete when you are done. A goal that has donations cannot be deleted (complete it instead), so your records stay intact.</p>';
|
||||
$goals = Store::goals()->all();
|
||||
$tierCounts = $goals ? ( new TierRepository() )->countsByGoal() : array();
|
||||
if ( ! $goals ) {
|
||||
echo '<div class="sg-card"><p>No goals yet. <a href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'new' ) ) ) . '">Create your first goal</a> or run the <a href="' . esc_url( SetupPage::url( 2 ) ) . '">setup guide</a>.</p></div>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
echo '<table class="widefat striped sg-table"><thead><tr><th>Goal</th><th>Status</th><th>Raised</th><th>Dates</th><th>Actions</th></tr></thead><tbody>';
|
||||
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 . ' · <code>[streamgoals_donate goal="' . $gid . '"]</code></span></td>';
|
||||
echo '<td><span class="sg-badge sg-' . esc_attr( (string) $g['status'] ) . '">' . esc_html( self::STATUSES[ $g['status'] ] ?? (string) $g['status'] ) . '</span></td>';
|
||||
echo '<td>' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)<div class="sg-bar"><span style="width:' . (int) $pct . '%"></span></div></td>';
|
||||
echo '<td>' . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '<br>' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '</td><td class="sg-actions">';
|
||||
echo '<tr>' . Admin::td( 'Goal' ) . '<strong>' . esc_html( (string) $g['title'] ) . '</strong><br><span class="description">ID ' . $gid . ' · <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;
|
||||
echo '<a class="button" href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'tiers', 'goal' => $gid ) ) ) . '">Tiers' . ( $nt > 0 ? ' (' . (int) $nt . ')' : '' ) . '</a> ';
|
||||
foreach ( array( 'active' => array( 'paused', 'Pause' ), 'paused' => array( 'active', 'Resume' ), 'complete' => array( 'active', 'Reopen' ) ) as $from => [ $to, $lbl ] ) {
|
||||
if ( $g['status'] === $from ) {
|
||||
Admin::form( 'sg_goal_status', array( 'goal_id' => $gid, 'status' => $to ), 'sg-inline' );
|
||||
@@ -61,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();
|
||||
}
|
||||
|
||||
@@ -80,16 +88,22 @@ final class GoalsPage {
|
||||
return;
|
||||
}
|
||||
$cur = $g ? Format::currency( $g['currency'] ) : Admin::currency();
|
||||
$tiered = $id && (bool) ( new TierRepository() )->forGoal( $id );
|
||||
Admin::open( $g ? 'Edit goal' : 'New goal' );
|
||||
Admin::form( 'sg_goal_save', array( 'goal_id' => $id ) );
|
||||
echo '<table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sg_title">Title</label></th><td><input type="text" required maxlength="190" id="sg_title" name="title" class="regular-text" value="' . esc_attr( (string) ( $g['title'] ?? '' ) ) . '"></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" required inputmode="decimal" id="sg_target" name="target" class="small-text" value="' . esc_attr( $g ? Format::decimal( (int) $g['target_minor'], $cur ) : '' ) . '"></td></tr>';
|
||||
if ( $tiered ) {
|
||||
echo '<tr><th scope="row">Target (' . esc_html( $cur ) . ')</th><td><strong>' . esc_html( Format::money( (int) $g['target_minor'], $cur ) ) . '</strong> <span class="description">Set automatically from your highest tier. To change it, <a href="' . esc_url( Admin::url( Admin::HOME, array( 'view' => 'tiers', 'goal' => $id ) ) ) . '">edit the tiers</a>.</span></td></tr>';
|
||||
} else {
|
||||
echo '<tr><th scope="row"><label for="sg_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" required inputmode="decimal" id="sg_target" name="target" class="small-text" value="' . esc_attr( $g ? Format::decimal( (int) $g['target_minor'], $cur ) : '' ) . '"></td></tr>';
|
||||
}
|
||||
echo '<tr><th scope="row">Currency</th><td><strong>' . esc_html( $cur ) . '</strong> <span class="description">One currency is used across the whole site. Change it in <a href="' . esc_url( Admin::url( 'streamgoals-settings' ) ) . '">Settings</a> (applies to new goals only).</span></td></tr>';
|
||||
$fmt = static fn( ?string $utc ): string => $utc ? get_date_from_gmt( $utc, 'Y-m-d\TH:i' ) : '';
|
||||
echo '<tr><th scope="row"><label for="sg_start">Starts</label></th><td><input type="datetime-local" id="sg_start" name="starts_at" value="' . esc_attr( $fmt( $g['starts_at'] ?? null ) ) . '"> <span class="description">Optional. Your site time zone. Empty = starts immediately.</span></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_end">Ends</label></th><td><input type="datetime-local" id="sg_end" name="ends_at" value="' . esc_attr( $fmt( $g['ends_at'] ?? null ) ) . '"> <span class="description">Optional. Donations stop after this time.</span></td></tr>';
|
||||
echo '<tr><th scope="row">Fees</th><td><label><input type="checkbox" name="counts_fees" value="1"' . checked( ! empty( $g['counts_fees'] ), true, false ) . '> Count fees covered by donors towards the goal</label><p class="description">Off (recommended): only the amount the donor chose counts, so a $10 donation always adds $10 even if they also covered the fee.</p></td></tr>';
|
||||
echo '<tr><th scope="row">End at target</th><td><label><input type="checkbox" name="close_at_target" value="1"' . checked( ! empty( $g['close_at_target'] ), true, false ) . '> Close this goal to donations when the target is reached</label><p class="description">When the raised total reaches or goes over the target, the goal is marked complete and the donation page stops taking donations to it. Donations already in checkout still complete. You can reopen it with "Reopen" (raise the target first if you want more donations: a reopened goal that is still at or over its target closes again after the next donation).</p></td></tr>';
|
||||
echo '</table><p><button class="button button-primary">' . ( $g ? 'Save goal' : 'Create goal' ) . '</button> <a class="button" href="' . esc_url( Admin::url() ) . '">Cancel</a></p></form>';
|
||||
Admin::close();
|
||||
}
|
||||
@@ -115,10 +129,12 @@ final class GoalsPage {
|
||||
$cur = $old ? Format::currency( $old['currency'] ) : Admin::currency();
|
||||
$title = Input::text( $post['title'] ?? '', 190 );
|
||||
$tgt = Input::amountToMinor( $post['target'] ?? '', $cur );
|
||||
// A goal with tiers has a derived target (its highest tier): never taken from the form.
|
||||
$tiered = $id && ( new TierRepository() )->forGoal( $id );
|
||||
if ( '' === $title ) {
|
||||
Admin::redirect( $back, 'error', 'Please give the goal a title.' );
|
||||
}
|
||||
if ( null === $tgt || $tgt <= 0 ) {
|
||||
if ( ! $tiered && ( null === $tgt || $tgt <= 0 ) ) {
|
||||
Admin::redirect( $back, 'error', 'Please enter a target greater than zero, for example 250.00.' );
|
||||
}
|
||||
$startRaw = Input::text( $post['starts_at'] ?? '', 20 );
|
||||
@@ -131,7 +147,10 @@ final class GoalsPage {
|
||||
if ( $start && $end && strtotime( $end . ' UTC' ) <= strtotime( $start . ' UTC' ) ) {
|
||||
Admin::redirect( $back, 'error', 'The end must be after the start.' );
|
||||
}
|
||||
$data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1 );
|
||||
$data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1, 'close_at_target' => \StreamGoals\Core\GoalTargetPolicy::flagFromPost( $post['close_at_target'] ?? null ) );
|
||||
if ( $tiered ) {
|
||||
unset( $data['target_minor'] );
|
||||
}
|
||||
if ( $id ) {
|
||||
Store::goals()->update( $id, $data );
|
||||
} else {
|
||||
@@ -170,6 +189,125 @@ final class GoalsPage {
|
||||
Admin::redirect( Admin::url(), 'success', 'Goal deleted.' );
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- tiers */
|
||||
|
||||
private static function tiersUrl( int $goalId, array $extra = array() ): string {
|
||||
return Admin::url( Admin::HOME, array_merge( array( 'view' => 'tiers', 'goal' => $goalId ), $extra ) );
|
||||
}
|
||||
|
||||
private static function renderTiers( int $goalId ): void {
|
||||
$g = Store::goals()->find( $goalId );
|
||||
if ( ! $g ) {
|
||||
Admin::open( 'Goal not found' );
|
||||
echo '<p><a href="' . esc_url( Admin::url() ) . '">Back to goals</a></p>';
|
||||
Admin::close();
|
||||
return;
|
||||
}
|
||||
$cur = Format::currency( $g['currency'] );
|
||||
$repo = new TierRepository();
|
||||
$tiers = $repo->forGoal( $goalId );
|
||||
$raised = Store::goals()->raised_minor( $goalId );
|
||||
Admin::open( 'Tiers for "' . (string) $g['title'] . '"' );
|
||||
echo '<p><a href="' . esc_url( Admin::url() ) . '">← Back to goals</a></p>';
|
||||
echo '<p class="sg-lead">Tiers turn one goal into a ladder of milestones. Each tier has a target and something you unlock or give away. When your total reaches a tier\'s target, that tier unlocks and the goal bar moves on to the next one. The goal\'s final target is your highest tier.</p>';
|
||||
|
||||
echo '<div class="sg-card"><h2>Your tiers</h2>';
|
||||
echo '<p class="description">Raised so far: <strong>' . esc_html( Format::money( $raised, $cur ) ) . '</strong>. Targets are cumulative totals, not extra amounts: a tier at ' . esc_html( Format::money( 25000, $cur ) ) . ' unlocks when the goal total reaches ' . esc_html( Format::money( 25000, $cur ) ) . '.</p>';
|
||||
if ( ! $tiers ) {
|
||||
echo '<p>No tiers yet. This goal works as a single target until you add one.</p>';
|
||||
} else {
|
||||
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>' . 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>' . 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 Admin::tableClose();
|
||||
}
|
||||
echo '</div>';
|
||||
|
||||
$editId = Admin::get_int( 'tier' );
|
||||
$edit = $editId ? $repo->find( $editId ) : null;
|
||||
if ( $edit && (int) $edit['goal_id'] !== $goalId ) {
|
||||
$edit = null;
|
||||
}
|
||||
$locked = $edit && TierPolicy::isReached( $edit );
|
||||
$min = Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
|
||||
echo '<div class="sg-card" id="sg-tier-form"><h2>' . ( $edit ? 'Edit tier' : 'Add a tier' ) . '</h2>';
|
||||
Admin::form( 'sg_tier_save', array( 'goal_id' => $goalId, 'tier_id' => $edit ? (int) $edit['id'] : 0 ) );
|
||||
echo '<table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row"><label for="sg_t_target">Target (' . esc_html( $cur ) . ')</label></th><td><input type="text" ' . ( $locked ? 'disabled' : 'required' ) . ' inputmode="decimal" id="sg_t_target" name="target" class="small-text" value="' . esc_attr( $edit ? Format::decimal( (int) $edit['target_minor'], $cur ) : '' ) . '">';
|
||||
echo '<p class="description">' . ( $locked ? 'This tier has been reached, so its target is locked. You can still change its name and description.' : 'When your total reaches this amount, this tier unlocks and the goal bar moves on to the next one. Must be above what has been raised so far (' . esc_html( Format::money( $raised, $cur ) ) . ') and at least ' . esc_html( Format::money( $min, $cur ) ) . '.' ) . '</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_t_title">Item or unlock</label></th><td><input type="text" required maxlength="120" id="sg_t_title" name="title" class="regular-text" value="' . esc_attr( $edit ? (string) $edit['title'] : '' ) . '"><p class="description">What viewers get when this tier is reached, for example "New microphone". Up to 120 characters. Shown on your overlay and the donation form.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_t_desc">Description</label></th><td><input type="text" maxlength="255" id="sg_t_desc" name="description" class="large-text" value="' . esc_attr( $edit ? (string) $edit['description'] : '' ) . '"><p class="description">Optional. A short note, up to 255 characters.</p></td></tr>';
|
||||
echo '</table><p><button class="button button-primary">' . ( $edit ? 'Save tier' : 'Add tier' ) . '</button>';
|
||||
if ( $edit ) {
|
||||
echo ' <a class="button" href="' . esc_url( self::tiersUrl( $goalId ) ) . '">Cancel</a>';
|
||||
}
|
||||
echo '</p></form></div>';
|
||||
Admin::close();
|
||||
}
|
||||
|
||||
public static function handleTierSave(): void {
|
||||
Admin::guard( 'sg_tier_save' );
|
||||
$post = Admin::post_raw();
|
||||
$goalId = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
|
||||
$tierId = isset( $post['tier_id'] ) ? absint( $post['tier_id'] ) : 0;
|
||||
$g = $goalId ? Store::goals()->find( $goalId ) : null;
|
||||
if ( ! $g ) {
|
||||
Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' );
|
||||
}
|
||||
$back = self::tiersUrl( $goalId, $tierId ? array( 'tier' => $tierId ) : array() );
|
||||
$cur = Format::currency( $g['currency'] );
|
||||
$repo = new TierRepository();
|
||||
$min = Settings::effectiveMin( (int) Settings::get( 'min_donation_minor', 0 ) );
|
||||
$res = TierPolicy::validate(
|
||||
$repo->forGoal( $goalId ),
|
||||
$tierId ?: null,
|
||||
Input::amountToMinor( $post['target'] ?? '', $cur ),
|
||||
Input::text( $post['title'] ?? '', 200 ),
|
||||
Input::text( $post['description'] ?? '', 400 ),
|
||||
Store::goals()->raised_minor( $goalId ),
|
||||
$min,
|
||||
Format::money( $min, $cur )
|
||||
);
|
||||
if ( null === $res['data'] ) {
|
||||
Admin::redirect( $back, 'error', (string) $res['error'] );
|
||||
}
|
||||
if ( $tierId ) {
|
||||
$repo->update( $tierId, $goalId, $res['data'] );
|
||||
} elseif ( $repo->create( $goalId, $res['data'] ) <= 0 ) {
|
||||
Admin::redirect( $back, 'error', 'The tier could not be saved. Another tier may already have that target.' );
|
||||
}
|
||||
$repo->syncGoalTarget( $goalId );
|
||||
$msg = 'Tier saved. The goal target is now ' . Format::money( TierPolicy::derivedGoalTarget( $repo->forGoal( $goalId ) ), $cur ) . '.';
|
||||
if ( 'complete' === ( $g['status'] ?? '' ) ) {
|
||||
$msg .= ' This goal is marked complete; use "Reopen" on the goals list if you want donations to continue.';
|
||||
}
|
||||
Admin::redirect( self::tiersUrl( $goalId ), 'success', $msg );
|
||||
}
|
||||
|
||||
public static function handleTierDelete(): void {
|
||||
Admin::guard( 'sg_tier_delete' );
|
||||
$post = Admin::post_raw();
|
||||
$goalId = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0;
|
||||
if ( $goalId && Store::goals()->find( $goalId ) ) {
|
||||
$repo = new TierRepository();
|
||||
$repo->delete( isset( $post['tier_id'] ) ? absint( $post['tier_id'] ) : 0, $goalId );
|
||||
$repo->syncGoalTarget( $goalId ); // no-op when the last tier was removed: the goal keeps its current target (editable again)
|
||||
}
|
||||
Admin::redirect( self::tiersUrl( $goalId ), 'success', 'Tier deleted.' );
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- rules */
|
||||
|
||||
private static function renderRules( int $goalId ): void {
|
||||
@@ -193,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>';
|
||||
|
||||
|
||||
@@ -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 ) ) ) );
|
||||
|
||||
@@ -34,6 +34,7 @@ final class SettingsPage {
|
||||
}
|
||||
echo '</select><p class="description">One currency for the whole site. It applies to goals you create from now on; existing goals keep their currency. Check the fixed fee below after changing it.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_min">Minimum donation (' . esc_html( $cur ) . ')</label></th><td><input type="text" id="sg_min" name="min_donation" class="small-text" inputmode="decimal" value="' . esc_attr( Format::decimal( \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ), $cur ) ) . '"> <span class="description">At least ' . esc_html( Format::money( \StreamGoals\Core\Settings::HARD_MIN_MINOR, $cur ) ) . '. Visitors cannot donate less than this.</span></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_notice">Notice under the donation form</label></th><td><input type="text" id="sg_notice" name="donation_notice" class="large-text" maxlength="200" value="' . esc_attr( (string) $s['donation_notice'] ) . '"><p class="description">Shown right under the PayPal buttons so donors see it before paying. Plain text, up to 200 characters. The default says donations are non-refundable. Leave it empty to hide the notice.</p></td></tr>';
|
||||
echo '<tr><th scope="row"><label for="sg_len">Longest message</label></th><td><input type="number" id="sg_len" name="message_max_length" min="0" max="500" class="small-text" value="' . (int) $s['message_max_length'] . '"> characters <span class="description">(0 to 500; 0 = no messages)</span></td></tr>';
|
||||
echo '<tr><th scope="row">Names</th><td><fieldset>';
|
||||
foreach ( self::POLICIES as $k => $l ) {
|
||||
@@ -43,7 +44,7 @@ final class SettingsPage {
|
||||
|
||||
echo '<div class="sg-card"><h2>Messages</h2><table class="form-table" role="presentation">';
|
||||
echo '<tr><th scope="row">Moderation</th><td><label><input type="checkbox" name="moderate_messages" value="1"' . checked( ! empty( $s['moderate_messages'] ), true, false ) . '> Hold messages for my approval before they can be shown in alerts</label></td></tr>';
|
||||
echo '<tr><th scope="row">Profanity filter</th><td><label><input type="checkbox" name="profanity_filter" value="1"' . checked( ! empty( $s['profanity_filter'] ), true, false ) . '> Filter bad language in messages and names</label><br>';
|
||||
echo '<tr><th scope="row">Profanity filter</th><td><label><input type="checkbox" name="profanity_filter" value="1"' . checked( ! empty( $s['profanity_filter'] ), true, false ) . '> Mask bad language in messages and donor names</label> <span class="description">A donor name that trips the filter is masked and the donation is held on the Moderation screen before its alert can show (it still counts towards your goal).</span><br>';
|
||||
echo '<label><input type="checkbox" name="profanity_use_builtin" value="1"' . checked( ! empty( $s['profanity_use_builtin'] ), true, false ) . '> Use the built-in word list</label>';
|
||||
echo '<p><label for="sg_words">Your own words to block (one per line)</label><br><textarea id="sg_words" name="profanity_words" rows="6" class="large-text code">' . esc_textarea( (string) $s['profanity_words'] ) . '</textarea></p></td></tr></table></div>';
|
||||
|
||||
@@ -56,9 +57,11 @@ final class SettingsPage {
|
||||
foreach ( \StreamGoals\Core\ClientIp::MODES as $k => $l ) {
|
||||
echo '<option value="' . esc_attr( $k ) . '"' . selected( (string) $s['visitor_ip_header'], $k, false ) . '>' . esc_html( $l ) . '</option>';
|
||||
}
|
||||
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). If your site is behind Cloudflare or another proxy, choose it here so each visitor is counted separately; otherwise everyone looks like the same visitor and a busy moment, like a raid, could block donations. Only choose a proxy option if <em>all</em> traffic to your site really goes through it.</p>';
|
||||
echo '</select><p class="description">Donation forms limit how fast one visitor can start payments (to stop abuse). Behind a proxy, every visitor can look like the same address, and a busy moment, like a raid, could block donations. <strong>Automatic</strong> recognises Cloudflare by its published addresses and counts each visitor separately; it ignores forged headers from anywhere else. For another kind of proxy, choose its option here, but only if <em>all</em> traffic to your site really goes through it.</p>';
|
||||
self::ipDiagnostics( (string) $s['visitor_ip_header'] );
|
||||
echo '</td></tr></table></div>';
|
||||
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">';
|
||||
@@ -80,7 +83,7 @@ final class SettingsPage {
|
||||
|
||||
/** Shows the owner what their server passes to the plugin right now, to help pick the right option. */
|
||||
private static function ipDiagnostics( string $mode ): void {
|
||||
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
|
||||
$keys = array( 'REMOTE_ADDR' => 'Connection address', 'HTTP_CF_CONNECTING_IP' => 'CF-Connecting-IP', 'HTTP_CF_RAY' => 'CF-Ray', 'HTTP_X_REAL_IP' => 'X-Real-IP', 'HTTP_X_FORWARDED_FOR' => 'X-Forwarded-For' );
|
||||
$server = array();
|
||||
foreach ( $keys as $k => $_ ) {
|
||||
if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) {
|
||||
@@ -91,8 +94,10 @@ final class SettingsPage {
|
||||
foreach ( $keys as $k => $label ) {
|
||||
echo '<tr><td>' . esc_html( $label ) . '</td><td><code>' . ( isset( $server[ $k ] ) ? esc_html( $server[ $k ] ) : '(not sent)' ) . '</code></td></tr>';
|
||||
}
|
||||
$viaCf = isset( $server['REMOTE_ADDR'] ) && \StreamGoals\Core\CloudflareRanges::isCloudflare( $server['REMOTE_ADDR'], (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
|
||||
echo '<tr><td>Is this connection from Cloudflare?</td><td>' . ( $viaCf ? '<strong>Yes</strong> - the connection comes from a Cloudflare address' : 'No' ) . '</td></tr>';
|
||||
echo '<tr><td><strong>Visitor address used with the saved option</strong></td><td><code>' . esc_html( \StreamGoals\Core\ClientIp::resolve( $server, $mode ) ) . '</code></td></tr>';
|
||||
echo '</tbody></table><p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
|
||||
echo '</tbody></table>' . ( ! $viaCf && ( isset( $server['HTTP_CF_RAY'] ) || isset( $server['HTTP_CF_CONNECTING_IP'] ) ) ? '<p class="sg-warn">Cloudflare headers were sent, but the connection is not from a known Cloudflare address, so "Automatic" ignores them. If your site really is behind Cloudflare, choose "Cloudflare" above (or update the plugin, as Cloudflare may have added new addresses).</p>' : '' ) . '<p class="description">This is your own visit. If the connection address belongs to your proxy or CDN (not to you) and your proxy\'s header shows your real address, choose that proxy option above and save. Then the "used" row should show your real address.</p></details>';
|
||||
}
|
||||
|
||||
public static function handleSave(): void {
|
||||
@@ -145,6 +150,8 @@ 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'] );
|
||||
$upd['profanity_use_builtin'] = ! empty( $post['profanity_use_builtin'] );
|
||||
|
||||
@@ -87,6 +87,7 @@ final class Store {
|
||||
self::deleteRule( (int) $r['id'], $goalId );
|
||||
}
|
||||
$wpdb->delete( self::t( 'state' ), array( 'goal_id' => $goalId ), array( '%d' ) );
|
||||
$wpdb->delete( self::t( 'goal_tiers' ), array( 'goal_id' => $goalId ), array( '%d' ) );
|
||||
return self::goals()->delete( $goalId );
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/**
|
||||
* Builds the public `media` block for one alert. URLs only ever come from the $attachment callback
|
||||
* (WordPress attachment lookup); the DB row contributes ids, never URLs.
|
||||
*/
|
||||
final class AlertMedia {
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $row Donation row (goal_id, base_minor).
|
||||
* @param array<int,array<string,mixed>> $defs Raw alert definitions.
|
||||
* @param array<int,array{action_id:int,amount_minor:int,title:string}> $triggered Rewards this donation triggered.
|
||||
* @param callable(int):?array{url:string,mime:string,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 ) {
|
||||
return null;
|
||||
}
|
||||
$ids = array();
|
||||
$amounts = array();
|
||||
foreach ( $triggered as $t ) {
|
||||
$aid = (int) ( $t['action_id'] ?? 0 );
|
||||
$ids[] = $aid;
|
||||
$amounts[ $aid ] = (int) ( $t['amount_minor'] ?? 0 );
|
||||
}
|
||||
$def = Resolver::pick( (int) ( $row['goal_id'] ?? 0 ), (int) ( $row['base_minor'] ?? 0 ), $ids, $defs, $amounts );
|
||||
if ( null === $def ) {
|
||||
return null;
|
||||
}
|
||||
return self::fromDef( $def, $name, $amountDisplay, $triggered, $attachment );
|
||||
}
|
||||
|
||||
/** @return array<string,mixed>|null */
|
||||
public static function fromDef( array $def, string $name, string $amountDisplay, array $triggered, callable $attachment ): ?array {
|
||||
$visual = null;
|
||||
$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;
|
||||
$sid = (int) ( $def['sound_id'] ?? 0 );
|
||||
if ( $sid > 0 ) {
|
||||
$a = self::lookup( $attachment, $sid );
|
||||
if ( $a && Media::isSound( $a['mime'] ) ) {
|
||||
$sound = array( 'url' => $a['url'] );
|
||||
}
|
||||
}
|
||||
$reward = '';
|
||||
$best = -1;
|
||||
foreach ( $triggered as $t ) {
|
||||
$amt = (int) ( $t['amount_minor'] ?? 0 );
|
||||
if ( 'reward' === ( $def['trigger_type'] ?? '' ) ) {
|
||||
if ( (int) ( $t['action_id'] ?? 0 ) === (int) $def['action_id'] ) {
|
||||
$reward = (string) ( $t['title'] ?? '' );
|
||||
break;
|
||||
}
|
||||
} elseif ( $amt > $best ) {
|
||||
$best = $amt;
|
||||
$reward = (string) ( $t['title'] ?? '' );
|
||||
}
|
||||
}
|
||||
$msg = Template::render( (string) ( $def['message'] ?? '' ), $name, $amountDisplay, $reward );
|
||||
if ( null === $visual && null === $sound && '' === $msg ) {
|
||||
return null; // nothing usable left: behave exactly as a plain alert
|
||||
}
|
||||
$duration = Media::clampDurationMs( $def['duration_ms'] ?? Media::DEFAULT_MS );
|
||||
if ( $visual && 'video' === $visual['type'] ) {
|
||||
$duration = Media::VIDEO_CAP_MS;
|
||||
}
|
||||
return array(
|
||||
'visual' => $visual,
|
||||
'sound' => $sound,
|
||||
'volume' => Media::clampVolume( $def['volume'] ?? 80 ),
|
||||
'duration_ms' => $duration,
|
||||
'message' => '' === $msg ? null : $msg,
|
||||
'frameless' => $frameless,
|
||||
);
|
||||
}
|
||||
|
||||
/** @return array{url:string,mime:string}|null */
|
||||
private static function lookup( callable $attachment, int $id ): ?array {
|
||||
try {
|
||||
$a = $attachment( $id );
|
||||
} catch ( \Throwable ) {
|
||||
return null;
|
||||
}
|
||||
if ( ! is_array( $a ) || ! Media::isAllowed( $a['mime'] ?? null ) ) {
|
||||
return null;
|
||||
}
|
||||
$url = Media::safeUrl( $a['url'] ?? null );
|
||||
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'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
use StreamGoals\Admin\Input;
|
||||
|
||||
/** Pure validation/sanitizing for the alert definition form. */
|
||||
final class DefInput {
|
||||
|
||||
/**
|
||||
* @param int[] $validGoalIds Existing goal ids (0 = all goals always allowed).
|
||||
* @param int[] $enabledActionIds Enabled rewards that may be chosen as a trigger.
|
||||
* @param callable(int):?array{mime:string,size?:int} $attachment Lookup of an attachment by id (null = missing).
|
||||
* @return array{data:?array,error:?string,warnings:string[]}
|
||||
*/
|
||||
public static function validate( array $post, int $minMinor, string $currency, array $validGoalIds, array $enabledActionIds, callable $attachment, int $defaultSort = 0 ): array {
|
||||
$fail = static fn( string $m ): array => array( 'data' => null, 'error' => $m, 'warnings' => array() );
|
||||
|
||||
$title = Input::text( $post['title'] ?? '', 200 );
|
||||
if ( '' === $title ) {
|
||||
return $fail( 'Please give this alert a name, for example "Big donation fireworks".' );
|
||||
}
|
||||
if ( mb_strlen( $title ) > 120 ) {
|
||||
return $fail( 'The name can be at most 120 characters.' );
|
||||
}
|
||||
$goal = Input::int( $post['goal_id'] ?? '0', 0, PHP_INT_MAX >> 1 );
|
||||
if ( null === $goal || ( 0 !== $goal && ! in_array( $goal, array_map( 'intval', $validGoalIds ), true ) ) ) {
|
||||
return $fail( 'Please choose all goals or one of your goals.' );
|
||||
}
|
||||
$trigger = is_scalar( $post['trigger_type'] ?? null ) ? (string) $post['trigger_type'] : '';
|
||||
$min = 0;
|
||||
$action = 0;
|
||||
if ( 'amount' === $trigger ) {
|
||||
$min = Input::amountToMinor( $post['amount'] ?? '', $currency );
|
||||
if ( null === $min || $min <= 0 ) {
|
||||
return $fail( 'Please enter the smallest donation that should trigger this alert, for example 10.00.' );
|
||||
}
|
||||
if ( $min < $minMinor ) {
|
||||
return $fail( 'The amount must be at least the minimum donation (' . \StreamGoals\Admin\Format::money( $minMinor, $currency ) . ').' );
|
||||
}
|
||||
} elseif ( 'reward' === $trigger ) {
|
||||
$action = Input::int( $post['action_id'] ?? '', 1, PHP_INT_MAX >> 1 );
|
||||
if ( null === $action || ! in_array( $action, array_map( 'intval', $enabledActionIds ), true ) ) {
|
||||
return $fail( 'Please choose one of your turned-on rewards.' );
|
||||
}
|
||||
} else {
|
||||
return $fail( 'Please choose when this alert plays.' );
|
||||
}
|
||||
|
||||
$warnings = array();
|
||||
$visualId = 0;
|
||||
$visual = '';
|
||||
$sound = 0;
|
||||
$vRaw = Input::int( $post['visual_id'] ?? '0', 0, PHP_INT_MAX >> 1 );
|
||||
$sRaw = Input::int( $post['sound_id'] ?? '0', 0, PHP_INT_MAX >> 1 );
|
||||
if ( null === $vRaw || null === $sRaw ) {
|
||||
return $fail( 'The chosen media file is not valid. Please pick it again.' );
|
||||
}
|
||||
if ( $vRaw > 0 ) {
|
||||
$a = $attachment( $vRaw );
|
||||
if ( ! is_array( $a ) ) {
|
||||
return $fail( 'The picture or video you chose no longer exists in your Media Library. Please pick it again.' );
|
||||
}
|
||||
$type = Media::visualType( $a['mime'] ?? null );
|
||||
if ( null === $type ) {
|
||||
return $fail( 'The picture or video must be PNG, JPEG, GIF, WebP, MP4 or WebM. Other file types are not allowed.' );
|
||||
}
|
||||
$visualId = $vRaw;
|
||||
$visual = $type;
|
||||
self::sizeWarning( $a, 'picture or video', 'video' === $type, $warnings );
|
||||
}
|
||||
if ( $sRaw > 0 ) {
|
||||
$a = $attachment( $sRaw );
|
||||
if ( ! is_array( $a ) ) {
|
||||
return $fail( 'The sound you chose no longer exists in your Media Library. Please pick it again.' );
|
||||
}
|
||||
if ( ! Media::isSound( $a['mime'] ?? null ) ) {
|
||||
return $fail( 'The sound must be an MP3, OGG or WAV file.' );
|
||||
}
|
||||
$sound = $sRaw;
|
||||
self::sizeWarning( $a, 'sound', false, $warnings );
|
||||
}
|
||||
|
||||
$vol = Input::int( $post['volume'] ?? '80', 0, 100 );
|
||||
if ( null === $vol ) {
|
||||
return $fail( 'Volume must be a whole number from 0 to 100.' );
|
||||
}
|
||||
$dur = Media::secondsToMs( $post['duration'] ?? '6' );
|
||||
if ( null === $dur || (int) round( (float) $post['duration'] * 1000 ) !== $dur ) {
|
||||
return $fail( 'How long the picture stays must be between 1 and 60 seconds.' );
|
||||
}
|
||||
$message = Input::text( $post['message'] ?? '', 400 );
|
||||
if ( mb_strlen( $message ) > 255 ) {
|
||||
return $fail( 'The message can be at most 255 characters.' );
|
||||
}
|
||||
$sortRaw = $post['sort'] ?? '';
|
||||
$sort = ( is_scalar( $sortRaw ) && '' === trim( (string) $sortRaw ) ) ? $defaultSort : Input::int( $sortRaw, 0, 99999 );
|
||||
if ( null === $sort ) {
|
||||
return $fail( 'The sort order must be a whole number from 0 to 99999.' );
|
||||
}
|
||||
$frameless = self::checkbox( $post['frameless'] ?? null ) ? 1 : 0;
|
||||
return array(
|
||||
'data' => array(
|
||||
'goal_id' => $goal,
|
||||
'trigger_type' => $trigger,
|
||||
'min_minor' => $min,
|
||||
'action_id' => $action,
|
||||
'title' => $title,
|
||||
'visual_id' => $visualId,
|
||||
'visual_type' => $visual,
|
||||
'sound_id' => $sound,
|
||||
'volume' => $vol,
|
||||
'duration_ms' => $dur,
|
||||
'message' => $message,
|
||||
'sort' => $sort,
|
||||
'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 ) {
|
||||
$warnings[] = 'The ' . $what . ' is over 25 MB.' . ( $video ? ' Big videos can make OBS stutter or load slowly; a short, compressed clip works much better.' : ' Large files take longer to load, so the alert may start late.' );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** $wpdb access to sg_alert_defs. */
|
||||
final class DefRepository {
|
||||
|
||||
private object $db;
|
||||
|
||||
public function __construct( ?object $db = null ) {
|
||||
$this->db = $db ?? $GLOBALS['wpdb'];
|
||||
}
|
||||
|
||||
private function t(): string {
|
||||
return $this->db->prefix . 'sg_alert_defs';
|
||||
}
|
||||
|
||||
/** @return array<string,mixed> */
|
||||
private static function cast( array $r ): array {
|
||||
return array(
|
||||
'id' => (int) ( $r['id'] ?? 0 ),
|
||||
'goal_id' => (int) ( $r['goal_id'] ?? 0 ),
|
||||
'trigger_type' => 'reward' === ( $r['trigger_type'] ?? '' ) ? 'reward' : 'amount',
|
||||
'min_minor' => (int) ( $r['min_minor'] ?? 0 ),
|
||||
'action_id' => (int) ( $r['action_id'] ?? 0 ),
|
||||
'title' => (string) ( $r['title'] ?? '' ),
|
||||
'visual_id' => (int) ( $r['visual_id'] ?? 0 ),
|
||||
'visual_type' => (string) ( $r['visual_type'] ?? '' ),
|
||||
'sound_id' => (int) ( $r['sound_id'] ?? 0 ),
|
||||
'volume' => (int) ( $r['volume'] ?? 80 ),
|
||||
'duration_ms' => (int) ( $r['duration_ms'] ?? 6000 ),
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'frameless' => (int) ( $r['frameless'] ?? 0 ) ? 1 : 0,
|
||||
'enabled' => (int) ( $r['enabled'] ?? 0 ),
|
||||
'sort' => (int) ( $r['sort'] ?? 0 ),
|
||||
'created_at' => (string) ( $r['created_at'] ?? '' ),
|
||||
);
|
||||
}
|
||||
|
||||
public function all(): array {
|
||||
return array_map( array( self::class, 'cast' ), (array) $this->db->get_results( 'SELECT * FROM ' . $this->t() . ' ORDER BY sort ASC, id ASC', ARRAY_A ) );
|
||||
}
|
||||
|
||||
/** All enabled definitions (one query); the Resolver filters by goal. */
|
||||
public function enabled(): array {
|
||||
return array_map( array( self::class, 'cast' ), (array) $this->db->get_results( 'SELECT * FROM ' . $this->t() . ' WHERE enabled = 1 ORDER BY sort ASC, id ASC', ARRAY_A ) );
|
||||
}
|
||||
|
||||
public function find( int $id ): ?array {
|
||||
$row = $this->db->get_row( $this->db->prepare( 'SELECT * FROM ' . $this->t() . ' WHERE id = %d', $id ), ARRAY_A );
|
||||
return $row ? self::cast( $row ) : null;
|
||||
}
|
||||
|
||||
public function nextSort(): int {
|
||||
return (int) $this->db->get_var( 'SELECT COALESCE(MAX(sort),0)+10 FROM ' . $this->t() );
|
||||
}
|
||||
|
||||
private const COLS = array(
|
||||
'goal_id' => '%d', 'trigger_type' => '%s', 'min_minor' => '%d', 'action_id' => '%d', 'title' => '%s', 'visual_id' => '%d',
|
||||
'visual_type' => '%s', 'sound_id' => '%d', 'volume' => '%d', 'duration_ms' => '%d', 'message' => '%s', 'sort' => '%d', 'frameless' => '%d',
|
||||
);
|
||||
|
||||
public function create( array $d ): int {
|
||||
$row = array();
|
||||
foreach ( self::COLS as $k => $f ) {
|
||||
$row[ $k ] = $d[ $k ] ?? ( '%d' === $f ? 0 : '' );
|
||||
}
|
||||
$row['enabled'] = 1;
|
||||
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
|
||||
$ok = $this->db->insert( $this->t(), $row, array_merge( array_values( self::COLS ), array( '%d', '%s' ) ) );
|
||||
return $ok ? (int) $this->db->insert_id : 0;
|
||||
}
|
||||
|
||||
public function update( int $id, array $d ): void {
|
||||
$row = array();
|
||||
foreach ( self::COLS as $k => $f ) {
|
||||
$row[ $k ] = $d[ $k ] ?? ( '%d' === $f ? 0 : '' );
|
||||
}
|
||||
$this->db->update( $this->t(), $row, array( 'id' => $id ), array_values( self::COLS ), array( '%d' ) );
|
||||
}
|
||||
|
||||
public function setEnabled( int $id, bool $on ): void {
|
||||
$this->db->update( $this->t(), array( 'enabled' => $on ? 1 : 0 ), array( 'id' => $id ), array( '%d' ), array( '%d' ) );
|
||||
}
|
||||
|
||||
public function delete( int $id ): void {
|
||||
$this->db->delete( $this->t(), array( 'id' => $id ), array( '%d' ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** Pure helpers: MIME whitelist, type classification and duration clamping for alert media. */
|
||||
final class Media {
|
||||
|
||||
/** Exact MIME => kind. Everything else (svg, html, ...) is rejected. */
|
||||
public const MIMES = array(
|
||||
'image/png' => 'image',
|
||||
'image/jpeg' => 'image',
|
||||
'image/gif' => 'image',
|
||||
'image/webp' => 'image',
|
||||
'video/mp4' => 'video',
|
||||
'video/webm' => 'video',
|
||||
'audio/mpeg' => 'audio',
|
||||
'audio/ogg' => 'audio',
|
||||
'audio/wav' => 'audio',
|
||||
);
|
||||
|
||||
public const WARN_BYTES = 26214400; // 25 MB
|
||||
public const MIN_DURATION_MS = 1000;
|
||||
public const MAX_DURATION_MS = 60000;
|
||||
public const DEFAULT_MS = 6000;
|
||||
public const VIDEO_CAP_MS = 30000;
|
||||
|
||||
/** 'image' | 'video' | 'audio' for an allowed MIME, else null. Strict: no parameters, no case games. */
|
||||
public static function kind( mixed $mime ): ?string {
|
||||
if ( ! is_string( $mime ) ) {
|
||||
return null;
|
||||
}
|
||||
return self::MIMES[ strtolower( $mime ) ] ?? null;
|
||||
}
|
||||
|
||||
public static function isAllowed( mixed $mime ): bool {
|
||||
return null !== self::kind( $mime );
|
||||
}
|
||||
|
||||
/** 'image' | 'video' for a visual attachment MIME, else null (audio is not a visual). */
|
||||
public static function visualType( mixed $mime ): ?string {
|
||||
$k = self::kind( $mime );
|
||||
return 'image' === $k || 'video' === $k ? $k : null;
|
||||
}
|
||||
|
||||
public static function isSound( mixed $mime ): bool {
|
||||
return 'audio' === self::kind( $mime );
|
||||
}
|
||||
|
||||
public static function clampDurationMs( mixed $ms, int $default = self::DEFAULT_MS ): int {
|
||||
if ( ! is_numeric( $ms ) ) {
|
||||
return $default;
|
||||
}
|
||||
return max( self::MIN_DURATION_MS, min( self::MAX_DURATION_MS, (int) $ms ) );
|
||||
}
|
||||
|
||||
/** Whole seconds (1-60) to clamped milliseconds; null when the input is not a number. */
|
||||
public static function secondsToMs( mixed $s ): ?int {
|
||||
if ( ! is_scalar( $s ) || ! preg_match( '/^\s*\d{1,4}(\.\d+)?\s*$/', (string) $s ) ) {
|
||||
return null;
|
||||
}
|
||||
return self::clampDurationMs( (int) round( (float) $s * 1000 ) );
|
||||
}
|
||||
|
||||
public static function clampVolume( mixed $v, int $default = 80 ): int {
|
||||
return is_numeric( $v ) ? max( 0, min( 100, (int) $v ) ) : $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 ) ) {
|
||||
return null;
|
||||
}
|
||||
return preg_match( '#^https?://[^/]#i', $url ) ? $url : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** Picks the single alert definition that applies to one donation. Pure. */
|
||||
final class Resolver {
|
||||
|
||||
/**
|
||||
* @param int[] $triggeredActionIds Rewards triggered by this donation.
|
||||
* @param array<int,array<string,mixed>> $defs Raw sg_alert_defs rows (any state; filtered here).
|
||||
* @param array<int,int> $actionAmounts action id => reward amount (minor); ties fall back to sort, id.
|
||||
* @return array<string,mixed>|null the winning row (with ints normalised) or null
|
||||
*/
|
||||
public static function pick( int $goalId, int $baseMinor, array $triggeredActionIds, array $defs, array $actionAmounts = array() ): ?array {
|
||||
$triggered = array_flip( array_map( 'intval', $triggeredActionIds ) );
|
||||
$reward = array();
|
||||
$amount = array();
|
||||
foreach ( $defs as $d ) {
|
||||
if ( ! is_array( $d ) || empty( $d['enabled'] ) ) {
|
||||
continue;
|
||||
}
|
||||
$dg = (int) ( $d['goal_id'] ?? 0 );
|
||||
if ( 0 !== $dg && $dg !== $goalId ) {
|
||||
continue;
|
||||
}
|
||||
$d['id'] = (int) ( $d['id'] ?? 0 );
|
||||
$d['sort'] = (int) ( $d['sort'] ?? 0 );
|
||||
$d['min_minor'] = (int) ( $d['min_minor'] ?? 0 );
|
||||
$d['action_id'] = (int) ( $d['action_id'] ?? 0 );
|
||||
$d['goal_id'] = $dg;
|
||||
if ( 'reward' === ( $d['trigger_type'] ?? '' ) ) {
|
||||
if ( $d['action_id'] > 0 && isset( $triggered[ $d['action_id'] ] ) ) {
|
||||
$reward[] = $d;
|
||||
}
|
||||
} elseif ( 'amount' === ( $d['trigger_type'] ?? '' ) && $baseMinor >= $d['min_minor'] ) {
|
||||
$amount[] = $d;
|
||||
}
|
||||
}
|
||||
if ( $reward ) {
|
||||
usort( $reward, static function ( array $a, array $b ) use ( $actionAmounts ): int {
|
||||
return ( (int) ( $actionAmounts[ $b['action_id'] ] ?? 0 ) <=> (int) ( $actionAmounts[ $a['action_id'] ] ?? 0 ) )
|
||||
?: ( $a['sort'] <=> $b['sort'] )
|
||||
?: ( $a['id'] <=> $b['id'] );
|
||||
} );
|
||||
return $reward[0];
|
||||
}
|
||||
if ( $amount ) {
|
||||
usort( $amount, static fn( array $a, array $b ): int => ( $b['min_minor'] <=> $a['min_minor'] ) ?: ( $a['sort'] <=> $b['sort'] ) ?: ( $a['id'] <=> $b['id'] ) );
|
||||
return $amount[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Alerts;
|
||||
|
||||
/** Renders the custom alert message. Output is plain text: no tags, no control characters, length-capped. */
|
||||
final class Template {
|
||||
|
||||
public const MAX = 200;
|
||||
|
||||
public static function clean( string $s ): string {
|
||||
$s = strip_tags( $s );
|
||||
$s = (string) preg_replace( '/[\x00-\x1F\x7F\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}\x{FEFF}]+/u', ' ', $s );
|
||||
$s = str_replace( array( '<', '>' ), '', $s );
|
||||
return trim( (string) preg_replace( '/\s+/u', ' ', $s ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokens: {name} {amount} {reward} (case-insensitive). Unknown tokens are dropped. Substituted values are never
|
||||
* re-scanned for tokens. Empty template (or empty result) returns '' meaning "use the default text".
|
||||
*/
|
||||
public static function render( string $template, string $name, string $amount, string $reward, int $max = self::MAX ): string {
|
||||
$tpl = self::clean( $template );
|
||||
if ( '' === $tpl ) {
|
||||
return '';
|
||||
}
|
||||
$name = self::clean( $name );
|
||||
$vals = array(
|
||||
'name' => '' === $name ? 'Anonymous' : mb_substr( $name, 0, 60 ),
|
||||
'amount' => mb_substr( self::clean( $amount ), 0, 30 ),
|
||||
'reward' => mb_substr( self::clean( $reward ), 0, 80 ),
|
||||
);
|
||||
$out = (string) preg_replace_callback(
|
||||
'/\{([A-Za-z_]{1,20})\}/',
|
||||
static fn( array $m ): string => $vals[ strtolower( $m[1] ) ] ?? '',
|
||||
$tpl
|
||||
);
|
||||
$out = trim( (string) preg_replace( '/\s+/u', ' ', $out ) );
|
||||
return mb_substr( $out, 0, max( 1, $max ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/** Pure IPv4/IPv6 CIDR membership test (no WordPress, no network). Malformed input never matches. */
|
||||
final class CidrMatcher {
|
||||
|
||||
/** @param string[] $cidrs e.g. ['173.245.48.0/20', '2606:4700::/32'] */
|
||||
public static function contains( string $ip, array $cidrs ): bool {
|
||||
$ipBin = @inet_pton( trim( $ip ) );
|
||||
if ( false === $ipBin ) {
|
||||
return false;
|
||||
}
|
||||
foreach ( $cidrs as $cidr ) {
|
||||
if ( self::inRange( $ipBin, (string) $cidr ) ) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static function inRange( string $ipBin, string $cidr ): bool {
|
||||
$parts = explode( '/', trim( $cidr ), 2 );
|
||||
if ( 2 !== count( $parts ) || ! ctype_digit( $parts[1] ) ) {
|
||||
return false;
|
||||
}
|
||||
$netBin = @inet_pton( $parts[0] );
|
||||
if ( false === $netBin || strlen( $netBin ) !== strlen( $ipBin ) ) { // different address families never match
|
||||
return false;
|
||||
}
|
||||
$bits = (int) $parts[1];
|
||||
if ( $bits < 0 || $bits > strlen( $netBin ) * 8 ) {
|
||||
return false;
|
||||
}
|
||||
$fullBytes = intdiv( $bits, 8 );
|
||||
if ( $fullBytes > 0 && substr( $ipBin, 0, $fullBytes ) !== substr( $netBin, 0, $fullBytes ) ) {
|
||||
return false;
|
||||
}
|
||||
$rest = $bits % 8;
|
||||
if ( 0 === $rest ) {
|
||||
return true;
|
||||
}
|
||||
$mask = ( 0xFF << ( 8 - $rest ) ) & 0xFF;
|
||||
return ( ord( $ipBin[ $fullBytes ] ) & $mask ) === ( ord( $netBin[ $fullBytes ] ) & $mask );
|
||||
}
|
||||
}
|
||||
@@ -12,12 +12,14 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class ClientIp {
|
||||
|
||||
public const MODE_AUTO = 'auto'; // detect Cloudflare automatically (recommended)
|
||||
public const MODE_DIRECT = ''; // no proxy: use REMOTE_ADDR
|
||||
public const MODE_CLOUDFLARE = 'cloudflare'; // CF-Connecting-IP
|
||||
public const MODE_REAL_IP = 'real_ip'; // X-Real-IP (nginx and many hosts)
|
||||
public const MODE_FORWARDED = 'forwarded'; // last address in X-Forwarded-For (exactly one proxy in front)
|
||||
|
||||
public const MODES = array(
|
||||
self::MODE_AUTO => 'Automatic (recommended): detects Cloudflare',
|
||||
self::MODE_DIRECT => 'Not behind a proxy or CDN (most sites)',
|
||||
self::MODE_CLOUDFLARE => 'Cloudflare (CF-Connecting-IP)',
|
||||
self::MODE_REAL_IP => 'X-Real-IP header',
|
||||
@@ -25,10 +27,16 @@ final class ClientIp {
|
||||
);
|
||||
|
||||
/** @param array<string,mixed> $server $_SERVER-style values (already unslashed). */
|
||||
public static function resolve( array $server, string $mode = self::MODE_DIRECT ): string {
|
||||
public static function resolve( array $server, string $mode = self::MODE_DIRECT, ?array $extraCloudflareRanges = null ): string {
|
||||
$remote = self::valid( $server['REMOTE_ADDR'] ?? null );
|
||||
$fromHeader = null;
|
||||
switch ( $mode ) {
|
||||
case self::MODE_AUTO:
|
||||
// Trust CF-Connecting-IP only when the connection itself comes from a Cloudflare address.
|
||||
if ( null !== $remote && CloudflareRanges::isCloudflare( $remote, $extraCloudflareRanges ) ) {
|
||||
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
|
||||
}
|
||||
break;
|
||||
case self::MODE_CLOUDFLARE:
|
||||
$fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null );
|
||||
break;
|
||||
@@ -46,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;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/**
|
||||
* Cloudflare's published proxy address ranges (https://www.cloudflare.com/ips-v4 and /ips-v6), fetched 2026-11-15.
|
||||
* They change very rarely. Sites can extend them with the `streamgoals_cloudflare_ranges` filter.
|
||||
* Used ONLY to decide whether a connection really comes from Cloudflare, so a forged CF-Connecting-IP header
|
||||
* from anywhere else is ignored.
|
||||
*/
|
||||
final class CloudflareRanges {
|
||||
|
||||
public const RANGES = array(
|
||||
'173.245.48.0/20', '103.21.244.0/22', '103.22.200.0/22', '103.31.4.0/22', '141.101.64.0/18', '108.162.192.0/18',
|
||||
'190.93.240.0/20', '188.114.96.0/20', '197.234.240.0/22', '198.41.128.0/17', '162.158.0.0/15', '104.16.0.0/13',
|
||||
'104.24.0.0/14', '172.64.0.0/13', '131.0.72.0/22',
|
||||
'2400:cb00::/32', '2606:4700::/32', '2803:f800::/32', '2405:b500::/32', '2405:8100::/32', '2a06:98c0::/29', '2c0f:f248::/32',
|
||||
);
|
||||
|
||||
/** @param string[]|null $extra additional ranges (from the filter) */
|
||||
public static function isCloudflare( string $ip, ?array $extra = null ): bool {
|
||||
return CidrMatcher::contains( $ip, array_merge( self::RANGES, $extra ?? array() ) );
|
||||
}
|
||||
}
|
||||
@@ -22,7 +22,7 @@ final class DonationRepository {
|
||||
|
||||
/** @return int|null new id, or null on failure (e.g. duplicate capture id). */
|
||||
public function insert( array $d ): ?int {
|
||||
$allowed = array( 'goal_id', 'paypal_order_id', 'paypal_capture_id', 'base_minor', 'fee_minor', 'total_minor', 'currency', 'donor_name', 'is_anonymous', 'message', 'status', 'moderation' );
|
||||
$allowed = array( 'goal_id', 'paypal_order_id', 'paypal_capture_id', 'base_minor', 'fee_minor', 'total_minor', 'currency', 'donor_name', 'is_anonymous', 'message', 'status', 'moderation', 'moderation_flags' );
|
||||
$row = array_intersect_key( $d, array_flip( $allowed ) );
|
||||
$row += array( 'status' => 'pending', 'moderation' => 'approved', 'fee_minor' => 0 );
|
||||
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
|
||||
|
||||
@@ -6,7 +6,7 @@ namespace StreamGoals\Core;
|
||||
/** $wpdb-backed CRUD for sg_goals. Requires live WordPress. */
|
||||
final class GoalRepository {
|
||||
|
||||
private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d' );
|
||||
private const FIELDS = array( 'title' => '%s', 'target_minor' => '%d', 'currency' => '%s', 'status' => '%s', 'starts_at' => '%s', 'ends_at' => '%s', 'counts_fees' => '%d', 'close_at_target' => '%d' );
|
||||
|
||||
private \wpdb $db;
|
||||
|
||||
@@ -21,7 +21,7 @@ final class GoalRepository {
|
||||
/** @return int new goal id */
|
||||
public function create( array $data ): int {
|
||||
$row = array_intersect_key( $data, self::FIELDS );
|
||||
$row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0 );
|
||||
$row += array( 'status' => 'active', 'currency' => 'USD', 'counts_fees' => 0, 'close_at_target' => 0 );
|
||||
$row['created_at'] = gmdate( 'Y-m-d H:i:s' );
|
||||
$this->db->insert( $this->table(), $row );
|
||||
return (int) $this->db->insert_id;
|
||||
@@ -62,9 +62,26 @@ final class GoalRepository {
|
||||
if ( ! $goal ) {
|
||||
return 0;
|
||||
}
|
||||
$col = ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor'; // whitelisted, not user input
|
||||
$col = GoalTargetPolicy::amountColumn( $goal ); // whitelisted, not user input
|
||||
$d = $this->db->prefix . 'sg_donations';
|
||||
$sum = $this->db->get_var( $this->db->prepare( "SELECT COALESCE(SUM({$col}), 0) FROM {$d} WHERE goal_id = %d AND status = 'completed'", $goalId ) );
|
||||
return (int) $sum;
|
||||
}
|
||||
|
||||
/**
|
||||
* "End at target": if the goal is active, flagged close_at_target and its raised total has reached the
|
||||
* target, set it to 'complete'. The UPDATE is conditional on status = 'active', so concurrent callers
|
||||
* change it once. Idempotent and cheap (one SELECT for non-flagged goals). Returns true if THIS call closed it.
|
||||
*/
|
||||
public function closeIfTargetReached( int $goalId ): bool {
|
||||
$goal = $this->find( $goalId );
|
||||
if ( ! $goal || empty( $goal['close_at_target'] ) || 'active' !== $goal['status'] ) {
|
||||
return false;
|
||||
}
|
||||
if ( ! GoalTargetPolicy::shouldClose( $goal, $this->raised_minor( $goalId ) ) ) {
|
||||
return false;
|
||||
}
|
||||
$n = $this->db->query( $this->db->prepare( "UPDATE {$this->table()} SET status = 'complete' WHERE id = %d AND status = 'active' AND close_at_target = 1", $goalId ) );
|
||||
return 1 === $n;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Core;
|
||||
|
||||
/** Pure rules for "end at target" goals (no WordPress / database access). */
|
||||
final class GoalTargetPolicy {
|
||||
|
||||
/** Donation column summed towards the goal: total (fees included) or base. Whitelisted values only. */
|
||||
public static function amountColumn( array $goal ): string {
|
||||
return ! empty( $goal['counts_fees'] ) ? 'total_minor' : 'base_minor';
|
||||
}
|
||||
|
||||
/** True when the goal should now be auto-closed: flag on, currently active, target set and reached or exceeded. */
|
||||
public static function shouldClose( array $goal, int $raisedMinor ): bool {
|
||||
return ! empty( $goal['close_at_target'] )
|
||||
&& 'active' === ( $goal['status'] ?? '' )
|
||||
&& (int) ( $goal['target_minor'] ?? 0 ) > 0
|
||||
&& $raisedMinor >= (int) $goal['target_minor'];
|
||||
}
|
||||
|
||||
/** True for a goal that is closed to donors because it reached its target (flag on + complete). */
|
||||
public static function isClosedAtTarget( array $goal ): bool {
|
||||
return ! empty( $goal['close_at_target'] ) && 'complete' === ( $goal['status'] ?? '' );
|
||||
}
|
||||
|
||||
/** Checkbox value from a raw form field: 1 when ticked, else 0. */
|
||||
public static function flagFromPost( mixed $raw ): int {
|
||||
if ( is_array( $raw ) || null === $raw ) {
|
||||
return 0;
|
||||
}
|
||||
return in_array( strtolower( trim( (string) $raw ) ), array( '1', 'on', 'true', 'yes' ), true ) ? 1 : 0;
|
||||
}
|
||||
}
|
||||
@@ -8,23 +8,45 @@ namespace StreamGoals\Core;
|
||||
*/
|
||||
final class Installer {
|
||||
|
||||
public const DB_VERSION = '3';
|
||||
public const DB_VERSION = '6';
|
||||
|
||||
public static function activate(): void {
|
||||
self::install_schema();
|
||||
self::install_schema( get_option( 'sg_db_version' ) );
|
||||
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. */
|
||||
public static function maybe_upgrade(): void {
|
||||
if ( get_option( 'sg_db_version' ) !== self::DB_VERSION ) {
|
||||
self::install_schema();
|
||||
$from = get_option( 'sg_db_version' );
|
||||
if ( $from !== self::DB_VERSION ) {
|
||||
self::install_schema( $from );
|
||||
}
|
||||
}
|
||||
|
||||
private static function install_schema(): void {
|
||||
/** Schema v6 added sg_donations.effects_applied_at; rows completed before that must not be replayed. */
|
||||
public static function needsEffectsBackfill( mixed $from ): bool {
|
||||
return false === $from || '' === $from || version_compare( (string) $from, '6', '<' );
|
||||
}
|
||||
|
||||
/**
|
||||
* One-time upgrade step: every donation that is ALREADY completed had its side effects applied by the code that
|
||||
* completed it (or was lost before this feature existed and is not worth replaying), so stamp it. Without this the
|
||||
* reconciler would replay the whole history. Only touches NULL rows, so re-running is harmless. False on DB error.
|
||||
*/
|
||||
public static function backfill_effects_applied(): bool {
|
||||
global $wpdb;
|
||||
$n = $wpdb->query( $wpdb->prepare(
|
||||
'UPDATE ' . $wpdb->prefix . "sg_donations SET effects_applied_at = %s WHERE status = 'completed' AND effects_applied_at IS NULL",
|
||||
gmdate( 'Y-m-d H:i:s' )
|
||||
) );
|
||||
return false !== $n;
|
||||
}
|
||||
|
||||
/** @param mixed $from Previously installed sg_db_version (false when never installed). */
|
||||
private static function install_schema( mixed $from = false ): void {
|
||||
global $wpdb;
|
||||
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
|
||||
$c = $wpdb->get_charset_collate();
|
||||
@@ -58,6 +80,8 @@ final class Installer {
|
||||
message VARCHAR(500) NOT NULL DEFAULT '',
|
||||
status VARCHAR(12) NOT NULL DEFAULT 'pending',
|
||||
moderation VARCHAR(10) NOT NULL DEFAULT 'approved',
|
||||
moderation_flags VARCHAR(16) NOT NULL DEFAULT '',
|
||||
effects_applied_at DATETIME NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY capture (paypal_capture_id),
|
||||
@@ -138,11 +162,31 @@ 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)
|
||||
) $c;" );
|
||||
|
||||
dbDelta( "CREATE TABLE {$p}goal_tiers (
|
||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||
goal_id BIGINT UNSIGNED NOT NULL,
|
||||
target_minor BIGINT UNSIGNED NOT NULL,
|
||||
title VARCHAR(120) NOT NULL,
|
||||
description VARCHAR(255) NOT NULL DEFAULT '',
|
||||
reached_at DATETIME NULL,
|
||||
reached_donation_id BIGINT UNSIGNED NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY goal_target (goal_id,target_minor),
|
||||
KEY reached_donation (reached_donation_id)
|
||||
) $c;" );
|
||||
|
||||
// Backfill BEFORE recording the new version: if it fails, the next load retries instead of replaying history.
|
||||
if ( self::needsEffectsBackfill( $from ) && ! self::backfill_effects_applied() ) {
|
||||
return;
|
||||
}
|
||||
|
||||
update_option( 'sg_db_version', self::DB_VERSION );
|
||||
}
|
||||
}
|
||||
@@ -14,15 +14,106 @@ final class Maintenance {
|
||||
public const HOOK = 'sg_purge_abandoned';
|
||||
public const MAX_AGE_DAYS = 7;
|
||||
|
||||
/** Reconcile "completed but side effects lost" donations (see reconcile_effects()). */
|
||||
public const RECONCILE_HOOK = 'sg_reconcile_effects';
|
||||
public const RECONCILE_SCHEDULE = 'sg_five_minutes';
|
||||
/** A donation must be this old before it is replayed, so a request still applying its effects is left alone. */
|
||||
public const RECONCILE_MIN_AGE = 120;
|
||||
/** Older donations are not retried (a row that can never succeed must not be replayed forever). */
|
||||
public const RECONCILE_MAX_AGE_DAYS = 30;
|
||||
public const RECONCILE_BATCH = 25;
|
||||
|
||||
public static function register(): void {
|
||||
add_action( self::HOOK, array( self::class, 'purge_abandoned' ) );
|
||||
if ( ! wp_next_scheduled( self::HOOK ) ) {
|
||||
wp_schedule_event( time() + HOUR_IN_SECONDS, 'daily', self::HOOK );
|
||||
}
|
||||
add_filter( 'cron_schedules', array( self::class, 'cron_schedules' ) );
|
||||
add_action( self::RECONCILE_HOOK, array( self::class, 'reconcile_effects' ) );
|
||||
if ( ! wp_next_scheduled( self::RECONCILE_HOOK ) ) {
|
||||
wp_schedule_event( time() + 300, self::RECONCILE_SCHEDULE, self::RECONCILE_HOOK );
|
||||
}
|
||||
}
|
||||
|
||||
/** @param array $schedules @return array */
|
||||
public static function cron_schedules( $schedules ): array {
|
||||
$schedules = is_array( $schedules ) ? $schedules : array();
|
||||
$schedules[ self::RECONCILE_SCHEDULE ] = array( 'interval' => 300, 'display' => 'Every five minutes (StreamGoals)' );
|
||||
return $schedules;
|
||||
}
|
||||
|
||||
public static function unschedule(): void {
|
||||
wp_clear_scheduled_hook( self::HOOK );
|
||||
wp_clear_scheduled_hook( self::RECONCILE_HOOK );
|
||||
}
|
||||
|
||||
/**
|
||||
* Replays the side effects (rules/timer/counter, rewards, tiers, end-at-target) of completed donations whose request
|
||||
* died before DonationStore::notify_applied() could stamp effects_applied_at. Safe by construction: every effect is
|
||||
* idempotent per (rule, donation) / (donation, action) / tier, and the donation row itself is never touched here.
|
||||
* Single-flight through a MySQL named lock so overlapping cron runs do not pile up.
|
||||
*
|
||||
* @return int Donations whose effects were confirmed applied by this run.
|
||||
*/
|
||||
public static function reconcile_effects(): int {
|
||||
global $wpdb;
|
||||
$locked = $wpdb && 1 === (int) $wpdb->get_var( $wpdb->prepare( 'SELECT GET_LOCK(%s, 0)', 'sg_reconcile_effects' ) );
|
||||
if ( ! $locked ) {
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
return self::reconcile(
|
||||
time(),
|
||||
array( \StreamGoals\PayPal\DonationStore::class, 'unapplied_completed_ids' ),
|
||||
array( \StreamGoals\PayPal\DonationStore::class, 'notify_applied' )
|
||||
);
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: reconcile failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return 0;
|
||||
} finally {
|
||||
$wpdb->get_var( $wpdb->prepare( 'SELECT RELEASE_LOCK(%s)', 'sg_reconcile_effects' ) );
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure orchestration (unit-tested).
|
||||
*
|
||||
* @param callable $find fn(string $notAfter, string $notBefore, int $limit): int[]
|
||||
* @param callable $apply fn(int $donationId): bool true once the donation is stamped as applied
|
||||
*/
|
||||
public static function reconcile( int $now, callable $find, callable $apply ): int {
|
||||
$notAfter = gmdate( 'Y-m-d H:i:s', $now - self::RECONCILE_MIN_AGE );
|
||||
$notBefore = gmdate( 'Y-m-d H:i:s', $now - self::RECONCILE_MAX_AGE_DAYS * 86400 );
|
||||
$done = 0;
|
||||
foreach ( (array) $find( $notAfter, $notBefore, self::RECONCILE_BATCH ) as $id ) {
|
||||
try {
|
||||
if ( $apply( (int) $id ) ) {
|
||||
++$done;
|
||||
}
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: reconcile of donation ' . (int) $id . ' failed: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
}
|
||||
}
|
||||
return $done;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. */
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -58,8 +58,23 @@ final class ProfanityFilter {
|
||||
return $this->enabled && array() !== $this->words;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when at least one word of $text is listed, i.e. filter() would change it. Same rules as filter()
|
||||
* (whole words, leetspeak, case-insensitive). Used to hold a donor name for moderation. Never throws.
|
||||
*/
|
||||
public function matches( string $text ): bool {
|
||||
$hit = false;
|
||||
$this->scan( $text, $hit );
|
||||
return $hit;
|
||||
}
|
||||
|
||||
/** Mask every listed word; everything else is returned byte-for-byte (after UTF-8 scrubbing). */
|
||||
public function filter( string $text ): string {
|
||||
$hit = false;
|
||||
return $this->scan( $text, $hit );
|
||||
}
|
||||
|
||||
private function scan( string $text, bool &$hit ): string {
|
||||
if ( ! $this->isEnabled() || '' === $text ) {
|
||||
return $text;
|
||||
}
|
||||
@@ -70,13 +85,14 @@ final class ProfanityFilter {
|
||||
$text = mb_scrub( $text, 'UTF-8' );
|
||||
$out = preg_replace_callback(
|
||||
'/[\p{L}\p{M}\p{N}@$!]+/u',
|
||||
function ( array $m ): string {
|
||||
function ( array $m ) use ( &$hit ): string {
|
||||
$tok = $m[0];
|
||||
// "!" is only a leet char inside a word; trailing/leading punctuation is not part of it.
|
||||
$core = trim( $tok, '!' );
|
||||
if ( '' === $core || ! $this->isListed( $core ) ) {
|
||||
return $tok;
|
||||
}
|
||||
$hit = true;
|
||||
$lead = (int) strspn( $tok, '!' );
|
||||
$trail = strlen( $tok ) - strlen( rtrim( $tok, '!' ) );
|
||||
return str_repeat( '!', $lead ) . str_repeat( '*', mb_strlen( $core ) ) . str_repeat( '!', $trail );
|
||||
|
||||
@@ -34,11 +34,13 @@ final class Settings {
|
||||
'profanity_words' => '', // streamer's extra words, one per line
|
||||
'message_max_length' => 200,
|
||||
'min_donation_minor' => 100,
|
||||
'donation_notice' => 'Donations are non-refundable.', // shown under the donation form; empty hides it
|
||||
'overlay_token' => '',
|
||||
'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp)
|
||||
'visitor_ip_header' => 'auto', // auto | '' (direct) | cloudflare | real_ip | forwarded (see Core\ClientIp)
|
||||
'funding_paylater' => false, // show PayPal "Pay Later" button
|
||||
'update_token' => '', // optional Gitea read token (only while the update repo is private)
|
||||
'funding_card' => true, // show the Debit/Credit Card button
|
||||
'delete_data_on_uninstall' => false, // when the plugin is deleted, also drop all tables/options (see Core\Uninstaller)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -57,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' ) );
|
||||
}
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
<?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 );
|
||||
wp_clear_scheduled_hook( Maintenance::RECONCILE_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 );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** Optional capability: configurable alert media (definitions, triggered rewards, attachment lookup). */
|
||||
interface AlertMediaSource {
|
||||
|
||||
/** Enabled alert definitions, raw rows. Called at most once per request. */
|
||||
public function alertDefs(): array;
|
||||
|
||||
/**
|
||||
* Rewards triggered per donation, one lookup for the whole page.
|
||||
*
|
||||
* @param int[] $donationIds
|
||||
* @return array<int,array<int,array{action_id:int,amount_minor:int,title:string}>> donation id => rewards
|
||||
*/
|
||||
public function triggeredActionsFor( array $donationIds ): array;
|
||||
|
||||
/**
|
||||
* Server-side attachment lookup (the only place media URLs come from). Null when it is gone.
|
||||
*
|
||||
* @return array{url:string,mime:string,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;
|
||||
}
|
||||
@@ -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 );
|
||||
}
|
||||
}
|
||||
@@ -8,14 +8,31 @@ final class OverlayService {
|
||||
|
||||
public const WIDGETS = array( 'goal', 'timer', 'counter', 'alerts', 'actions' );
|
||||
|
||||
/** @var array<int,array<string,mixed>>|null */
|
||||
private ?array $defs = null;
|
||||
|
||||
public function __construct( private OverlayDataSource $source ) {}
|
||||
|
||||
/** Enabled alert definitions, loaded at most once per service instance (= per request). */
|
||||
private function defs(): array {
|
||||
if ( null === $this->defs ) {
|
||||
$this->defs = $this->source instanceof AlertMediaSource ? array_values( $this->source->alertDefs() ) : array();
|
||||
}
|
||||
return $this->defs;
|
||||
}
|
||||
|
||||
/** Extra ETag input so editing media definitions invalidates cached alert payloads even when no alert is pending. */
|
||||
public function etagSalt( string $widget ): string {
|
||||
return 'alerts' === $widget && $this->defs() ? md5( (string) json_encode( $this->defs() ) ) : '';
|
||||
}
|
||||
|
||||
public function payload( string $widget, int $now, ?int $since = null, bool $recent = false ): ?array {
|
||||
$goal = $this->source->activeGoal();
|
||||
$gid = $goal ? (int) $goal['id'] : 0;
|
||||
switch ( $widget ) {
|
||||
case 'goal':
|
||||
return Payloads::goal( $goal, $goal ? $this->source->raisedMinor( $goal ) : 0 );
|
||||
$tiers = ( $gid && $this->source instanceof TiersSource ) ? $this->source->tiersFor( $gid ) : array();
|
||||
return Payloads::goal( $goal, $goal ? $this->source->raisedMinor( $goal ) : 0, $tiers ?: null );
|
||||
case 'timer':
|
||||
return Payloads::timer(
|
||||
$gid ? $this->source->stateValue( $gid, 'timer_ends_at' ) : null,
|
||||
@@ -39,11 +56,22 @@ final class OverlayService {
|
||||
$ids = array_values( array_filter( array_map( static fn( $r ) => (int) ( $r['id'] ?? 0 ), $rows ) ) );
|
||||
$bonuses = ( ( $recent || null !== $since ) && $ids ) ? $this->source->bonusesFor( $ids ) : array();
|
||||
$actions = ( ( $recent || null !== $since ) && $ids && $this->source instanceof ActionsSource ) ? $this->source->actionsFor( $ids ) : array();
|
||||
$tiers = ( ( $recent || null !== $since ) && $ids && $this->source instanceof TiersSource ) ? $this->source->tiersReachedFor( $ids ) : array();
|
||||
foreach ( $rows as $i => $r ) {
|
||||
$rows[ $i ]['bonuses'] = $bonuses[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
$rows[ $i ]['actions'] = $actions[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
$rows[ $i ]['tiers'] = $tiers[ (int) ( $r['id'] ?? 0 ) ] ?? array();
|
||||
}
|
||||
return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent );
|
||||
$mediaFor = null;
|
||||
$defs = ( $recent || null !== $since ) ? $this->defs() : array();
|
||||
if ( $defs && $ids && $this->source instanceof AlertMediaSource ) {
|
||||
$src = $this->source;
|
||||
$triggered = $src->triggeredActionsFor( $ids );
|
||||
$mediaFor = static fn( array $r, string $name, string $amount ): ?array => \StreamGoals\Alerts\AlertMedia::build(
|
||||
$r, $name, $amount, $defs, $triggered[ (int) ( $r['id'] ?? 0 ) ] ?? array(), static fn( int $id ): ?array => $src->attachment( $id )
|
||||
);
|
||||
}
|
||||
return Payloads::alerts( $rows, $since, $recent ? 20 : 10, $recent, $mediaFor );
|
||||
case 'actions':
|
||||
$rows = ( $gid && $this->source instanceof ActionsSource ) ? $this->source->menuActions( $gid ) : array();
|
||||
return Payloads::actionsMenu( $goal, $rows );
|
||||
|
||||
@@ -4,6 +4,7 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Tiers\TierPolicy;
|
||||
|
||||
/**
|
||||
* Pure, WordPress-free payload builders. Everything returned here is public-safe.
|
||||
@@ -31,7 +32,10 @@ final class Payloads {
|
||||
return max( 0, min( 100, intdiv( max( 0, $raised ) * 100, $target ) ) );
|
||||
}
|
||||
|
||||
public static function goal( ?array $goal, int $raised ): array {
|
||||
/**
|
||||
* @param array<int,array<string,mixed>>|null $tiers Raw sg_goal_tiers rows; null/empty = an ordinary (untiered) goal, payload unchanged.
|
||||
*/
|
||||
public static function goal( ?array $goal, int $raised, ?array $tiers = null ): array {
|
||||
if ( null === $goal ) {
|
||||
return array( 'active' => false, 'title' => '', 'raised_minor' => 0, 'target_minor' => 0, 'percent' => 0,
|
||||
'currency' => 'USD', 'raised_display' => '', 'target_display' => '' );
|
||||
@@ -39,6 +43,9 @@ final class Payloads {
|
||||
$cur = strtoupper( (string) ( $goal['currency'] ?? 'USD' ) );
|
||||
$target = max( 0, (int) ( $goal['target_minor'] ?? 0 ) );
|
||||
$raised = max( 0, $raised );
|
||||
if ( $tiers ) {
|
||||
return self::tieredGoal( $goal, $raised, $cur, $tiers );
|
||||
}
|
||||
return array(
|
||||
'active' => true,
|
||||
'title' => (string) ( $goal['title'] ?? '' ),
|
||||
@@ -51,6 +58,40 @@ final class Payloads {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tiered goal: raised stays cumulative; target/percent describe the CURRENT tier (percent is within the tier).
|
||||
* When every tier is reached the bar is full at the top tier's target.
|
||||
*/
|
||||
private static function tieredGoal( array $goal, int $raised, string $cur, array $tiers ): array {
|
||||
$sorted = TierPolicy::sorted( $tiers );
|
||||
$current = TierPolicy::currentTier( $sorted );
|
||||
$all = null === $current;
|
||||
$target = $all ? TierPolicy::derivedGoalTarget( $sorted ) : max( 0, (int) $current['target_minor'] );
|
||||
$floor = TierPolicy::floorMinor( $sorted );
|
||||
return array(
|
||||
'active' => true,
|
||||
'title' => (string) ( $goal['title'] ?? '' ),
|
||||
'raised_minor' => $raised,
|
||||
'target_minor' => $target,
|
||||
'percent' => TierPolicy::percentFor( $sorted, $raised ),
|
||||
'currency' => $cur,
|
||||
'raised_display' => self::money( $raised, $cur ),
|
||||
'target_display' => self::money( $target, $cur ),
|
||||
'tiers' => array(
|
||||
'count' => count( $sorted ),
|
||||
'index' => TierPolicy::currentIndex( $sorted ),
|
||||
'current' => $all ? null : array(
|
||||
'title' => self::text( $current['title'] ?? '', 120 ),
|
||||
'description' => self::text( $current['description'] ?? '', 255 ),
|
||||
'target_minor' => $target,
|
||||
'target_display' => self::money( $target, $cur ),
|
||||
'floor_minor' => $floor,
|
||||
),
|
||||
'all_reached' => $all,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string|null $endsAt sg_state `timer_ends_at` (epoch seconds, or a UTC datetime string).
|
||||
* @param string|null $pausedRemaining sg_state `paused_remaining` seconds; non-null means paused.
|
||||
@@ -78,7 +119,7 @@ final class Payloads {
|
||||
* @param bool $recent Recent mode: ignore $since and return the newest $limit approved alerts (ascending id),
|
||||
* so a message approved after newer donations still shows up. The client dedupes by id.
|
||||
*/
|
||||
public static function alerts( array $rows, ?int $since, int $limit = 10, bool $recent = false ): array {
|
||||
public static function alerts( array $rows, ?int $since, int $limit = 10, bool $recent = false, ?callable $mediaFor = null ): array {
|
||||
$safe = array();
|
||||
foreach ( $rows as $r ) {
|
||||
if ( 'completed' !== ( $r['status'] ?? '' ) || 'approved' !== ( $r['moderation'] ?? '' ) ) {
|
||||
@@ -89,7 +130,7 @@ final class Payloads {
|
||||
usort( $safe, static fn( $a, $b ) => (int) $a['id'] <=> (int) $b['id'] );
|
||||
if ( $recent ) {
|
||||
$safe = array_slice( $safe, -max( 1, $limit ) );
|
||||
$alerts = array_map( array( self::class, 'alert' ), $safe );
|
||||
$alerts = array_map( static fn( array $r ): array => self::alert( $r, $mediaFor ), $safe );
|
||||
return array( 'alerts' => $alerts, 'last_id' => $alerts ? (int) end( $alerts )['id'] : 0 );
|
||||
}
|
||||
$lastId = $since ?? 0;
|
||||
@@ -104,7 +145,7 @@ final class Payloads {
|
||||
if ( (int) $r['id'] <= $since ) {
|
||||
continue;
|
||||
}
|
||||
$alerts[] = self::alert( $r );
|
||||
$alerts[] = self::alert( $r, $mediaFor );
|
||||
}
|
||||
$alerts = array_slice( $alerts, 0, max( 1, $limit ) );
|
||||
if ( $alerts ) {
|
||||
@@ -113,20 +154,27 @@ final class Payloads {
|
||||
return array( 'alerts' => $alerts, 'last_id' => $lastId );
|
||||
}
|
||||
|
||||
/** @param array<string,mixed> $r */
|
||||
private static function alert( array $r ): array {
|
||||
/**
|
||||
* @param array<string,mixed> $r
|
||||
* @param (callable(array,string,string):?array)|null $mediaFor Builds the `media` block from (row, public name, amount display).
|
||||
*/
|
||||
private static function alert( array $r, ?callable $mediaFor = null ): array {
|
||||
$cur = strtoupper( (string) ( $r['currency'] ?? 'USD' ) );
|
||||
$anon = ! empty( $r['is_anonymous'] );
|
||||
$name = trim( (string) ( $r['donor_name'] ?? '' ) );
|
||||
$pub = ( $anon || '' === $name ) ? self::ANON_NAME : $name;
|
||||
$disp = self::money( (int) $r['base_minor'], $cur );
|
||||
return array(
|
||||
'id' => (int) $r['id'],
|
||||
'name' => ( $anon || '' === $name ) ? self::ANON_NAME : $name,
|
||||
'name' => $pub,
|
||||
'amount_minor' => (int) $r['base_minor'],
|
||||
'amount_display' => self::money( (int) $r['base_minor'], $cur ),
|
||||
'amount_display' => $disp,
|
||||
'currency' => $cur,
|
||||
'message' => (string) ( $r['message'] ?? '' ),
|
||||
'bonuses' => self::bonuses( $r['bonuses'] ?? array() ),
|
||||
'actions' => self::actionEvents( $r['actions'] ?? array() ),
|
||||
'tiers' => self::tierEvents( $r['tiers'] ?? array() ),
|
||||
'media' => $mediaFor ? $mediaFor( $r, $pub, $disp ) : null,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -194,6 +242,27 @@ final class Payloads {
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tiers a donation unlocked, for the "TIER UNLOCKED" pill: [ {title} ]. At most 5, titles capped at 80 chars, blanks dropped.
|
||||
*
|
||||
* @param mixed $events
|
||||
* @return array<int,array{title:string}>
|
||||
*/
|
||||
public static function tierEvents( mixed $events ): array {
|
||||
$out = array();
|
||||
foreach ( is_array( $events ) ? $events : array() as $e ) {
|
||||
$title = self::text( is_array( $e ) ? ( $e['title'] ?? '' ) : '', 80 );
|
||||
if ( '' === $title ) {
|
||||
continue;
|
||||
}
|
||||
$out[] = array( 'title' => $title );
|
||||
if ( count( $out ) >= 5 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The on-stream reward menu for the active goal. Empty list means "render nothing".
|
||||
*
|
||||
@@ -223,10 +292,10 @@ final class Payloads {
|
||||
return array( 'active' => (bool) $list, 'currency' => $cur, 'actions' => $list );
|
||||
}
|
||||
|
||||
/** Strong ETag over the payload, ignoring the volatile server_now so unchanged data yields 304s. */
|
||||
public static function etag( array $payload ): string {
|
||||
/** Strong ETag over the payload (plus an optional salt, e.g. a hash of media definitions), ignoring the volatile server_now so unchanged data yields 304s. */
|
||||
public static function etag( array $payload, string $salt = '' ): string {
|
||||
unset( $payload['server_now'] );
|
||||
return '"' . md5( (string) json_encode( $payload, JSON_UNESCAPED_UNICODE ) ) . '"';
|
||||
return '"' . md5( $salt . (string) json_encode( $payload, JSON_UNESCAPED_UNICODE ) ) . '"';
|
||||
}
|
||||
|
||||
private static function toEpoch( ?string $v ): ?int {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
use StreamGoals\Core\GoalTargetPolicy;
|
||||
use StreamGoals\Tiers\TierPolicy;
|
||||
|
||||
/**
|
||||
* Pure, WordPress-free public progress view for the donate form / [streamgoals_progress] / GET /progress.
|
||||
* Numbers come from Payloads::goal() so they match the overlay exactly. Public-safe fields only (no donor data).
|
||||
*/
|
||||
final class Progress {
|
||||
|
||||
/** Parse a shortcode yes/no attribute. Unknown or empty values fall back to $default. */
|
||||
public static function flag( mixed $raw, bool $default ): bool {
|
||||
if ( is_bool( $raw ) ) {
|
||||
return $raw;
|
||||
}
|
||||
if ( is_array( $raw ) || null === $raw ) {
|
||||
return $default;
|
||||
}
|
||||
$v = strtolower( trim( (string) $raw ) );
|
||||
if ( in_array( $v, array( 'yes', 'true', '1', 'on' ), true ) ) {
|
||||
return true;
|
||||
}
|
||||
if ( in_array( $v, array( 'no', 'false', '0', 'off' ), true ) ) {
|
||||
return false;
|
||||
}
|
||||
return $default;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $goal sg_goals row
|
||||
* @param array<int,array<string,mixed>>|null $tiers raw sg_goal_tiers rows
|
||||
* @return array{goal_id:int,title:string,currency:string,raised_minor:int,target_minor:int,percent:int,raised_display:string,target_display:string,reached:bool,tier:?array}
|
||||
*/
|
||||
public static function payload( array $goal, int $raised, ?array $tiers = null ): array {
|
||||
$g = Payloads::goal( $goal, $raised, $tiers ?: null );
|
||||
$tier = null;
|
||||
$reached = GoalTargetPolicy::isClosedAtTarget( $goal );
|
||||
if ( isset( $g['tiers'] ) ) {
|
||||
$cur = $g['tiers']['current'];
|
||||
if ( null !== $cur ) {
|
||||
$tier = array(
|
||||
'index' => (int) $g['tiers']['index'],
|
||||
'count' => (int) $g['tiers']['count'],
|
||||
'title' => (string) $cur['title'],
|
||||
'target_minor' => (int) $cur['target_minor'],
|
||||
'target_display' => (string) $cur['target_display'],
|
||||
);
|
||||
}
|
||||
$reached = $reached || ! empty( $g['tiers']['all_reached'] );
|
||||
} else {
|
||||
$reached = $reached || ( $g['target_minor'] > 0 && $g['raised_minor'] >= $g['target_minor'] );
|
||||
}
|
||||
return array(
|
||||
'goal_id' => (int) ( $goal['id'] ?? 0 ),
|
||||
'title' => $g['title'],
|
||||
'currency' => $g['currency'],
|
||||
'raised_minor' => $g['raised_minor'],
|
||||
'target_minor' => $g['target_minor'],
|
||||
'percent' => $reached ? 100 : $g['percent'],
|
||||
'raised_display' => $g['raised_display'],
|
||||
'target_display' => $g['target_display'],
|
||||
'reached' => $reached,
|
||||
'tier' => $tier,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-rendered bar (the JS updates this same markup in place). Labels are already translated.
|
||||
*
|
||||
* @param array<string,string> $labels reached, of (%1$s raised, %2$s target), tier (%1$s name, %2$s target), label (%s title)
|
||||
*/
|
||||
public static function html( array $p, array $labels ): string {
|
||||
$e = static fn( string $s ): string => htmlspecialchars( $s, ENT_QUOTES, 'UTF-8' );
|
||||
$pct = max( 0, min( 100, (int) $p['percent'] ) );
|
||||
$sub = static fn( string $tpl, array $v ): string => (string) preg_replace_callback( '/%(\d)\$s/', static fn( array $m ): string => $v[ (int) $m[1] - 1 ] ?? '', $tpl );
|
||||
$of = $sub( $labels['of'] ?? '%1$s / %2$s', array( $p['raised_display'], $p['target_display'] ) );
|
||||
$out = '<div class="sg-progress' . ( $p['reached'] ? ' sg-progress-reached' : '' ) . '" data-goal="' . (int) $p['goal_id'] . '">';
|
||||
$out .= '<div class="sg-progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="' . $pct . '"'
|
||||
. ' aria-valuetext="' . $e( $p['reached'] ? ( $labels['reached'] ?? '' ) : $of . ' (' . $pct . '%)' ) . '"'
|
||||
. ' aria-label="' . $e( str_replace( '%s', (string) $p['title'], $labels['label'] ?? '%s' ) ) . '">'
|
||||
. '<span class="sg-progress-fill" style="width:' . $pct . '%"></span></div>';
|
||||
$out .= '<div class="sg-progress-text"><span class="sg-progress-amounts">' . $e( $of ) . '</span> <span class="sg-progress-pct">' . $pct . '%</span></div>';
|
||||
$out .= '<p class="sg-progress-tier"' . ( $p['tier'] ? '' : ' hidden' ) . '>'
|
||||
. ( $p['tier'] ? $e( $sub( $labels['tier'] ?? '%1$s (%2$s)', array( $p['tier']['title'], $p['tier']['target_display'] ) ) ) : '' ) . '</p>';
|
||||
$out .= '<p class="sg-progress-done"' . ( $p['reached'] ? '' : ' hidden' ) . '>' . $e( $p['reached'] ? ( $labels['reached'] ?? '' ) : '' ) . '</p>';
|
||||
return $out . '</div>';
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** Optional capability: goal tiers (milestones). Sources without it behave as if no goal had tiers. */
|
||||
interface TiersSource {
|
||||
|
||||
/**
|
||||
* Tiers of a goal ordered by target ascending. Rows with keys id, target_minor, title, description, reached_at.
|
||||
*
|
||||
* @return array<int,array<string,mixed>>
|
||||
*/
|
||||
public function tiersFor( int $goalId ): array;
|
||||
|
||||
/**
|
||||
* Tiers unlocked by each donation, ONE lookup for the whole page: donation id => [ {title} ].
|
||||
*
|
||||
* @param int[] $donationIds
|
||||
* @return array<int,array<int,array<string,mixed>>>
|
||||
*/
|
||||
public function tiersReachedFor( array $donationIds ): array;
|
||||
}
|
||||
@@ -4,7 +4,10 @@ declare( strict_types=1 );
|
||||
namespace StreamGoals\Overlay;
|
||||
|
||||
/** $wpdb adapter reading sg_goals, sg_donations, sg_state, sg_rules directly. */
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource {
|
||||
final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource, TiersSource {
|
||||
|
||||
/** @var array<int,?array{url:string,mime:string,v:int,modified:string}> */
|
||||
private array $attachments = array();
|
||||
|
||||
private function t( string $name ): string {
|
||||
global $wpdb;
|
||||
@@ -117,9 +120,57 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function tiersFor( int $goalId ): array {
|
||||
return ( new \StreamGoals\Tiers\TierRepository( $GLOBALS['wpdb'] ) )->forGoal( $goalId );
|
||||
}
|
||||
|
||||
public function tiersReachedFor( array $donationIds ): array {
|
||||
return ( new \StreamGoals\Tiers\TierRepository( $GLOBALS['wpdb'] ) )->reachedByDonation( $donationIds );
|
||||
}
|
||||
|
||||
public function alertDefs(): array {
|
||||
return ( new \StreamGoals\Alerts\DefRepository( $GLOBALS['wpdb'] ) )->enabled();
|
||||
}
|
||||
|
||||
public function triggeredActionsFor( array $donationIds ): array {
|
||||
global $wpdb;
|
||||
$ids = array_values( array_unique( array_filter( array_map( 'intval', $donationIds ), static fn( $i ) => $i > 0 ) ) );
|
||||
if ( ! $ids ) {
|
||||
return array();
|
||||
}
|
||||
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT e.donation_id, e.action_id, e.title, COALESCE(a.amount_minor,0) AS amount_minor FROM {$this->t('action_events')} e
|
||||
LEFT JOIN {$this->t('actions')} a ON a.id = e.action_id WHERE e.donation_id IN ($in) ORDER BY e.id ASC",
|
||||
$ids
|
||||
), ARRAY_A );
|
||||
$out = array();
|
||||
foreach ( (array) $rows as $row ) {
|
||||
$out[ (int) $row['donation_id'] ][] = array( 'action_id' => (int) $row['action_id'], 'amount_minor' => (int) $row['amount_minor'], 'title' => (string) $row['title'] );
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
public function attachment( int $id ): ?array {
|
||||
if ( array_key_exists( $id, $this->attachments ) ) {
|
||||
return $this->attachments[ $id ];
|
||||
}
|
||||
$out = null;
|
||||
if ( $id > 0 && 'attachment' === get_post_type( $id ) ) {
|
||||
$mime = (string) get_post_mime_type( $id );
|
||||
$url = wp_get_attachment_url( $id );
|
||||
if ( \StreamGoals\Alerts\Media::isAllowed( $mime ) && is_string( $url ) && '' !== $url ) {
|
||||
$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;
|
||||
}
|
||||
|
||||
public function donations( ?int $sinceId, int $limit ): array {
|
||||
global $wpdb;
|
||||
$cols = 'id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
|
||||
$cols = 'id, goal_id, base_minor, currency, donor_name, is_anonymous, message, status, moderation';
|
||||
$where = "status = 'completed' AND moderation = 'approved'";
|
||||
if ( null === $sinceId ) {
|
||||
$rows = $wpdb->get_results( "SELECT $cols FROM {$this->t('donations')} WHERE $where ORDER BY id DESC LIMIT 1", ARRAY_A );
|
||||
@@ -136,7 +187,7 @@ final class WpdbDataSource implements OverlayDataSource, RecentDonationsSource,
|
||||
public function recentDonations( int $limit ): array {
|
||||
global $wpdb;
|
||||
$rows = $wpdb->get_results( $wpdb->prepare(
|
||||
"SELECT id, base_minor, currency, donor_name, is_anonymous, message, status, moderation FROM {$this->t('donations')}
|
||||
"SELECT id, goal_id, base_minor, currency, donor_name, is_anonymous, message, status, moderation FROM {$this->t('donations')}
|
||||
WHERE status = 'completed' AND moderation = 'approved' ORDER BY id DESC LIMIT %d",
|
||||
max( 1, $limit )
|
||||
), ARRAY_A );
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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 ) {
|
||||
|
||||
@@ -60,9 +60,10 @@ final class DonationStore {
|
||||
'message' => $v['message'],
|
||||
'status' => 'pending',
|
||||
'moderation' => $v['moderation'],
|
||||
'moderation_flags' => (string) ( $v['moderation_flags'] ?? '' ),
|
||||
'created_at' => gmdate( 'Y-m-d H:i:s' ),
|
||||
),
|
||||
array( '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s' )
|
||||
array( '%d', '%s', '%d', '%d', '%d', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s' )
|
||||
);
|
||||
return $ok ? (int) $wpdb->insert_id : 0;
|
||||
}
|
||||
@@ -84,21 +85,98 @@ final class DonationStore {
|
||||
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 );
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run every side effect of a completed donation (rules/timer/counter, rewards, tiers, end-at-target) and, only if ALL of
|
||||
* them finished without error, stamp sg_donations.effects_applied_at. Never throws. Every step is idempotent, so this is
|
||||
* also what Maintenance::reconcile_effects() replays for a donation whose request died after mark_completed().
|
||||
*
|
||||
* @return bool True when the donation is (now) marked as fully applied.
|
||||
*/
|
||||
public static function notify_applied( int $id ): bool {
|
||||
$ok = self::call_engine( 'applyDonation', $id );
|
||||
// Donation actions (rewards). Not under the goal lock: events are idempotent via a UNIQUE key. Never throws.
|
||||
if ( ! \StreamGoals\Actions\Recorder::forDonation( $id ) ) {
|
||||
$ok = false;
|
||||
}
|
||||
// Goal tiers: unlock every tier this donation reaches. MUST run before the close-at-target check below
|
||||
// (the final tier's target is the goal target). Own try/catch; never throws, never delays a capture.
|
||||
if ( null === \StreamGoals\Tiers\Recorder::forDonationChecked( $id ) ) {
|
||||
$ok = false;
|
||||
}
|
||||
if ( ! self::close_goal_if_target_reached( $id ) ) {
|
||||
$ok = false;
|
||||
}
|
||||
return $ok && self::mark_effects_applied( $id );
|
||||
}
|
||||
|
||||
/** Stamp "side effects applied" once. Only a completed row with a NULL stamp is touched (first stamp wins). */
|
||||
public static function mark_effects_applied( int $id ): bool {
|
||||
global $wpdb;
|
||||
$n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET effects_applied_at = %s WHERE id = %d AND status = 'completed' AND effects_applied_at IS NULL", gmdate( 'Y-m-d H:i:s' ), $id ) );
|
||||
return false !== $n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Completed donations whose side effects were never confirmed: completed, effects_applied_at NULL, a real goal
|
||||
* (test rows use goal_id 0), created between $notBefore and $notAfter (UTC 'Y-m-d H:i:s'; the lower bound keeps a
|
||||
* permanently failing row from being retried forever, the upper bound leaves in-flight requests alone). Oldest first.
|
||||
*
|
||||
* @return int[]
|
||||
*/
|
||||
public static function unapplied_completed_ids( string $notAfter, string $notBefore, int $limit ): array {
|
||||
global $wpdb;
|
||||
$ids = $wpdb->get_col( $wpdb->prepare(
|
||||
'SELECT id FROM ' . self::t( 'donations' ) . " WHERE status = 'completed' AND effects_applied_at IS NULL AND goal_id > 0 AND created_at < %s AND created_at >= %s ORDER BY id ASC LIMIT %d",
|
||||
$notAfter,
|
||||
$notBefore,
|
||||
max( 1, $limit )
|
||||
) );
|
||||
return array_map( 'intval', (array) $ids );
|
||||
}
|
||||
|
||||
/**
|
||||
* "End at target": runs after the donation is already completed and counted, so it can never refuse or
|
||||
* undo a capture. Failures are logged and swallowed. Idempotent (atomic UPDATE ... WHERE status='active').
|
||||
*
|
||||
* @return bool False when the check failed.
|
||||
*/
|
||||
public static function close_goal_if_target_reached( int $donationId ): bool {
|
||||
try {
|
||||
\StreamGoals\Actions\Recorder::forDonation( $id );
|
||||
$row = self::find( $donationId );
|
||||
if ( $row && (int) $row->goal_id > 0 ) {
|
||||
( new \StreamGoals\Core\GoalRepository() )->closeIfTargetReached( (int) $row->goal_id );
|
||||
}
|
||||
return true;
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: Recorder failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
error_log( 'StreamGoals: end-at-target check failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function call_engine( string $method, int $id ): void {
|
||||
/** Goals closed because they reached their target (newest first), for the donor-facing "goal reached" message. @return array[] */
|
||||
public static function reached_goals(): array {
|
||||
global $wpdb;
|
||||
return (array) $wpdb->get_results( 'SELECT * FROM ' . self::t( 'goals' ) . " WHERE status = 'complete' AND close_at_target = 1 ORDER BY id DESC LIMIT 20", ARRAY_A );
|
||||
}
|
||||
|
||||
private static function call_engine( string $method, int $id ): bool {
|
||||
$row = self::find( $id );
|
||||
if ( ! $row ) {
|
||||
return;
|
||||
return false; // vanished row: nothing to apply, and never claim success
|
||||
}
|
||||
try {
|
||||
$donation = \StreamGoals\Core\DonationRepository::toDonation( (array) $row );
|
||||
@@ -108,8 +186,10 @@ final class DonationStore {
|
||||
\StreamGoals\Rules\Engine::default()->$method( $donation );
|
||||
}
|
||||
);
|
||||
return true;
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: Engine::' . $method . ' failed for donation ' . $id . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ final class OrderValidator {
|
||||
* @param array $input Raw client params (goal_id, amount, display_name, anonymous, message, cover_fees).
|
||||
* @param array $goal sg_goals row as array (id, currency, status, starts_at, ends_at).
|
||||
* @param array $settings Settings::all()-shaped array.
|
||||
* @return array{goal_id:int,currency:string,base_minor:int,fee_minor:int,total_minor:int,donor_name:string,is_anonymous:bool,message:string,cover_fees:bool,moderation:string}
|
||||
* @return array{goal_id:int,currency:string,base_minor:int,fee_minor:int,total_minor:int,donor_name:string,is_anonymous:bool,message:string,cover_fees:bool,moderation:string,moderation_flags:string}
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public static function validate( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array {
|
||||
@@ -59,9 +59,20 @@ final class OrderValidator {
|
||||
}
|
||||
|
||||
// Mask profanity before anything is stored (same-length masking, so length checks above still hold).
|
||||
$filter = new ProfanityFilter( $settings );
|
||||
$name = $filter->filter( $name );
|
||||
$message = $filter->filter( $message );
|
||||
// A donor name that trips the filter is stored masked AND held for moderation (the donation still completes
|
||||
// and counts). Anonymous names were blanked above, so they can never flag.
|
||||
$filter = new ProfanityFilter( $settings );
|
||||
$nameFlagged = '' !== $name && $filter->matches( $name );
|
||||
$name = $filter->filter( $name );
|
||||
$message = $filter->filter( $message );
|
||||
$msgHeld = ! empty( $settings['moderate_messages'] ) && '' !== $message;
|
||||
$flags = array();
|
||||
if ( $nameFlagged ) {
|
||||
$flags[] = 'name';
|
||||
}
|
||||
if ( $msgHeld ) {
|
||||
$flags[] = 'message';
|
||||
}
|
||||
|
||||
return array(
|
||||
'goal_id' => (int) $goal['id'],
|
||||
@@ -73,7 +84,8 @@ final class OrderValidator {
|
||||
'is_anonymous' => $anon,
|
||||
'message' => $message,
|
||||
'cover_fees' => $cover,
|
||||
'moderation' => ( ! empty( $settings['moderate_messages'] ) && '' !== $message ) ? 'pending' : 'approved',
|
||||
'moderation' => $flags ? 'pending' : 'approved',
|
||||
'moderation_flags' => implode( ',', $flags ), // '', 'name', 'message' or 'name,message' (why it is held)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -84,6 +96,9 @@ final class OrderValidator {
|
||||
* @throws ValidationException
|
||||
*/
|
||||
public static function quote( array $input, array $goal, array $settings, FeeCalculator $fees, int $nowTs ): array {
|
||||
if ( 'complete' === ( $goal['status'] ?? '' ) ) {
|
||||
throw new ValidationException( 'goal_inactive', 'This goal is closed and no longer accepting donations. Thank you for your support!', 409 );
|
||||
}
|
||||
if ( ! self::goalIsOpen( $goal, $nowTs ) ) {
|
||||
throw new ValidationException( 'goal_inactive', 'This goal is not accepting donations.', 409 );
|
||||
}
|
||||
|
||||
@@ -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 );
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -3,14 +3,17 @@ declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Rest;
|
||||
|
||||
use StreamGoals\Core\GoalTargetPolicy;
|
||||
use StreamGoals\Core\Money;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Progress;
|
||||
use StreamGoals\PayPal\CaptureFinalizer;
|
||||
use StreamGoals\PayPal\Client;
|
||||
use StreamGoals\PayPal\DonationStore;
|
||||
use StreamGoals\PayPal\OrderValidator;
|
||||
use StreamGoals\PayPal\PayPalException;
|
||||
use StreamGoals\PayPal\RateLimiter;
|
||||
use StreamGoals\PayPal\RequestId;
|
||||
use StreamGoals\PayPal\ValidationException;
|
||||
use StreamGoals\PayPal\WpCache;
|
||||
|
||||
@@ -19,9 +22,13 @@ 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' ) );
|
||||
add_shortcode( 'streamgoals_progress', array( self::class, 'progress_shortcode' ) );
|
||||
}
|
||||
|
||||
public static function routes(): void {
|
||||
@@ -52,14 +59,44 @@ final class DonateController {
|
||||
'permission_callback' => '__return_true',
|
||||
)
|
||||
);
|
||||
register_rest_route(
|
||||
self::NS,
|
||||
'/progress',
|
||||
array(
|
||||
'methods' => 'GET',
|
||||
'callback' => array( self::class, 'progress_route' ),
|
||||
'permission_callback' => '__return_true',
|
||||
'args' => array( 'goal' => array( 'sanitize_callback' => 'absint' ) ),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- REST */
|
||||
|
||||
/** Public, read-only totals for the progress bar. Whitelisted goal figures only; never donor data. */
|
||||
public static function progress_route( \WP_REST_Request $req ) {
|
||||
if ( $limited = self::limit( 'progress', 60, 60 ) ) {
|
||||
return $limited;
|
||||
}
|
||||
$goal = DonationStore::goal( (int) $req->get_param( 'goal' ) );
|
||||
if ( ! $goal || ! in_array( (string) $goal['status'], array( 'active', 'complete' ), true ) ) {
|
||||
return new \WP_Error( 'sg_goal_not_found', __( 'Goal not found.', 'streamgoals-donate' ), array( 'status' => 404 ) );
|
||||
}
|
||||
$res = rest_ensure_response( self::progress_for( $goal ) );
|
||||
// Short shared cache lets a CDN collapse bursts; the page JS adds a cache-busting parameter after a donation.
|
||||
$res->header( 'Cache-Control', 'public, max-age=10, s-maxage=10' );
|
||||
return $res;
|
||||
}
|
||||
|
||||
public static function create_order( \WP_REST_Request $req ) {
|
||||
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 ) );
|
||||
@@ -75,7 +112,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
|
||||
@@ -103,7 +140,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 );
|
||||
@@ -119,7 +156,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.
|
||||
@@ -148,8 +186,9 @@ final class DonateController {
|
||||
/* ----------------------------------------------------------- Shortcode */
|
||||
|
||||
public static function shortcode( $atts ): string {
|
||||
$atts = shortcode_atts( array( 'goal' => '' ), (array) $atts, 'streamgoals_donate' );
|
||||
$atts = shortcode_atts( array( 'goal' => '', 'show_progress' => 'yes' ), (array) $atts, 'streamgoals_donate' );
|
||||
$pinned = (int) $atts['goal'];
|
||||
$showP = Progress::flag( $atts['show_progress'], true );
|
||||
$s = Settings::all();
|
||||
if ( '' === (string) $s['paypal_client_id'] ) {
|
||||
return '<p class="sg-donate-unavailable">' . esc_html__( 'Donations are not available right now.', 'streamgoals-donate' ) . '</p>';
|
||||
@@ -161,15 +200,23 @@ final class DonateController {
|
||||
if ( $pinned && (int) $g['id'] !== $pinned ) {
|
||||
continue;
|
||||
}
|
||||
$goals[] = array(
|
||||
$next = self::next_unlock( $g );
|
||||
$goals[] = ( null === $next ? array() : array( 'nextUnlock' => $next ) ) + array(
|
||||
'id' => (int) $g['id'],
|
||||
'title' => (string) $g['title'],
|
||||
'currency' => strtoupper( (string) $g['currency'] ),
|
||||
'exp' => Money::exponent( (string) $g['currency'] ),
|
||||
'actions' => $actions[ (int) $g['id'] ] ?? array(),
|
||||
);
|
||||
) + ( $showP ? array( 'progress' => self::progress_for( $g ) ) : array() );
|
||||
}
|
||||
if ( ! $goals ) {
|
||||
$reached = $pinned ? DonationStore::goal( $pinned ) : null;
|
||||
$reached = $pinned ? ( $reached && GoalTargetPolicy::isClosedAtTarget( $reached ) ) : (bool) DonationStore::reached_goals();
|
||||
if ( $reached ) {
|
||||
$rg = $pinned ? DonationStore::goal( $pinned ) : ( DonationStore::reached_goals()[0] ?? null );
|
||||
$bar = ( $showP && $rg ) ? self::progress_markup( self::progress_for( $rg ) ) : '';
|
||||
return $bar . '<p class="sg-donate-unavailable sg-donate-reached">' . esc_html__( 'This goal has been reached - thank you for your support!', 'streamgoals-donate' ) . '</p>';
|
||||
}
|
||||
return '<p class="sg-donate-unavailable">' . esc_html__( 'There is no active goal to donate to right now.', 'streamgoals-donate' ) . '</p>';
|
||||
}
|
||||
|
||||
@@ -181,6 +228,7 @@ final class DonateController {
|
||||
'policy' => (string) $s['anonymity_policy'],
|
||||
'minMinor' => \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ),
|
||||
'messageMax' => min( 500, (int) $s['message_max_length'] ),
|
||||
'notice' => (string) ( $s['donation_notice'] ?? '' ),
|
||||
'disableFunding' => array_values( array_filter( array( empty( $s['funding_paylater'] ) ? 'paylater' : '', empty( $s['funding_card'] ) ? 'card' : '' ) ) ),
|
||||
'goals' => $goals,
|
||||
'i18n' => array(
|
||||
@@ -200,6 +248,8 @@ final class DonateController {
|
||||
'customPlaceholder' => __( 'Other amount', 'streamgoals-donate' ),
|
||||
/* translators: %s: formatted amount, e.g. $5.00 */
|
||||
'everyLabel' => __( 'Every %s', 'streamgoals-donate' ),
|
||||
/* translators: 1: item/unlock title, 2: formatted amount still needed, e.g. $106.00 */
|
||||
'nextUnlock' => __( 'Next unlock: %1$s — %2$s to go', 'streamgoals-donate' ),
|
||||
'actionsHint' => __( 'Pick a reward, or enter your own amount below.', 'streamgoals-donate' ),
|
||||
/* translators: %s: formatted minimum amount, e.g. $1.00 */
|
||||
'minHint' => __( 'Minimum donation: %s', 'streamgoals-donate' ),
|
||||
@@ -211,11 +261,89 @@ final class DonateController {
|
||||
);
|
||||
wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsDonate=' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' );
|
||||
|
||||
return '<div class="sg-donate" data-goal="' . esc_attr( (string) $pinned ) . '"></div>';
|
||||
self::enqueue_progress();
|
||||
$first = $showP ? $goals[0]['progress'] : null;
|
||||
return '<div class="sg-donate" data-goal="' . esc_attr( (string) $pinned ) . '"' . ( $showP ? ' data-progress="1"' : '' ) . '>'
|
||||
. ( $first ? self::progress_markup( $first ) : '' ) . '</div>';
|
||||
}
|
||||
|
||||
/** [streamgoals_progress goal=""]: the same bar without the form. Server-rendered; JS refreshes it. */
|
||||
public static function progress_shortcode( $atts ): string {
|
||||
$atts = shortcode_atts( array( 'goal' => '' ), (array) $atts, 'streamgoals_progress' );
|
||||
$id = (int) $atts['goal'];
|
||||
$goal = $id ? DonationStore::goal( $id ) : ( DonationStore::active_goals()[0] ?? ( DonationStore::reached_goals()[0] ?? null ) );
|
||||
if ( ! $goal || ! in_array( (string) $goal['status'], array( 'active', 'complete' ), true ) ) {
|
||||
return '';
|
||||
}
|
||||
self::enqueue_progress();
|
||||
return '<div class="sg-donate sg-progress-only">' . self::progress_markup( self::progress_for( $goal ) ) . '</div>';
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- Helpers */
|
||||
|
||||
/** @return array<string,mixed> Progress::payload() for a goal row (same raised basis and tiers as the overlay). */
|
||||
private static function progress_for( array $goal ): array {
|
||||
global $wpdb;
|
||||
$id = (int) $goal['id'];
|
||||
$tiers = array();
|
||||
try {
|
||||
$tiers = ( new \StreamGoals\Tiers\TierRepository( $wpdb ) )->forGoal( $id );
|
||||
} catch ( \Throwable $e ) {
|
||||
$tiers = array();
|
||||
}
|
||||
return Progress::payload( $goal, ( new \StreamGoals\Overlay\WpdbDataSource() )->raisedMinor( $goal ), $tiers ?: null );
|
||||
}
|
||||
|
||||
private static function progress_i18n(): array {
|
||||
return array(
|
||||
'reached' => __( 'Goal reached', 'streamgoals-donate' ),
|
||||
/* translators: 1: formatted amount raised, 2: formatted target */
|
||||
'of' => __( '%1$s of %2$s', 'streamgoals-donate' ),
|
||||
/* translators: 1: current tier name, 2: formatted tier target */
|
||||
'tier' => __( 'Current tier: %1$s (target %2$s)', 'streamgoals-donate' ),
|
||||
/* translators: %s: goal title */
|
||||
'label' => __( 'Progress towards %s', 'streamgoals-donate' ),
|
||||
);
|
||||
}
|
||||
|
||||
private static function progress_markup( array $p ): string {
|
||||
return Progress::html( $p, self::progress_i18n() );
|
||||
}
|
||||
|
||||
/** Enqueue assets and the (once per page) config the bar's JS needs. */
|
||||
private static function enqueue_progress(): void {
|
||||
static $done = false;
|
||||
wp_enqueue_style( 'streamgoals-donate', STREAMGOALS_URL . 'assets/donate/donate.css', array(), STREAMGOALS_VERSION );
|
||||
wp_enqueue_script( 'streamgoals-donate', STREAMGOALS_URL . 'assets/donate/donate.js', array(), STREAMGOALS_VERSION, true );
|
||||
if ( $done ) {
|
||||
return;
|
||||
}
|
||||
$done = true;
|
||||
$cfg = array( 'restUrl' => esc_url_raw( rest_url( self::NS ) ), 'i18n' => self::progress_i18n(), 'pollMs' => 30000 );
|
||||
wp_add_inline_script( 'streamgoals-donate', 'window.StreamGoalsProgress=' . wp_json_encode( $cfg, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';', 'before' );
|
||||
}
|
||||
|
||||
/**
|
||||
* "Next unlock" hint for a tiered goal: the current (first unreached) tier's title and the amount still needed, in minor units.
|
||||
* Null for goals without tiers or with every tier reached. Computed when the page renders.
|
||||
*
|
||||
* @return array{title:string,remaining_minor:int}|null
|
||||
*/
|
||||
private static function next_unlock( array $goal ): ?array {
|
||||
try {
|
||||
global $wpdb;
|
||||
$tiers = ( new \StreamGoals\Tiers\TierRepository( $wpdb ) )->forGoal( (int) $goal['id'] );
|
||||
$cur = $tiers ? \StreamGoals\Tiers\TierPolicy::currentTier( $tiers ) : null;
|
||||
if ( null === $cur ) {
|
||||
return null;
|
||||
}
|
||||
$raised = ( new \StreamGoals\Core\GoalRepository( $wpdb ) )->raised_minor( (int) $goal['id'] );
|
||||
return array( 'title' => (string) $cur['title'], 'remaining_minor' => max( 1, (int) $cur['target_minor'] - $raised ) );
|
||||
} catch ( \Throwable $e ) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Enabled actions per goal id (rows with goal_id 0 apply to every goal), at or above the effective minimum.
|
||||
* Public-safe fields only. One query; reads sg_actions directly.
|
||||
@@ -271,17 +399,32 @@ 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 ] ) ) {
|
||||
$server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) );
|
||||
}
|
||||
}
|
||||
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', '' ) );
|
||||
if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) {
|
||||
return null;
|
||||
}
|
||||
return new \WP_Error( 'sg_rate_limited', __( 'Too many requests. Please wait a moment.', 'streamgoals-donate' ), array( 'status' => 429 ) );
|
||||
$ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', 'auto' ), (array) apply_filters( 'streamgoals_cloudflare_ranges', array() ) );
|
||||
return \StreamGoals\Core\ClientIp::bucketKey( $ip );
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -49,13 +59,14 @@ final class OverlayController {
|
||||
}
|
||||
$since = $req->has_param( 'since' ) && '' !== (string) $req->get_param( 'since' ) ? absint( $req->get_param( 'since' ) ) : null;
|
||||
$recent = $req->has_param( 'recent' ) && 1 === absint( $req->get_param( 'recent' ) );
|
||||
$payload = ( new OverlayService( new WpdbDataSource() ) )->payload( (string) $req['widget'], time(), $since, $recent );
|
||||
$service = new OverlayService( new WpdbDataSource() );
|
||||
$payload = $service->payload( (string) $req['widget'], time(), $since, $recent );
|
||||
if ( null === $payload ) {
|
||||
return new \WP_Error( 'sg_not_found', 'Not found.', array( 'status' => 404 ) );
|
||||
}
|
||||
|
||||
$etag = Payloads::etag( $payload );
|
||||
$headers = array( 'ETag' => $etag, 'Cache-Control' => 'private, max-age=1, must-revalidate', 'X-Robots-Tag' => 'noindex' );
|
||||
$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' ) + 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 );
|
||||
|
||||
@@ -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 ) );
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tiers;
|
||||
|
||||
/** Unlocks the tiers a completed donation reaches. Runs BEFORE the "end at target" check. */
|
||||
final class Recorder {
|
||||
|
||||
/**
|
||||
* Never throws. Idempotent (atomic UPDATE ... WHERE reached_at IS NULL per tier). Test donations (goal_id 0) are skipped.
|
||||
*
|
||||
* @return int[] ids of the tiers this call unlocked.
|
||||
*/
|
||||
public static function forDonation( int $donationId ): array {
|
||||
return self::forDonationChecked( $donationId ) ?? array();
|
||||
}
|
||||
|
||||
/** Same as forDonation() but null (instead of an empty list) when something failed. Never throws. @return int[]|null */
|
||||
public static function forDonationChecked( int $donationId ): ?array {
|
||||
try {
|
||||
global $wpdb;
|
||||
$row = $wpdb->get_row( $wpdb->prepare( 'SELECT id, goal_id, status FROM ' . $wpdb->prefix . 'sg_donations WHERE id = %d', $donationId ), ARRAY_A );
|
||||
if ( ! is_array( $row ) || 'completed' !== ( $row['status'] ?? '' ) || (int) $row['goal_id'] <= 0 ) {
|
||||
return array();
|
||||
}
|
||||
$goalId = (int) $row['goal_id'];
|
||||
$repo = new TierRepository( $wpdb );
|
||||
if ( ! $repo->forGoal( $goalId ) ) {
|
||||
return array();
|
||||
}
|
||||
$raised = ( new \StreamGoals\Core\GoalRepository( $wpdb ) )->raised_minor( $goalId );
|
||||
return $repo->markReached( $goalId, $raised, $donationId );
|
||||
} catch ( \Throwable $e ) {
|
||||
error_log( 'StreamGoals: tier unlock failed for donation ' . $donationId . ': ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tiers;
|
||||
|
||||
/**
|
||||
* Pure rules for goal tiers (milestones). No WordPress / database access.
|
||||
* A tier row is an array with keys: id, target_minor, title, description, reached_at (null|string), reached_donation_id.
|
||||
*/
|
||||
final class TierPolicy {
|
||||
|
||||
public const TITLE_MAX = 120;
|
||||
public const DESC_MAX = 255;
|
||||
|
||||
/** Tiers ordered by target ascending (ties by id). Non-array entries are dropped. @return array[] */
|
||||
public static function sorted( array $tiers ): array {
|
||||
$tiers = array_values( array_filter( $tiers, 'is_array' ) );
|
||||
usort(
|
||||
$tiers,
|
||||
static fn( array $a, array $b ): int => ( (int) $a['target_minor'] <=> (int) $b['target_minor'] ) ?: ( (int) ( $a['id'] ?? 0 ) <=> (int) ( $b['id'] ?? 0 ) )
|
||||
);
|
||||
return $tiers;
|
||||
}
|
||||
|
||||
public static function isReached( array $tier ): bool {
|
||||
return ! empty( $tier['reached_at'] );
|
||||
}
|
||||
|
||||
/** The first tier (by target) that is not reached yet, or null (no tiers, or all reached). */
|
||||
public static function currentTier( array $tiers ): ?array {
|
||||
foreach ( self::sorted( $tiers ) as $t ) {
|
||||
if ( ! self::isReached( $t ) ) {
|
||||
return $t;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** True when there is at least one tier and every tier is reached. */
|
||||
public static function allReached( array $tiers ): bool {
|
||||
return $tiers && null === self::currentTier( $tiers );
|
||||
}
|
||||
|
||||
/** 1-based position of the current tier; when all are reached, the count; 0 without tiers. */
|
||||
public static function currentIndex( array $tiers ): int {
|
||||
$sorted = self::sorted( $tiers );
|
||||
foreach ( $sorted as $i => $t ) {
|
||||
if ( ! self::isReached( $t ) ) {
|
||||
return $i + 1;
|
||||
}
|
||||
}
|
||||
return count( $sorted );
|
||||
}
|
||||
|
||||
/** Start of the current tier's range: the previous tier's target (0 for the first / when none is current). */
|
||||
public static function floorMinor( array $tiers ): int {
|
||||
$prev = 0;
|
||||
foreach ( self::sorted( $tiers ) as $t ) {
|
||||
if ( ! self::isReached( $t ) ) {
|
||||
return $prev;
|
||||
}
|
||||
$prev = (int) $t['target_minor'];
|
||||
}
|
||||
return $prev; // all reached: the top tier's target
|
||||
}
|
||||
|
||||
/** Progress inside a tier, 0..100 (clamped). Below the floor = 0, at or above the target = 100. */
|
||||
public static function percent( int $raised, int $floor, int $target ): int {
|
||||
if ( $target <= $floor ) {
|
||||
return $raised >= $target && $target > 0 ? 100 : 0;
|
||||
}
|
||||
$p = intdiv( ( $raised - $floor ) * 100, $target - $floor );
|
||||
return max( 0, min( 100, $p ) );
|
||||
}
|
||||
|
||||
/** Percent within the current tier for the given tiers and raised total (100 when all reached, 0 without tiers). */
|
||||
public static function percentFor( array $tiers, int $raised ): int {
|
||||
$cur = self::currentTier( $tiers );
|
||||
if ( null === $cur ) {
|
||||
return $tiers ? 100 : 0;
|
||||
}
|
||||
return self::percent( $raised, self::floorMinor( $tiers ), (int) $cur['target_minor'] );
|
||||
}
|
||||
|
||||
/** Money still needed to reach the current tier (0 when none). */
|
||||
public static function remainingMinor( array $tiers, int $raised ): int {
|
||||
$cur = self::currentTier( $tiers );
|
||||
return null === $cur ? 0 : max( 0, (int) $cur['target_minor'] - $raised );
|
||||
}
|
||||
|
||||
/** Every unreached tier whose target is at or below the raised total, in target order. A big donation can unlock several. @return array[] */
|
||||
public static function newlyReached( array $tiers, int $raised ): array {
|
||||
$out = array();
|
||||
foreach ( self::sorted( $tiers ) as $t ) {
|
||||
if ( ! self::isReached( $t ) && (int) $t['target_minor'] <= $raised ) {
|
||||
$out[] = $t;
|
||||
}
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** The goal's target when it has tiers: the highest tier target (0 when no tiers). */
|
||||
public static function derivedGoalTarget( array $tiers ): int {
|
||||
$max = 0;
|
||||
foreach ( $tiers as $t ) {
|
||||
$max = max( $max, (int) ( $t['target_minor'] ?? 0 ) );
|
||||
}
|
||||
return $max;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate a tier form submission.
|
||||
*
|
||||
* @param array $tiers All tiers of the goal (including the one being edited).
|
||||
* @param int|null $editId Tier id when editing, null when adding.
|
||||
* @param int|null $target Parsed target in minor units (null = not a valid amount).
|
||||
* @param int $raised Goal raised total (minor units).
|
||||
* @param int $minMinor Settings::effectiveMin().
|
||||
* @return array{data:?array{target_minor:int,title:string,description:string},error:?string}
|
||||
*/
|
||||
public static function validate( array $tiers, ?int $editId, ?int $target, string $title, string $description, int $raised, int $minMinor, string $minLabel = '' ): array {
|
||||
$fail = static fn( string $m ): array => array( 'data' => null, 'error' => $m );
|
||||
$title = trim( $title );
|
||||
$desc = trim( $description );
|
||||
if ( '' === $title ) {
|
||||
return $fail( 'Please name what unlocks at this tier, for example "New microphone".' );
|
||||
}
|
||||
if ( self::len( $title ) > self::TITLE_MAX ) {
|
||||
return $fail( 'The title can be at most ' . self::TITLE_MAX . ' characters.' );
|
||||
}
|
||||
if ( self::len( $desc ) > self::DESC_MAX ) {
|
||||
return $fail( 'The description can be at most ' . self::DESC_MAX . ' characters.' );
|
||||
}
|
||||
$existing = null;
|
||||
if ( null !== $editId ) {
|
||||
foreach ( $tiers as $t ) {
|
||||
if ( (int) ( $t['id'] ?? 0 ) === $editId ) {
|
||||
$existing = $t;
|
||||
}
|
||||
}
|
||||
if ( null === $existing ) {
|
||||
return $fail( 'That tier no longer exists.' );
|
||||
}
|
||||
}
|
||||
if ( null !== $existing && self::isReached( $existing ) ) {
|
||||
// Reached tiers: the target is locked, only the text can change.
|
||||
return array( 'data' => array( 'target_minor' => (int) $existing['target_minor'], 'title' => $title, 'description' => $desc ), 'error' => null );
|
||||
}
|
||||
if ( null === $target || $target <= 0 ) {
|
||||
return $fail( 'Please enter a target greater than zero, for example 250.00.' );
|
||||
}
|
||||
if ( $target < $minMinor ) {
|
||||
return $fail( 'The target must be at least the minimum donation' . ( '' !== $minLabel ? ' (' . $minLabel . ')' : '' ) . '.' );
|
||||
}
|
||||
foreach ( $tiers as $t ) {
|
||||
if ( (int) ( $t['id'] ?? 0 ) !== (int) $editId && (int) $t['target_minor'] === $target ) {
|
||||
return $fail( 'Another tier already has that target. Each tier needs its own amount.' );
|
||||
}
|
||||
}
|
||||
$unchanged = null !== $existing && (int) $existing['target_minor'] === $target;
|
||||
if ( ! $unchanged && $target <= $raised ) {
|
||||
return $fail( 'This goal has already raised more than that, so the tier would unlock instantly. Choose a target above the current total.' );
|
||||
}
|
||||
return array( 'data' => array( 'target_minor' => $target, 'title' => $title, 'description' => $desc ), 'error' => null );
|
||||
}
|
||||
|
||||
/** Display status of a tier given the sorted list: 'reached' | 'current' | 'upcoming'. */
|
||||
public static function status( array $tiers, array $tier ): string {
|
||||
if ( self::isReached( $tier ) ) {
|
||||
return 'reached';
|
||||
}
|
||||
$cur = self::currentTier( $tiers );
|
||||
return $cur && (int) $cur['id'] === (int) $tier['id'] ? 'current' : 'upcoming';
|
||||
}
|
||||
|
||||
private static function len( string $s ): int {
|
||||
return function_exists( 'mb_strlen' ) ? mb_strlen( $s ) : strlen( $s );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tiers;
|
||||
|
||||
/** $wpdb access to sg_goal_tiers (and keeping sg_goals.target_minor in step). */
|
||||
final class TierRepository {
|
||||
|
||||
private object $db;
|
||||
|
||||
public function __construct( ?object $db = null ) {
|
||||
$this->db = $db ?? $GLOBALS['wpdb'];
|
||||
}
|
||||
|
||||
private function t( string $name ): string {
|
||||
return $this->db->prefix . 'sg_' . $name;
|
||||
}
|
||||
|
||||
/** @return array{id:int,goal_id:int,target_minor:int,title:string,description:string,reached_at:?string,reached_donation_id:?int,created_at:string} */
|
||||
private static function cast( array $r ): array {
|
||||
return array(
|
||||
'id' => (int) ( $r['id'] ?? 0 ),
|
||||
'goal_id' => (int) ( $r['goal_id'] ?? 0 ),
|
||||
'target_minor' => (int) ( $r['target_minor'] ?? 0 ),
|
||||
'title' => (string) ( $r['title'] ?? '' ),
|
||||
'description' => (string) ( $r['description'] ?? '' ),
|
||||
'reached_at' => isset( $r['reached_at'] ) && '' !== (string) $r['reached_at'] ? (string) $r['reached_at'] : null,
|
||||
'reached_donation_id' => isset( $r['reached_donation_id'] ) && null !== $r['reached_donation_id'] ? (int) $r['reached_donation_id'] : null,
|
||||
'created_at' => (string) ( $r['created_at'] ?? '' ),
|
||||
);
|
||||
}
|
||||
|
||||
/** Tiers of a goal ordered by target ascending. @return array[] */
|
||||
public function forGoal( int $goalId ): array {
|
||||
$rows = $this->db->get_results(
|
||||
$this->db->prepare( 'SELECT * FROM ' . $this->t( 'goal_tiers' ) . ' WHERE goal_id = %d ORDER BY target_minor ASC, id ASC', $goalId ),
|
||||
ARRAY_A
|
||||
);
|
||||
return array_map( array( self::class, 'cast' ), (array) $rows );
|
||||
}
|
||||
|
||||
public function find( int $id ): ?array {
|
||||
$row = $this->db->get_row( $this->db->prepare( 'SELECT * FROM ' . $this->t( 'goal_tiers' ) . ' WHERE id = %d', $id ), ARRAY_A );
|
||||
return $row ? self::cast( $row ) : null;
|
||||
}
|
||||
|
||||
/** Tier counts per goal id (one query) for the goals list. @return array<int,int> */
|
||||
public function countsByGoal(): array {
|
||||
$rows = $this->db->get_results( 'SELECT goal_id, COUNT(*) AS n FROM ' . $this->t( 'goal_tiers' ) . ' GROUP BY goal_id', ARRAY_A );
|
||||
$out = array();
|
||||
foreach ( (array) $rows as $r ) {
|
||||
$out[ (int) $r['goal_id'] ] = (int) $r['n'];
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/** @param array{target_minor:int,title:string,description:string} $d @return int new id (0 on failure, e.g. duplicate target) */
|
||||
public function create( int $goalId, array $d ): int {
|
||||
$ok = $this->db->insert(
|
||||
$this->t( 'goal_tiers' ),
|
||||
array(
|
||||
'goal_id' => $goalId,
|
||||
'target_minor' => (int) $d['target_minor'],
|
||||
'title' => (string) $d['title'],
|
||||
'description' => (string) $d['description'],
|
||||
'created_at' => gmdate( 'Y-m-d H:i:s' ),
|
||||
),
|
||||
array( '%d', '%d', '%s', '%s', '%s' )
|
||||
);
|
||||
return $ok ? (int) $this->db->insert_id : 0;
|
||||
}
|
||||
|
||||
public function update( int $id, int $goalId, array $d ): void {
|
||||
$this->db->update(
|
||||
$this->t( 'goal_tiers' ),
|
||||
array( 'target_minor' => (int) $d['target_minor'], 'title' => (string) $d['title'], 'description' => (string) $d['description'] ),
|
||||
array( 'id' => $id, 'goal_id' => $goalId ),
|
||||
array( '%d', '%s', '%s' ),
|
||||
array( '%d', '%d' )
|
||||
);
|
||||
}
|
||||
|
||||
public function delete( int $id, int $goalId ): void {
|
||||
$this->db->delete( $this->t( 'goal_tiers' ), array( 'id' => $id, 'goal_id' => $goalId ), array( '%d', '%d' ) );
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark every unreached tier of the goal with target <= $raised as reached by $donationId. One atomic
|
||||
* UPDATE per tier (WHERE reached_at IS NULL): replays and concurrent callers cannot re-mark a tier.
|
||||
*
|
||||
* @return int[] ids of the tiers THIS call marked.
|
||||
*/
|
||||
public function markReached( int $goalId, int $raised, int $donationId ): array {
|
||||
$marked = array();
|
||||
if ( $goalId <= 0 || $donationId <= 0 ) {
|
||||
return $marked;
|
||||
}
|
||||
$now = gmdate( 'Y-m-d H:i:s' );
|
||||
foreach ( TierPolicy::newlyReached( $this->forGoal( $goalId ), $raised ) as $tier ) {
|
||||
$n = $this->db->query(
|
||||
$this->db->prepare(
|
||||
'UPDATE ' . $this->t( 'goal_tiers' ) . ' SET reached_at = %s, reached_donation_id = %d WHERE id = %d AND reached_at IS NULL',
|
||||
$now,
|
||||
$donationId,
|
||||
(int) $tier['id']
|
||||
)
|
||||
);
|
||||
if ( 1 === (int) $n ) {
|
||||
$marked[] = (int) $tier['id'];
|
||||
}
|
||||
}
|
||||
return $marked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tiers unlocked by each donation, one query for the whole page: donation id => [ {title}, ... ] in target order.
|
||||
*
|
||||
* @param int[] $donationIds
|
||||
* @return array<int,array<int,array{title:string}>>
|
||||
*/
|
||||
public function reachedByDonation( array $donationIds ): array {
|
||||
$ids = array_values( array_unique( array_filter( array_map( 'intval', $donationIds ), static fn( $i ) => $i > 0 ) ) );
|
||||
if ( ! $ids ) {
|
||||
return array();
|
||||
}
|
||||
$in = implode( ',', array_fill( 0, count( $ids ), '%d' ) );
|
||||
$rows = $this->db->get_results(
|
||||
$this->db->prepare( 'SELECT reached_donation_id, title FROM ' . $this->t( 'goal_tiers' ) . " WHERE reached_donation_id IN ($in) ORDER BY target_minor ASC, id ASC", ...$ids ),
|
||||
ARRAY_A
|
||||
);
|
||||
$out = array();
|
||||
foreach ( (array) $rows as $r ) {
|
||||
$out[ (int) $r['reached_donation_id'] ][] = array( 'title' => (string) $r['title'] );
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep sg_goals.target_minor equal to the highest tier target. Leaves the goal untouched when it has no tiers.
|
||||
*
|
||||
* @return bool true when the goal row was set from tiers.
|
||||
*/
|
||||
public function syncGoalTarget( int $goalId ): bool {
|
||||
$max = $this->db->get_var( $this->db->prepare( 'SELECT MAX(target_minor) FROM ' . $this->t( 'goal_tiers' ) . ' WHERE goal_id = %d', $goalId ) );
|
||||
if ( null === $max || (int) $max <= 0 ) {
|
||||
return false;
|
||||
}
|
||||
$this->db->query( $this->db->prepare( 'UPDATE ' . $this->t( 'goals' ) . ' SET target_minor = %d WHERE id = %d', (int) $max, $goalId ) );
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\Csv;
|
||||
use StreamGoals\Admin\DonationsPage;
|
||||
use StreamGoals\Admin\Format;
|
||||
use StreamGoals\Admin\Input;
|
||||
use StreamGoals\Admin\RuleConfig;
|
||||
@@ -133,4 +134,11 @@ final class AdminLogicTest extends TestCase {
|
||||
$this->assertTrue( Format::isTest( array( 'paypal_order_id' => 'TEST-abc' ) ) );
|
||||
$this->assertFalse( Format::isTest( array( 'paypal_order_id' => '5O1234' ) ) );
|
||||
}
|
||||
|
||||
public function test_after_moderation_redirect_only_to_registered_page(): void {
|
||||
$this->assertSame( 'streamgoals-donations', DonationsPage::afterModerationPage( false, 0 ) );
|
||||
$this->assertSame( 'streamgoals-moderation', DonationsPage::afterModerationPage( false, 2 ) );
|
||||
$this->assertSame( 'streamgoals-moderation', DonationsPage::afterModerationPage( true, 0 ) );
|
||||
$this->assertSame( 'streamgoals-moderation', DonationsPage::afterModerationPage( true, 5 ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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 "x""', $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&"">', Admin::td( 'A&"', 'sg-actions' ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Alerts\DefInput;
|
||||
|
||||
final class AlertDefInputTest extends TestCase {
|
||||
|
||||
private function att(): callable {
|
||||
$files = array(
|
||||
10 => array( 'mime' => 'image/gif', 'size' => 1000 ),
|
||||
11 => array( 'mime' => 'video/mp4', 'size' => 30 * 1024 * 1024 ),
|
||||
12 => array( 'mime' => 'audio/mpeg', 'size' => 5000 ),
|
||||
13 => array( 'mime' => 'image/svg+xml', 'size' => 10 ),
|
||||
14 => array( 'mime' => 'text/html', 'size' => 10 ),
|
||||
15 => array( 'mime' => 'image/png', 'size' => 10 ),
|
||||
);
|
||||
return static fn( int $id ): ?array => $files[ $id ] ?? null;
|
||||
}
|
||||
|
||||
private function post( array $o = array() ): array {
|
||||
return $o + array( 'title' => 'Big', 'goal_id' => '0', 'trigger_type' => 'amount', 'amount' => '10.00', 'visual_id' => '10', 'sound_id' => '12',
|
||||
'volume' => '70', 'duration' => '8', 'message' => '{name} sent {amount}', 'sort' => '' );
|
||||
}
|
||||
|
||||
private function run_( array $post, int $min = 100 ): array {
|
||||
return DefInput::validate( $post, $min, 'USD', array( 3 ), array( 5 ), $this->att(), 40 );
|
||||
}
|
||||
|
||||
public function test_valid_amount_def(): void {
|
||||
$r = $this->run_( $this->post() );
|
||||
$this->assertNull( $r['error'] );
|
||||
$d = $r['data'];
|
||||
$this->assertSame( array( 0, 'amount', 1000, 0, 10, 'image', 12, 70, 8000, 40 ), array( $d['goal_id'], $d['trigger_type'], $d['min_minor'], $d['action_id'], $d['visual_id'], $d['visual_type'], $d['sound_id'], $d['volume'], $d['duration_ms'], $d['sort'] ) );
|
||||
$this->assertSame( array(), $r['warnings'] );
|
||||
}
|
||||
|
||||
public function test_valid_reward_def_ignores_amount(): void {
|
||||
$r = $this->run_( $this->post( array( 'trigger_type' => 'reward', 'action_id' => '5', 'amount' => '' ) ) );
|
||||
$this->assertNull( $r['error'] );
|
||||
$this->assertSame( array( 'reward', 0, 5 ), array( $r['data']['trigger_type'], $r['data']['min_minor'], $r['data']['action_id'] ) );
|
||||
}
|
||||
|
||||
public function test_reward_must_be_enabled_one(): void {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'trigger_type' => 'reward', 'action_id' => '6' ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'trigger_type' => 'reward', 'action_id' => '0' ) ) )['error'] );
|
||||
}
|
||||
|
||||
public function test_amount_must_reach_effective_minimum(): void {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'amount' => '0.50' ) ), 100 )['error'] );
|
||||
$this->assertNull( $this->run_( $this->post( array( 'amount' => '1.00' ) ), 100 )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'amount' => 'abc' ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'amount' => '' ) ) )['error'] );
|
||||
}
|
||||
|
||||
public function test_rejects_bad_mime_and_missing_attachments(): void {
|
||||
foreach ( array( 13, 14, 12, 99 ) as $bad ) {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'visual_id' => (string) $bad ) ) )['error'], "visual $bad" );
|
||||
}
|
||||
foreach ( array( 13, 10, 11, 99 ) as $bad ) {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'sound_id' => (string) $bad ) ) )['error'], "sound $bad" );
|
||||
}
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'visual_id' => 'x' ) ) )['error'] );
|
||||
}
|
||||
|
||||
public function test_media_is_optional_and_type_is_detected_server_side(): void {
|
||||
$r = $this->run_( $this->post( array( 'visual_id' => '0', 'sound_id' => '0', 'visual_type' => 'video' ) ) );
|
||||
$this->assertSame( array( 0, '', 0 ), array( $r['data']['visual_id'], $r['data']['visual_type'], $r['data']['sound_id'] ) );
|
||||
$r = $this->run_( $this->post( array( 'visual_id' => '15', 'visual_type' => 'video' ) ) );
|
||||
$this->assertSame( 'image', $r['data']['visual_type'], 'client-supplied type is ignored' );
|
||||
}
|
||||
|
||||
public function test_big_files_warn_but_do_not_block(): void {
|
||||
$r = $this->run_( $this->post( array( 'visual_id' => '11' ) ) );
|
||||
$this->assertNull( $r['error'] );
|
||||
$this->assertSame( 'video', $r['data']['visual_type'] );
|
||||
$this->assertCount( 1, $r['warnings'] );
|
||||
$this->assertStringContainsString( 'OBS', $r['warnings'][0] );
|
||||
}
|
||||
|
||||
public function test_numeric_ranges(): void {
|
||||
foreach ( array( '-1', '101', 'x' ) as $v ) {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'volume' => $v ) ) )['error'], "volume $v" );
|
||||
}
|
||||
$this->assertSame( 0, $this->run_( $this->post( array( 'volume' => '0' ) ) )['data']['volume'] );
|
||||
foreach ( array( '0', '61', '0.5', 'x', '' , '-2' ) as $v ) {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'duration' => $v ) ) )['error'], "duration '$v'" );
|
||||
}
|
||||
$this->assertSame( 60000, $this->run_( $this->post( array( 'duration' => '60' ) ) )['data']['duration_ms'] );
|
||||
$this->assertSame( 1000, $this->run_( $this->post( array( 'duration' => '1' ) ) )['data']['duration_ms'] );
|
||||
}
|
||||
|
||||
public function test_title_goal_message_sort(): void {
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'title' => ' ' ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'title' => str_repeat( 'a', 121 ) ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'goal_id' => '99' ) ) )['error'] );
|
||||
$this->assertSame( 3, $this->run_( $this->post( array( 'goal_id' => '3' ) ) )['data']['goal_id'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'trigger_type' => 'nope' ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'message' => str_repeat( 'm', 256 ) ) ) )['error'] );
|
||||
$this->assertNotNull( $this->run_( $this->post( array( 'sort' => '100000' ) ) )['error'] );
|
||||
$this->assertStringNotContainsString( '<', $this->run_( $this->post( array( 'title' => '<script>x</script>Hi', 'message' => '<b>hi</b>' ) ) )['data']['title'] );
|
||||
$this->assertStringNotContainsString( '<', $this->run_( $this->post( array( 'message' => '<b>hi</b>{name}' ) ) )['data']['message'] );
|
||||
}
|
||||
|
||||
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 ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Alerts\Media;
|
||||
use StreamGoals\Alerts\Template;
|
||||
|
||||
final class AlertHelpersTest extends TestCase {
|
||||
|
||||
public function test_mime_whitelist_and_kinds(): void {
|
||||
foreach ( array( 'image/png', 'image/jpeg', 'image/gif', 'image/webp' ) as $m ) {
|
||||
$this->assertSame( 'image', Media::kind( $m ) );
|
||||
$this->assertSame( 'image', Media::visualType( $m ) );
|
||||
}
|
||||
foreach ( array( 'video/mp4', 'video/webm' ) as $m ) {
|
||||
$this->assertSame( 'video', Media::visualType( $m ) );
|
||||
}
|
||||
foreach ( array( 'audio/mpeg', 'audio/ogg', 'audio/wav' ) as $m ) {
|
||||
$this->assertTrue( Media::isSound( $m ) );
|
||||
$this->assertNull( Media::visualType( $m ) );
|
||||
}
|
||||
$this->assertTrue( Media::isAllowed( 'IMAGE/PNG' ) );
|
||||
}
|
||||
|
||||
/** @dataProvider hostileMimes */
|
||||
public function test_hostile_mimes_rejected( mixed $mime ): void {
|
||||
$this->assertFalse( Media::isAllowed( $mime ) );
|
||||
$this->assertNull( Media::visualType( $mime ) );
|
||||
$this->assertFalse( Media::isSound( $mime ) );
|
||||
}
|
||||
|
||||
public static function hostileMimes(): array {
|
||||
return array(
|
||||
array( 'image/svg+xml' ), array( 'text/html' ), array( 'application/javascript' ), array( '' ), array( null ), array( 123 ),
|
||||
array( array( 'image/png' ) ), array( 'image/png; charset=x' ), array( "image/png\0.html" ), array( ' image/png' ), array( 'image/*' ),
|
||||
array( 'video/x-msvideo' ), array( 'audio/x-wav' ), array( 'image/png,text/html' ),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_duration_clamping(): void {
|
||||
$this->assertSame( 6000, Media::clampDurationMs( 'abc' ) );
|
||||
$this->assertSame( 1000, Media::clampDurationMs( 5 ) );
|
||||
$this->assertSame( 1000, Media::clampDurationMs( -9999 ) );
|
||||
$this->assertSame( 60000, Media::clampDurationMs( 9999999 ) );
|
||||
$this->assertSame( 12000, Media::clampDurationMs( '12000' ) );
|
||||
$this->assertSame( 8000, Media::secondsToMs( '8' ) );
|
||||
$this->assertSame( 1500, Media::secondsToMs( '1.5' ) );
|
||||
$this->assertNull( Media::secondsToMs( 'x' ) );
|
||||
$this->assertNull( Media::secondsToMs( '-3' ) );
|
||||
$this->assertNull( Media::secondsToMs( array() ) );
|
||||
$this->assertSame( 100, Media::clampVolume( 500 ) );
|
||||
$this->assertSame( 0, Media::clampVolume( -5 ) );
|
||||
$this->assertSame( 80, Media::clampVolume( 'loud' ) );
|
||||
}
|
||||
|
||||
public function test_safe_url(): void {
|
||||
$this->assertSame( 'https://x.test/a.png', Media::safeUrl( 'https://x.test/a.png' ) );
|
||||
foreach ( array( 'javascript:alert(1)', 'data:text/html,x', '//evil.test/x', '/relative.png', 'https://x.test/a b', "https://x.test/\"onerror=", '', null, 5 ) as $bad ) {
|
||||
$this->assertNull( Media::safeUrl( $bad ), var_export( $bad, true ) );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_template_tokens(): void {
|
||||
$this->assertSame( 'Al sent $5.00 for Bean!', Template::render( '{name} sent {amount} for {reward}!', 'Al', '$5.00', 'Bean' ) );
|
||||
$this->assertSame( 'Al sent', Template::render( '{Name} {nope} sent', 'Al', '$5', '' ), 'unknown tokens dropped, case-insensitive' );
|
||||
$this->assertSame( '', Template::render( '', 'Al', '$5', '' ) );
|
||||
$this->assertSame( '', Template::render( ' ', 'Al', '$5', '' ) );
|
||||
$this->assertSame( 'Anonymous rocks', Template::render( '{name} rocks', '', '$5', '' ) );
|
||||
}
|
||||
|
||||
public function test_template_is_html_free_and_not_reexpanded(): void {
|
||||
$out = Template::render( '<b>{name}</b><script>alert(1)</script> {amount}', '<img src=x onerror=alert(1)>Al', '$5', '' );
|
||||
$this->assertStringNotContainsString( '<', $out );
|
||||
$this->assertStringNotContainsString( '>', $out );
|
||||
$this->assertStringContainsString( 'Al', $out );
|
||||
$this->assertSame( '{amount} 5', Template::render( '{name} {amount}', '{amount}', '5', '' ) );
|
||||
$this->assertStringNotContainsString( '9', Template::render( '{name}', 'x{amount}', '9', '' ) );
|
||||
$this->assertStringNotContainsString( "\n", Template::render( "a\r\n\t{name}\x00\u{202E}", 'Al', '$5', '' ) );
|
||||
$this->assertStringNotContainsString( '<', Template::render( '<<b>script>x', 'Al', '$5', '' ) );
|
||||
}
|
||||
|
||||
public function test_template_length_capped(): void {
|
||||
$this->assertLessThanOrEqual( 200, mb_strlen( Template::render( str_repeat( 'x', 5000 ), 'Al', '$5', '' ) ) );
|
||||
$long = str_repeat( 'N', 500 );
|
||||
$this->assertLessThanOrEqual( 60, mb_strlen( Template::render( '{name}', $long, '$5', '' ) ) );
|
||||
$this->assertLessThanOrEqual( 80, mb_strlen( Template::render( '{reward}', 'Al', '$5', $long ) ) );
|
||||
$this->assertLessThanOrEqual( 10, mb_strlen( Template::render( str_repeat( 'x', 50 ), 'Al', '$5', '', 10 ) ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Alerts\Resolver;
|
||||
|
||||
final class AlertResolverTest extends TestCase {
|
||||
|
||||
private function def( int $id, array $o = array() ): array {
|
||||
return $o + array( 'id' => $id, 'goal_id' => 0, 'trigger_type' => 'amount', 'min_minor' => 100, 'action_id' => 0, 'enabled' => 1, 'sort' => 0 );
|
||||
}
|
||||
|
||||
public function test_highest_matching_amount_wins(): void {
|
||||
$defs = array( $this->def( 1, array( 'min_minor' => 100 ) ), $this->def( 2, array( 'min_minor' => 1000 ) ), $this->def( 3, array( 'min_minor' => 5000 ) ) );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 1000, array(), $defs )['id'] );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 4999, array(), $defs )['id'] );
|
||||
$this->assertSame( 3, Resolver::pick( 1, 99999, array(), $defs )['id'] );
|
||||
$this->assertSame( 1, Resolver::pick( 1, 100, array(), $defs )['id'] );
|
||||
}
|
||||
|
||||
public function test_none_when_below_every_minimum_or_no_defs(): void {
|
||||
$this->assertNull( Resolver::pick( 1, 99, array(), array( $this->def( 1 ) ) ) );
|
||||
$this->assertNull( Resolver::pick( 1, 5000, array(), array() ) );
|
||||
}
|
||||
|
||||
public function test_reward_beats_amount(): void {
|
||||
$defs = array( $this->def( 1, array( 'min_minor' => 100 ) ), $this->def( 2, array( 'trigger_type' => 'reward', 'action_id' => 9 ) ) );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 5000, array( 9 ), $defs )['id'] );
|
||||
$this->assertSame( 1, Resolver::pick( 1, 5000, array( 8 ), $defs )['id'], 'other reward does not match' );
|
||||
$this->assertSame( 1, Resolver::pick( 1, 5000, array(), $defs )['id'] );
|
||||
}
|
||||
|
||||
public function test_reward_def_matches_even_when_base_is_tiny(): void {
|
||||
$defs = array( $this->def( 2, array( 'trigger_type' => 'reward', 'action_id' => 9, 'min_minor' => 0 ) ) );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 1, array( 9 ), $defs )['id'] );
|
||||
}
|
||||
|
||||
public function test_several_rewards_highest_reward_amount_then_sort_then_id(): void {
|
||||
$defs = array(
|
||||
$this->def( 1, array( 'trigger_type' => 'reward', 'action_id' => 5, 'sort' => 0 ) ),
|
||||
$this->def( 2, array( 'trigger_type' => 'reward', 'action_id' => 6, 'sort' => 9 ) ),
|
||||
);
|
||||
$this->assertSame( 2, Resolver::pick( 1, 5000, array( 5, 6 ), $defs, array( 5 => 500, 6 => 2500 ) )['id'] );
|
||||
$this->assertSame( 1, Resolver::pick( 1, 5000, array( 5, 6 ), $defs, array( 5 => 500, 6 => 500 ) )['id'], 'tie: lower sort' );
|
||||
$defs[1]['sort'] = 0;
|
||||
$this->assertSame( 1, Resolver::pick( 1, 5000, array( 5, 6 ), $defs )['id'], 'tie: lower id' );
|
||||
}
|
||||
|
||||
public function test_goal_scoping(): void {
|
||||
$defs = array( $this->def( 1, array( 'goal_id' => 7, 'min_minor' => 100 ) ), $this->def( 2, array( 'goal_id' => 0, 'min_minor' => 100, 'sort' => 5 ) ) );
|
||||
$this->assertSame( 1, Resolver::pick( 7, 500, array(), $defs )['id'] );
|
||||
$this->assertSame( 2, Resolver::pick( 8, 500, array(), $defs )['id'], 'goal 8 never sees goal 7 defs' );
|
||||
$this->assertSame( 2, Resolver::pick( 0, 500, array(), $defs )['id'], 'test donations (goal 0) use goal-0 defs only' );
|
||||
$only7 = array( $defs[0] );
|
||||
$this->assertNull( Resolver::pick( 0, 500, array(), $only7 ) );
|
||||
}
|
||||
|
||||
public function test_disabled_ignored(): void {
|
||||
$defs = array( $this->def( 1, array( 'enabled' => 0, 'min_minor' => 1000 ) ), $this->def( 2, array( 'min_minor' => 100 ) ),
|
||||
$this->def( 3, array( 'trigger_type' => 'reward', 'action_id' => 9, 'enabled' => 0 ) ) );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 5000, array( 9 ), $defs )['id'] );
|
||||
}
|
||||
|
||||
public function test_string_columns_from_db_are_handled_and_unknown_trigger_ignored(): void {
|
||||
$defs = array( array( 'id' => '4', 'goal_id' => '0', 'trigger_type' => 'amount', 'min_minor' => '500', 'enabled' => '1', 'sort' => '0' ),
|
||||
array( 'id' => '5', 'trigger_type' => 'bogus', 'enabled' => 1 ) );
|
||||
$this->assertSame( 4, Resolver::pick( 3, 500, array(), $defs )['id'] );
|
||||
}
|
||||
|
||||
public function test_equal_minimum_tie_breaks_by_sort_then_id(): void {
|
||||
$defs = array( $this->def( 1, array( 'sort' => 5 ) ), $this->def( 2, array( 'sort' => 1 ) ) );
|
||||
$this->assertSame( 2, Resolver::pick( 1, 500, array(), $defs )['id'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Core\CidrMatcher;
|
||||
use StreamGoals\Core\CloudflareRanges;
|
||||
|
||||
final class CidrMatcherTest extends TestCase {
|
||||
|
||||
public function test_ipv4_boundaries(): void {
|
||||
$r = array( '173.245.48.0/20' ); // 173.245.48.0 - 173.245.63.255
|
||||
$this->assertTrue( CidrMatcher::contains( '173.245.48.0', $r ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '173.245.63.255', $r ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '173.245.47.255', $r ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '173.245.64.0', $r ) );
|
||||
}
|
||||
|
||||
public function test_non_byte_aligned_and_wide_masks(): void {
|
||||
$this->assertTrue( CidrMatcher::contains( '104.27.255.255', array( '104.24.0.0/14' ) ) ); // /14 spans 104.24 - 104.27
|
||||
$this->assertFalse( CidrMatcher::contains( '104.28.0.0', array( '104.24.0.0/14' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '104.23.255.255', array( '104.24.0.0/14' ) ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '8.8.8.8', array( '0.0.0.0/0' ) ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '1.2.3.4', array( '1.2.3.4/32' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '1.2.3.5', array( '1.2.3.4/32' ) ) );
|
||||
}
|
||||
|
||||
public function test_ipv6(): void {
|
||||
$this->assertTrue( CidrMatcher::contains( '2606:4700::1', array( '2606:4700::/32' ) ) );
|
||||
$this->assertTrue( CidrMatcher::contains( '2a06:98c7:ffff::1', array( '2a06:98c0::/29' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '2a06:98c8::1', array( '2a06:98c0::/29' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '2606:4701::1', array( '2606:4700::/32' ) ) );
|
||||
}
|
||||
|
||||
public function test_families_never_cross_match_and_bad_input_is_false(): void {
|
||||
$this->assertFalse( CidrMatcher::contains( '1.2.3.4', array( '2606:4700::/32' ) ) );
|
||||
$this->assertFalse( CidrMatcher::contains( '2606:4700::1', array( '173.245.48.0/20' ) ) );
|
||||
foreach ( array( 'garbage', '', '999.1.1.1', "1.2.3.4\nX: y", '1.2.3.4, 5.6.7.8' ) as $bad ) {
|
||||
$this->assertFalse( CidrMatcher::contains( $bad, array( '0.0.0.0/0' ) ), "matched bad ip: $bad" );
|
||||
}
|
||||
foreach ( array( '1.2.3.4', '1.2.3.4/x', '1.2.3.4/33', '1.2.3.4/-1', 'nope/8', '' ) as $badCidr ) {
|
||||
$this->assertFalse( CidrMatcher::contains( '1.2.3.4', array( $badCidr ) ), "matched bad cidr: $badCidr" );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_surrounding_whitespace_is_tolerated(): void {
|
||||
$this->assertTrue( CidrMatcher::contains( ' 173.245.48.1 ', array( '173.245.48.0/20' ) ) );
|
||||
}
|
||||
|
||||
public function test_cloudflare_ranges(): void {
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '172.70.1.1' ) );
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '104.16.0.1' ) );
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '2606:4700:3030::1' ) );
|
||||
$this->assertFalse( CloudflareRanges::isCloudflare( '203.0.113.9' ) );
|
||||
$this->assertFalse( CloudflareRanges::isCloudflare( '47.151.185.180' ) );
|
||||
$this->assertTrue( CloudflareRanges::isCloudflare( '203.0.113.9', array( '203.0.113.0/24' ) ), 'filter-supplied ranges extend the list' );
|
||||
}
|
||||
}
|
||||
@@ -56,4 +56,52 @@ final class ClientIpTest extends TestCase {
|
||||
$srv = array( 'REMOTE_ADDR' => self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4' );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, 'something_else' ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_trusts_cf_header_only_from_a_cloudflare_connection(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => '172.70.1.1', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
|
||||
$v6 = array( 'REMOTE_ADDR' => '2606:4700:3030::1', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $v6, ClientIp::MODE_AUTO ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_ignores_a_forged_header_from_a_non_cloudflare_connection(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => '47.151.185.180', 'HTTP_CF_CONNECTING_IP' => '6.6.6.6', 'HTTP_X_FORWARDED_FOR' => '7.7.7.7' );
|
||||
$this->assertSame( '47.151.185.180', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_falls_back_when_header_missing_or_invalid(): void {
|
||||
$this->assertSame( '172.70.1.1', ClientIp::resolve( array( 'REMOTE_ADDR' => '172.70.1.1' ), ClientIp::MODE_AUTO ) );
|
||||
$this->assertSame( '172.70.1.1', ClientIp::resolve( array( 'REMOTE_ADDR' => '172.70.1.1', 'HTTP_CF_CONNECTING_IP' => 'nope' ), ClientIp::MODE_AUTO ) );
|
||||
}
|
||||
|
||||
public function test_auto_mode_extra_ranges_from_the_filter(): void {
|
||||
$srv = array( 'REMOTE_ADDR' => '198.18.0.5', 'HTTP_CF_CONNECTING_IP' => self::CLIENT );
|
||||
$this->assertSame( '198.18.0.5', ClientIp::resolve( $srv, ClientIp::MODE_AUTO ) );
|
||||
$this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_AUTO, array( '198.18.0.0/15' ) ) );
|
||||
}
|
||||
|
||||
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 );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\Input;
|
||||
use StreamGoals\Core\Settings;
|
||||
|
||||
final class DonationNoticeTest extends TestCase {
|
||||
|
||||
public function test_default_notice_says_donations_are_non_refundable(): void {
|
||||
$d = Settings::defaults();
|
||||
$this->assertArrayHasKey( 'donation_notice', $d );
|
||||
$this->assertStringContainsString( 'non-refundable', strtolower( (string) $d['donation_notice'] ) );
|
||||
}
|
||||
|
||||
public function test_admin_input_is_plain_text_and_length_capped(): void {
|
||||
$this->assertSame( 'No refunds, sorry.', Input::text( ' No refunds, sorry. ', 200 ) );
|
||||
$this->assertStringNotContainsString( '<', Input::text( '<script>alert(1)</script><b>Hi</b>', 200 ), 'no markup survives (and it is rendered as text anyway)' );
|
||||
$this->assertStringNotContainsString( '<', Input::text( '<b>Bold</b> <i>text</i>', 200 ) );
|
||||
$this->assertSame( 200, strlen( Input::text( str_repeat( 'a', 500 ), 200 ) ) );
|
||||
$this->assertSame( '', Input::text( "\x00\x1F", 200 ) );
|
||||
}
|
||||
|
||||
public function test_form_script_renders_the_notice_with_textcontent_only(): void {
|
||||
$js = (string) file_get_contents( dirname( __DIR__, 2 ) . '/assets/donate/donate.js' );
|
||||
$this->assertMatchesRegularExpression( '/if \(C\.notice\).*sg-notice.*text: String\(C\.notice\)/s', $js, 'notice must be rendered as text, never HTML' );
|
||||
$this->assertStringNotContainsString( 'innerHTML', $js );
|
||||
}
|
||||
|
||||
public function test_form_config_passes_the_notice_through(): void {
|
||||
$php = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Rest/DonateController.php' );
|
||||
$this->assertStringContainsString( "'notice' => (string) ( \$s['donation_notice'] ?? '' )", $php );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Admin\Format;
|
||||
use StreamGoals\Core\FeeCalculator;
|
||||
use StreamGoals\Core\ProfanityFilter;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\PayPal\OrderValidator;
|
||||
|
||||
/** A donor name that trips the profanity filter is masked, the donation is held for moderation, and no alert shows it. */
|
||||
final class DonorNameFlaggingTest extends TestCase {
|
||||
|
||||
private function validate( array $in, array $settings = array() ): array {
|
||||
$goal = array( 'id' => 3, 'currency' => 'USD', 'status' => 'active', 'starts_at' => null, 'ends_at' => null );
|
||||
return OrderValidator::validate( $in + array( 'amount' => '10.00' ), $goal, array_merge( Settings::defaults(), array( 'moderate_messages' => false ), $settings ), new FeeCalculator( 349, 49 ), 1800000000 );
|
||||
}
|
||||
|
||||
public function test_matches_agrees_with_filter(): void {
|
||||
$f = new ProfanityFilter( array( 'profanity_words' => 'jerk' ) );
|
||||
$this->assertTrue( $f->matches( 'Big Jerk' ) );
|
||||
$this->assertTrue( $f->matches( 'sh1t head' ), 'leetspeak counts' );
|
||||
$this->assertFalse( $f->matches( 'Scunthorpe class' ) );
|
||||
$this->assertFalse( $f->matches( '' ) );
|
||||
$this->assertFalse( ( new ProfanityFilter( array( 'profanity_filter' => false ) ) )->matches( 'shit' ) );
|
||||
}
|
||||
|
||||
public function test_flagged_name_is_masked_and_held_even_when_message_moderation_is_off(): void {
|
||||
$v = $this->validate( array( 'display_name' => 'Big Jerk', 'message' => 'thanks' ), array( 'profanity_words' => 'jerk' ) );
|
||||
$this->assertSame( 'Big ****', $v['donor_name'] );
|
||||
$this->assertSame( 'pending', $v['moderation'] );
|
||||
$this->assertSame( 'name', $v['moderation_flags'] );
|
||||
}
|
||||
|
||||
public function test_clean_name_and_off_switch_stay_approved(): void {
|
||||
$v = $this->validate( array( 'display_name' => 'Ann', 'message' => 'hi' ) );
|
||||
$this->assertSame( array( 'approved', '' ), array( $v['moderation'], $v['moderation_flags'] ) );
|
||||
$v = $this->validate( array( 'display_name' => 'shit', 'message' => '' ), array( 'profanity_filter' => false ) );
|
||||
$this->assertSame( array( 'approved', '' ), array( $v['moderation'], $v['moderation_flags'] ) );
|
||||
$this->assertSame( 'shit', $v['donor_name'] );
|
||||
}
|
||||
|
||||
public function test_message_only_and_both_flags(): void {
|
||||
$v = $this->validate( array( 'display_name' => 'Ann', 'message' => 'hello' ), array( 'moderate_messages' => true ) );
|
||||
$this->assertSame( array( 'pending', 'message' ), array( $v['moderation'], $v['moderation_flags'] ) );
|
||||
$v = $this->validate( array( 'display_name' => 'shit', 'message' => 'hello' ), array( 'moderate_messages' => true ) );
|
||||
$this->assertSame( array( 'pending', 'name,message' ), array( $v['moderation'], $v['moderation_flags'] ) );
|
||||
$v = $this->validate( array( 'display_name' => 'shit', 'message' => '' ), array( 'moderate_messages' => true ) );
|
||||
$this->assertSame( 'name', $v['moderation_flags'], 'empty message is never flagged' );
|
||||
}
|
||||
|
||||
public function test_anonymous_donor_name_never_stored_and_never_flags(): void {
|
||||
$v = $this->validate( array( 'display_name' => 'shit', 'anonymous' => true, 'message' => '' ) );
|
||||
$this->assertSame( '', $v['donor_name'] );
|
||||
$this->assertSame( array( 'approved', '' ), array( $v['moderation'], $v['moderation_flags'] ) );
|
||||
$v = $this->validate( array( 'display_name' => 'shit', 'message' => '' ), array( 'anonymity_policy' => 'force_anonymous' ) );
|
||||
$this->assertSame( 'approved', $v['moderation'] );
|
||||
}
|
||||
|
||||
public function test_flagged_label(): void {
|
||||
$this->assertSame( 'Name', Format::flaggedLabel( array( 'moderation_flags' => 'name' ) ) );
|
||||
$this->assertSame( 'Message', Format::flaggedLabel( array( 'moderation_flags' => 'message' ) ) );
|
||||
$this->assertSame( 'Name and message', Format::flaggedLabel( array( 'moderation_flags' => 'name,message' ) ) );
|
||||
$this->assertSame( 'Message', Format::flaggedLabel( array( 'moderation_flags' => '' ) ), 'rows held before v6' );
|
||||
$this->assertSame( 'Message', Format::flaggedLabel( array() ) );
|
||||
}
|
||||
|
||||
public function test_alert_for_held_name_is_not_emitted_until_approved_then_shows_masked_name(): void {
|
||||
$row = array( 'id' => 5, 'base_minor' => 500, 'currency' => 'USD', 'donor_name' => 'Big ****', 'is_anonymous' => 0,
|
||||
'message' => '', 'status' => 'completed', 'moderation' => 'pending' );
|
||||
foreach ( array( 'pending', 'rejected' ) as $m ) {
|
||||
foreach ( array( false, true ) as $recent ) {
|
||||
$out = Payloads::alerts( array( array( 'moderation' => $m ) + $row ), 0, 10, $recent );
|
||||
$this->assertSame( array(), $out['alerts'], "$m (recent=" . (int) $recent . ') must hold the whole alert' );
|
||||
}
|
||||
}
|
||||
$out = Payloads::alerts( array( array( 'moderation' => 'approved' ) + $row ), 0 );
|
||||
$this->assertSame( 'Big ****', $out['alerts'][0]['name'] );
|
||||
}
|
||||
|
||||
public function test_flags_are_wired_through_storage_and_data_sources(): void {
|
||||
$root = dirname( __DIR__, 2 ) . '/includes/';
|
||||
$this->assertStringContainsString( "'moderation_flags' => (string)", (string) file_get_contents( $root . 'PayPal/DonationStore.php' ) );
|
||||
$this->assertStringContainsString( 'moderation_flags VARCHAR(16) NOT NULL DEFAULT', (string) file_get_contents( $root . 'Core/Installer.php' ) );
|
||||
foreach ( array( 'Overlay/WpdbDataSource.php', 'Core/DonationRepository.php' ) as $f ) {
|
||||
$this->assertStringContainsString( "moderation = 'approved'", (string) file_get_contents( $root . $f ), $f );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,339 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace {
|
||||
if ( ! defined( 'ARRAY_A' ) ) {
|
||||
define( 'ARRAY_A', 'ARRAY_A' );
|
||||
}
|
||||
if ( ! class_exists( 'wpdb' ) ) {
|
||||
/** Scripted stand-in so DonationStore::notify_applied() can run its real wiring without WordPress. */
|
||||
class wpdb {
|
||||
public string $prefix = 'wp_';
|
||||
public array $sql = array();
|
||||
public bool $failRules = false;
|
||||
public array $ids = array( 7 );
|
||||
public function prepare( string $q, ...$args ): string {
|
||||
$i = 0;
|
||||
return (string) preg_replace_callback( '/%[dsf]/', static function ( $m ) use ( &$i, $args ) {
|
||||
$v = $args[ $i++ ];
|
||||
return '%s' === $m[0] ? "'" . $v . "'" : (string) $v;
|
||||
}, $q );
|
||||
}
|
||||
public function get_row( string $q, $out = 'OBJECT' ) {
|
||||
$this->sql[] = $q;
|
||||
$row = array( 'id' => 7, 'goal_id' => 1, 'base_minor' => 500, 'fee_minor' => 0, 'total_minor' => 500, 'currency' => 'USD', 'status' => 'completed', 'close_at_target' => 0 );
|
||||
return 'ARRAY_A' === $out ? $row : (object) $row;
|
||||
}
|
||||
public function get_results( string $q, $out = null ): array {
|
||||
$this->sql[] = $q;
|
||||
if ( $this->failRules && str_contains( $q, 'sg_rules' ) ) {
|
||||
throw new \RuntimeException( 'db gone' );
|
||||
}
|
||||
return array();
|
||||
}
|
||||
public function get_var( string $q ) {
|
||||
$this->sql[] = $q;
|
||||
return str_contains( $q, 'GET_LOCK' ) ? 1 : null;
|
||||
}
|
||||
public function get_col( string $q ): array {
|
||||
$this->sql[] = $q;
|
||||
return $this->ids;
|
||||
}
|
||||
public function query( string $q ) {
|
||||
$this->sql[] = $q;
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace StreamGoals\Tests\Unit {
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Actions\ActionRepository;
|
||||
use StreamGoals\Core\Installer;
|
||||
use StreamGoals\Core\Maintenance;
|
||||
use StreamGoals\PayPal\CaptureFinalizer;
|
||||
use StreamGoals\PayPal\DonationStore;
|
||||
use StreamGoals\Rules\Donation;
|
||||
use StreamGoals\Rules\Engine;
|
||||
use StreamGoals\Rules\RuleDef;
|
||||
use StreamGoals\Tiers\TierRepository;
|
||||
|
||||
final class EffectsReconciliationTest extends TestCase {
|
||||
|
||||
private $prevDb;
|
||||
|
||||
protected function setUp(): void {
|
||||
$this->prevDb = $GLOBALS['wpdb'] ?? null;
|
||||
$GLOBALS['wpdb'] = new \wpdb();
|
||||
}
|
||||
|
||||
protected function tearDown(): void {
|
||||
$GLOBALS['wpdb'] = $this->prevDb;
|
||||
}
|
||||
|
||||
private function stamps( object $db ): array {
|
||||
return array_values( array_filter( $db->sql, static fn( $q ) => str_contains( $q, 'SET effects_applied_at' ) ) );
|
||||
}
|
||||
|
||||
// ---- stamping ---------------------------------------------------------------------------------------
|
||||
|
||||
public function test_notify_applied_stamps_only_when_every_step_succeeded(): void {
|
||||
$db = $GLOBALS['wpdb'];
|
||||
$this->assertTrue( DonationStore::notify_applied( 7 ) );
|
||||
$stamps = $this->stamps( $db );
|
||||
$this->assertCount( 1, $stamps );
|
||||
$this->assertStringContainsString( "WHERE id = 7 AND status = 'completed' AND effects_applied_at IS NULL", $stamps[0] );
|
||||
|
||||
$db->sql = array();
|
||||
$db->failRules = true; // simulates the engine dying
|
||||
$this->assertFalse( DonationStore::notify_applied( 7 ) );
|
||||
$this->assertSame( array(), $this->stamps( $db ), 'a failed side effect must leave effects_applied_at NULL so reconcile retries' );
|
||||
}
|
||||
|
||||
public function test_stamp_is_the_last_step_of_notify_applied(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/PayPal/DonationStore.php' );
|
||||
$start = strpos( $src, 'function notify_applied' );
|
||||
$body = substr( $src, $start, strpos( $src, 'function mark_effects_applied' ) - $start );
|
||||
$this->assertLessThan( strpos( $body, 'mark_effects_applied' ), strpos( $body, 'close_goal_if_target_reached' ) );
|
||||
$this->assertLessThan( strpos( $body, 'close_goal_if_target_reached' ), strpos( $body, 'Tiers\\Recorder::forDonationChecked' ), 'tiers still before close-at-target' );
|
||||
}
|
||||
|
||||
public function test_capture_finalizer_still_runs_effects_once_even_if_replayed(): void {
|
||||
$row = array( 'id' => 7, 'status' => 'pending', 'total_minor' => 500, 'currency' => 'USD' );
|
||||
$state = (object) array( 'status' => 'pending', 'applied' => 0 );
|
||||
$mark = static function () use ( $state ): bool {
|
||||
if ( 'pending' !== $state->status ) {
|
||||
return false;
|
||||
}
|
||||
$state->status = 'completed';
|
||||
return true;
|
||||
};
|
||||
$notify = static function () use ( $state ): void {
|
||||
$state->applied++;
|
||||
};
|
||||
$m = new \StreamGoals\Core\Money( 500, 'USD' );
|
||||
$this->assertSame( 'completed', CaptureFinalizer::finalize( $row, 'COMPLETED', 'C1', $m, $mark, $notify ) );
|
||||
$this->assertSame( 'duplicate', CaptureFinalizer::finalize( $row, 'COMPLETED', 'C1', $m, $mark, $notify ), 'webhook replay on a stale pending snapshot' );
|
||||
$this->assertSame( 'duplicate', CaptureFinalizer::finalize( array( 'status' => 'completed' ) + $row, 'COMPLETED', 'C1', $m, $mark, $notify ) );
|
||||
$this->assertSame( 1, $state->applied );
|
||||
}
|
||||
|
||||
// ---- reconcile --------------------------------------------------------------------------------------
|
||||
|
||||
public function test_reconcile_window_batch_and_counting(): void {
|
||||
$now = 1800000000;
|
||||
$seen = array();
|
||||
$n = Maintenance::reconcile(
|
||||
$now,
|
||||
function ( string $after, string $before, int $limit ) use ( &$seen ): array {
|
||||
$seen = array( strtotime( $after . ' UTC' ), strtotime( $before . ' UTC' ), $limit );
|
||||
return array( 4, 5, 6 );
|
||||
},
|
||||
static function ( int $id ): bool {
|
||||
if ( 5 === $id ) {
|
||||
throw new \RuntimeException( 'boom' );
|
||||
}
|
||||
return 4 === $id; // 6 "fails" (not stamped)
|
||||
}
|
||||
);
|
||||
$this->assertSame( 1, $n, 'a throwing or failing donation neither aborts the batch nor counts as applied' );
|
||||
$this->assertSame( $now - 120, $seen[0], 'only donations older than 2 minutes' );
|
||||
$this->assertSame( $now - 30 * 86400, $seen[1] );
|
||||
$this->assertSame( Maintenance::RECONCILE_BATCH, $seen[2] );
|
||||
}
|
||||
|
||||
public function test_candidate_query_only_selects_completed_unstamped_real_goal_rows(): void {
|
||||
$db = $GLOBALS['wpdb'];
|
||||
$ids = DonationStore::unapplied_completed_ids( '2026-01-02 00:00:00', '2025-12-01 00:00:00', 25 );
|
||||
$this->assertSame( array( 7 ), $ids );
|
||||
$q = $db->sql[0];
|
||||
$this->assertStringContainsString( "status = 'completed' AND effects_applied_at IS NULL AND goal_id > 0", $q );
|
||||
$this->assertStringContainsString( "created_at < '2026-01-02 00:00:00' AND created_at >= '2025-12-01 00:00:00'", $q );
|
||||
$this->assertStringNotContainsString( 'UPDATE', $q );
|
||||
$this->assertStringNotContainsString( 'DELETE', $q );
|
||||
}
|
||||
|
||||
public function test_reconcile_effects_is_single_flight_and_releases_the_lock(): void {
|
||||
$db = $GLOBALS['wpdb'];
|
||||
$this->assertSame( 1, Maintenance::reconcile_effects() ); // id 7 -> notify_applied -> stamped
|
||||
$this->assertNotEmpty( array_filter( $db->sql, static fn( $q ) => str_contains( $q, 'RELEASE_LOCK' ) ) );
|
||||
$this->assertCount( 1, $this->stamps( $db ) );
|
||||
|
||||
$busy = new class() extends \wpdb {
|
||||
public function get_var( string $q ) {
|
||||
$this->sql[] = $q;
|
||||
return 0; // GET_LOCK denied
|
||||
}
|
||||
};
|
||||
$GLOBALS['wpdb'] = $busy;
|
||||
$this->assertSame( 0, Maintenance::reconcile_effects() );
|
||||
$this->assertSame( array(), $this->stamps( $busy ) );
|
||||
}
|
||||
|
||||
public function test_cron_schedule_and_hooks(): void {
|
||||
$s = Maintenance::cron_schedules( array( 'daily' => array() ) );
|
||||
$this->assertSame( 300, $s[ Maintenance::RECONCILE_SCHEDULE ]['interval'] );
|
||||
$this->assertArrayHasKey( 'daily', $s );
|
||||
$this->assertSame( 120, Maintenance::RECONCILE_MIN_AGE );
|
||||
$root = dirname( __DIR__, 2 ) . '/includes/Core/';
|
||||
$this->assertStringContainsString( 'wp_clear_scheduled_hook( self::RECONCILE_HOOK )', (string) file_get_contents( $root . 'Maintenance.php' ) );
|
||||
$this->assertStringContainsString( 'Maintenance::RECONCILE_HOOK', (string) file_get_contents( $root . 'Uninstaller.php' ) );
|
||||
}
|
||||
|
||||
// ---- upgrade ----------------------------------------------------------------------------------------
|
||||
|
||||
public function test_installer_v6_schema_and_backfill_ordering(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' );
|
||||
$this->assertSame( '6', Installer::DB_VERSION );
|
||||
$this->assertStringContainsString( 'effects_applied_at DATETIME NULL,', $src );
|
||||
$this->assertStringContainsString( "moderation_flags VARCHAR(16) NOT NULL DEFAULT ''", $src );
|
||||
$this->assertLessThan( strpos( $src, "update_option( 'sg_db_version'" ), strpos( $src, 'backfill_effects_applied()' ), 'version is only recorded after a successful backfill' );
|
||||
}
|
||||
|
||||
public function test_backfill_runs_for_pre_v6_and_fresh_installs_only(): void {
|
||||
foreach ( array( false, '', '1', '2', '5' ) as $from ) {
|
||||
$this->assertTrue( Installer::needsEffectsBackfill( $from ), var_export( $from, true ) );
|
||||
}
|
||||
$this->assertFalse( Installer::needsEffectsBackfill( '6' ) );
|
||||
$this->assertFalse( Installer::needsEffectsBackfill( '7' ) );
|
||||
}
|
||||
|
||||
public function test_backfill_stamps_existing_completed_rows_once_and_reports_failure(): void {
|
||||
$db = $GLOBALS['wpdb'];
|
||||
$this->assertTrue( Installer::backfill_effects_applied() );
|
||||
$q = $db->sql[0];
|
||||
$this->assertStringContainsString( 'UPDATE wp_sg_donations SET effects_applied_at =', $q );
|
||||
$this->assertStringContainsString( "WHERE status = 'completed' AND effects_applied_at IS NULL", $q );
|
||||
|
||||
$GLOBALS['wpdb'] = new class() extends \wpdb {
|
||||
public function query( string $q ) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
$this->assertFalse( Installer::backfill_effects_applied() );
|
||||
}
|
||||
|
||||
// ---- replay does not double-apply -------------------------------------------------------------------
|
||||
|
||||
private function rules(): array {
|
||||
return array(
|
||||
new RuleDef( 1, 1, 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ) ),
|
||||
new RuleDef( 2, 1, 'counter', array( 'step' => 1, 'per_minor' => 1000, 'carry_over' => true ) ),
|
||||
new RuleDef( 3, 1, 'bonus', array( 'min_minor' => 1000, 'event' => 'big' ) ),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_engine_replay_after_full_apply_changes_nothing_and_fires_no_second_bonus(): void {
|
||||
$state = new FakeStateRepository();
|
||||
$ev = new FakeEventStore();
|
||||
$fired = 0;
|
||||
$e = new Engine( new FakeRuleStore( $this->rules() ), $ev, $state, fn(): int => 1000, function () use ( &$fired ): void {
|
||||
$fired++;
|
||||
} );
|
||||
$d = new Donation( 10, 1, 2500, 0, 2500, 'USD' );
|
||||
$e->applyDonation( $d );
|
||||
$state1 = $state->data;
|
||||
$ev1 = $ev->events;
|
||||
$this->assertSame( 1, $fired );
|
||||
for ( $i = 0; $i < 3; $i++ ) {
|
||||
$e->applyDonation( $d );
|
||||
}
|
||||
$this->assertSame( $state1, $state->data, 'timer and counter untouched by replays' );
|
||||
$this->assertSame( $ev1, $ev->events );
|
||||
$this->assertSame( 1, $fired, 'bonus event fires once' );
|
||||
}
|
||||
|
||||
public function test_engine_replay_after_partial_apply_only_applies_the_missing_rules(): void {
|
||||
$state = new FakeStateRepository();
|
||||
$ev = new FakeEventStore();
|
||||
$d = new Donation( 10, 1, 2500, 0, 2500, 'USD' );
|
||||
$rules = $this->rules();
|
||||
// The process died after the timer rule (rule 1) but before the others.
|
||||
( new Engine( new FakeRuleStore( array( $rules[0] ) ), $ev, $state, fn(): int => 1000 ) )->applyDonation( $d );
|
||||
$timer = $state->getInt( 1, 'timer_ends_at' );
|
||||
$this->assertSame( 2500, $timer );
|
||||
// Later (clock moved on) the reconciler replays with all rules.
|
||||
( new Engine( new FakeRuleStore( $rules ), $ev, $state, fn(): int => 5000 ) )->applyDonation( $d );
|
||||
$this->assertSame( $timer, $state->getInt( 1, 'timer_ends_at' ), 'timer must not be added twice' );
|
||||
$this->assertSame( 1500, $state->getInt( 1, 'timer_added:1' ) );
|
||||
$this->assertSame( 2, $state->getInt( 1, 'counter:2' ), 'the lost counter effect is recovered' );
|
||||
$this->assertSame( array( '1:10', '2:10', '3:10' ), array_keys( $ev->events ) );
|
||||
}
|
||||
|
||||
public function test_action_events_replay_is_insert_ignore_on_the_unique_key(): void {
|
||||
$db = new class() {
|
||||
public string $prefix = 'wp_';
|
||||
public array $rows = array();
|
||||
public function prepare( string $q, ...$args ): string {
|
||||
$i = 0;
|
||||
return (string) preg_replace_callback( '/%[dsf]/', static function ( $m ) use ( &$i, $args ) {
|
||||
$v = $args[ $i++ ];
|
||||
return '%s' === $m[0] ? "'" . $v . "'" : (string) $v;
|
||||
}, $q );
|
||||
}
|
||||
public function query( string $q ) {
|
||||
if ( ! str_starts_with( $q, 'INSERT IGNORE' ) || ! preg_match( '/VALUES \((\d+), (\d+),/', $q, $m ) ) {
|
||||
return 0;
|
||||
}
|
||||
$k = $m[1] . ':' . $m[2];
|
||||
if ( isset( $this->rows[ $k ] ) ) {
|
||||
return 0; // UNIQUE(donation_id, action_id) swallowed it
|
||||
}
|
||||
$this->rows[ $k ] = $q;
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
$repo = new ActionRepository( $db );
|
||||
$matches = array( array( 'action_id' => 4, 'title' => 'Beans', 'times' => 5 ), array( 'action_id' => 9, 'title' => 'Pushups', 'times' => 1 ) );
|
||||
$repo->recordEvents( 10, $matches );
|
||||
$repo->recordEvents( 10, $matches );
|
||||
$this->assertCount( 2, $db->rows, 'one queued event per (donation, action) no matter how often it is replayed' );
|
||||
$this->assertStringContainsString( 'UNIQUE KEY donation_action (donation_id,action_id)', (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/Installer.php' ) );
|
||||
}
|
||||
|
||||
public function test_tier_marks_replay_does_not_reassign_or_re_mark(): void {
|
||||
$db = new class() {
|
||||
public string $prefix = 'wp_';
|
||||
public array $tiers = array(
|
||||
1 => array( 'id' => '1', 'goal_id' => '7', 'target_minor' => '10000', 'title' => 'A', 'description' => '', 'reached_at' => null, 'reached_donation_id' => null, 'created_at' => '2026-01-01 00:00:00' ),
|
||||
2 => array( 'id' => '2', 'goal_id' => '7', 'target_minor' => '90000', 'title' => 'B', 'description' => '', 'reached_at' => null, 'reached_donation_id' => null, 'created_at' => '2026-01-01 00:00:00' ),
|
||||
);
|
||||
public function prepare( string $q, ...$args ): string {
|
||||
$i = 0;
|
||||
return (string) preg_replace_callback( '/%[dsf]/', static function ( $m ) use ( &$i, $args ) {
|
||||
$v = $args[ $i++ ];
|
||||
return '%s' === $m[0] ? "'" . $v . "'" : (string) $v;
|
||||
}, $q );
|
||||
}
|
||||
public function get_results( string $q, $o = null ): array {
|
||||
return array_values( $this->tiers );
|
||||
}
|
||||
public function query( string $q ) {
|
||||
if ( ! preg_match( "/SET reached_at = '([^']+)', reached_donation_id = (\\d+) WHERE id = (\\d+) AND reached_at IS NULL/", $q, $m ) ) {
|
||||
return 0;
|
||||
}
|
||||
if ( null !== $this->tiers[ (int) $m[3] ]['reached_at'] ) {
|
||||
return 0;
|
||||
}
|
||||
$this->tiers[ (int) $m[3] ]['reached_at'] = $m[1];
|
||||
$this->tiers[ (int) $m[3] ]['reached_donation_id'] = $m[2];
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
$repo = new TierRepository( $db );
|
||||
$this->assertSame( array( 1 ), $repo->markReached( 7, 20000, 55 ) );
|
||||
$this->assertSame( array(), $repo->markReached( 7, 20000, 55 ), 'replay marks nothing' );
|
||||
$this->assertSame( array(), $repo->markReached( 7, 20000, 56 ), 'a later replay never steals the unlock from donation 55' );
|
||||
$this->assertSame( '55', $db->tiers[1]['reached_donation_id'] );
|
||||
$this->assertNull( $db->tiers[2]['reached_at'] );
|
||||
}
|
||||
|
||||
public function test_goal_close_is_conditional_so_replay_cannot_reclose(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Core/GoalRepository.php' );
|
||||
$this->assertStringContainsString( "AND status = 'active' AND close_at_target = 1", $src );
|
||||
$this->assertStringContainsString( "'active' !== \$goal['status']", $src );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Core\FeeCalculator;
|
||||
use StreamGoals\Core\GoalTargetPolicy;
|
||||
use StreamGoals\Core\Settings;
|
||||
use StreamGoals\PayPal\OrderValidator;
|
||||
use StreamGoals\PayPal\ValidationException;
|
||||
|
||||
final class GoalTargetPolicyTest extends TestCase {
|
||||
|
||||
private function goal( array $o = array() ): array {
|
||||
return array_merge( array( 'id' => 3, 'currency' => 'USD', 'status' => 'active', 'target_minor' => 10000, 'close_at_target' => 1, 'counts_fees' => 0, 'starts_at' => null, 'ends_at' => null ), $o );
|
||||
}
|
||||
|
||||
public function test_below_equal_and_over_target(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal(), 9999 ) );
|
||||
$this->assertTrue( GoalTargetPolicy::shouldClose( $this->goal(), 10000 ) );
|
||||
$this->assertTrue( GoalTargetPolicy::shouldClose( $this->goal(), 25000 ) );
|
||||
}
|
||||
|
||||
public function test_flag_off_or_missing_never_closes(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'close_at_target' => 0 ) ), 99999 ) );
|
||||
$g = $this->goal();
|
||||
unset( $g['close_at_target'] );
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $g, 99999 ) );
|
||||
}
|
||||
|
||||
public function test_only_active_goals_are_closed(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'status' => 'complete' ) ), 20000 ) );
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'status' => 'paused' ) ), 20000 ) );
|
||||
}
|
||||
|
||||
public function test_target_zero_never_closes(): void {
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'target_minor' => 0 ) ), 0 ) );
|
||||
$this->assertFalse( GoalTargetPolicy::shouldClose( $this->goal( array( 'target_minor' => 0 ) ), 500 ) );
|
||||
}
|
||||
|
||||
public function test_base_vs_total_basis(): void {
|
||||
$this->assertSame( 'base_minor', GoalTargetPolicy::amountColumn( $this->goal() ) );
|
||||
$this->assertSame( 'total_minor', GoalTargetPolicy::amountColumn( $this->goal( array( 'counts_fees' => 1 ) ) ) );
|
||||
}
|
||||
|
||||
public function test_closed_at_target_detection_and_pause_is_not_closed(): void {
|
||||
$this->assertTrue( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'complete' ) ) ) );
|
||||
$this->assertFalse( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'paused' ) ) ) );
|
||||
$this->assertFalse( GoalTargetPolicy::isClosedAtTarget( $this->goal( array( 'status' => 'complete', 'close_at_target' => 0 ) ) ) );
|
||||
}
|
||||
|
||||
public function test_checkbox_parsing(): void {
|
||||
$this->assertSame( 1, GoalTargetPolicy::flagFromPost( '1' ) );
|
||||
$this->assertSame( 1, GoalTargetPolicy::flagFromPost( 'on' ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( null ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( '' ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( '0' ) );
|
||||
$this->assertSame( 0, GoalTargetPolicy::flagFromPost( array( '1' ) ) );
|
||||
}
|
||||
|
||||
public function test_new_orders_for_a_closed_goal_get_a_friendly_409(): void {
|
||||
try {
|
||||
OrderValidator::validate( array( 'amount' => '5.00' ), $this->goal( array( 'status' => 'complete' ) ), Settings::defaults(), new FeeCalculator( 349, 49 ), 1800000000 );
|
||||
$this->fail( 'expected refusal' );
|
||||
} catch ( ValidationException $e ) {
|
||||
$this->assertSame( 'goal_inactive', $e->errorCode );
|
||||
$this->assertSame( 409, $e->status );
|
||||
$this->assertStringContainsString( 'Thank you', $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_paused_goal_keeps_generic_message(): void {
|
||||
try {
|
||||
OrderValidator::quote( array( 'amount' => '5.00' ), $this->goal( array( 'status' => 'paused' ) ), Settings::defaults(), new FeeCalculator( 349, 49 ), 1800000000 );
|
||||
$this->fail( 'expected refusal' );
|
||||
} catch ( ValidationException $e ) {
|
||||
$this->assertSame( 'This goal is not accepting donations.', $e->getMessage() );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_goal_open_for_active_flagged_goal(): void {
|
||||
$this->assertTrue( OrderValidator::goalIsOpen( $this->goal(), 1800000000 ) );
|
||||
$this->assertFalse( OrderValidator::goalIsOpen( $this->goal( array( 'status' => 'complete' ) ), 1800000000 ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Alerts\AlertMedia;
|
||||
use StreamGoals\Overlay\ActionsSource;
|
||||
use StreamGoals\Overlay\AlertMediaSource;
|
||||
use StreamGoals\Overlay\OverlayDataSource;
|
||||
use StreamGoals\Overlay\OverlayService;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\Overlay\RecentDonationsSource;
|
||||
|
||||
final class OverlayAlertMediaTest extends TestCase {
|
||||
|
||||
private function def( int $id, array $o = array() ): array {
|
||||
return $o + array( 'id' => $id, 'goal_id' => 0, 'trigger_type' => 'amount', 'min_minor' => 100, 'action_id' => 0, 'visual_id' => 10, 'visual_type' => 'image',
|
||||
'sound_id' => 12, 'volume' => 60, 'duration_ms' => 7000, 'message' => '', 'enabled' => 1, 'sort' => 0 );
|
||||
}
|
||||
|
||||
private function row( int $id, array $o = array() ): array {
|
||||
return $o + array( 'id' => $id, 'goal_id' => 7, 'base_minor' => 2500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0,
|
||||
'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
|
||||
}
|
||||
|
||||
private function files(): array {
|
||||
return array(
|
||||
10 => array( 'url' => 'https://cdn.test/a.gif', 'mime' => 'image/gif' ),
|
||||
11 => array( 'url' => 'https://cdn.test/v.mp4', 'mime' => 'video/mp4' ),
|
||||
12 => array( 'url' => 'https://cdn.test/s.mp3', 'mime' => 'audio/mpeg' ),
|
||||
13 => array( 'url' => 'https://cdn.test/x.svg', 'mime' => 'image/svg+xml' ),
|
||||
14 => array( 'url' => 'javascript:alert(1)', 'mime' => 'image/png' ),
|
||||
);
|
||||
}
|
||||
|
||||
private function build( array $def, array $row = array(), array $triggered = array() ): ?array {
|
||||
$files = $this->files();
|
||||
return AlertMedia::build( $row ?: $this->row( 1 ), 'Al', '$25.00', array( $def ), $triggered, static fn( int $id ): ?array => $files[ $id ] ?? null );
|
||||
}
|
||||
|
||||
public function test_shape_for_image_and_sound(): void {
|
||||
$m = $this->build( $this->def( 1, array( 'message' => '{name} gave {amount}' ) ) );
|
||||
$this->assertSame( array(
|
||||
'visual' => array( 'type' => 'image', 'url' => 'https://cdn.test/a.gif' ),
|
||||
'sound' => array( 'url' => 'https://cdn.test/s.mp3' ),
|
||||
'volume' => 60,
|
||||
'duration_ms' => 7000,
|
||||
'message' => 'Al gave $25.00',
|
||||
'frameless' => false,
|
||||
), $m );
|
||||
}
|
||||
|
||||
public function test_video_duration_is_capped_and_type_comes_from_mime(): void {
|
||||
$m = $this->build( $this->def( 1, array( 'visual_id' => 11, 'visual_type' => 'image', 'duration_ms' => 2000 ) ) );
|
||||
$this->assertSame( 'video', $m['visual']['type'] );
|
||||
$this->assertSame( 30000, $m['duration_ms'] );
|
||||
$this->assertNull( $m['message'] );
|
||||
}
|
||||
|
||||
public function test_invalid_media_dropped_silently(): void {
|
||||
$m = $this->build( $this->def( 1, array( 'visual_id' => 13, 'sound_id' => 99 ) ) );
|
||||
$this->assertNull( $m, 'nothing usable and no message: plain alert' );
|
||||
$m = $this->build( $this->def( 1, array( 'visual_id' => 13, 'sound_id' => 12 ) ) );
|
||||
$this->assertNull( $m['visual'] );
|
||||
$this->assertSame( 'https://cdn.test/s.mp3', $m['sound']['url'] );
|
||||
$m = $this->build( $this->def( 1, array( 'visual_id' => 14, 'sound_id' => 0, 'message' => 'hi' ) ) );
|
||||
$this->assertNull( $m['visual'], 'non-http url dropped' );
|
||||
$this->assertSame( 'hi', $m['message'] );
|
||||
$this->assertNull( $this->build( $this->def( 1, array( 'sound_id' => 10, 'visual_id' => 12 ) ) ), 'wrong kinds in wrong slots' );
|
||||
}
|
||||
|
||||
public function test_urls_come_only_from_callback_not_from_def_or_row(): void {
|
||||
$def = $this->def( 1, array( 'url' => 'https://evil.test/x.png', 'visual_url' => 'https://evil.test/y.png' ) );
|
||||
$row = $this->row( 1, array( 'media' => array( 'visual' => array( 'type' => 'image', 'url' => 'https://evil.test/z.png' ) ) ) );
|
||||
$json = json_encode( $this->build( $def, $row ) );
|
||||
$this->assertStringNotContainsString( 'evil.test', (string) $json );
|
||||
$this->assertStringContainsString( 'cdn.test\/a.gif', (string) $json );
|
||||
$boom = AlertMedia::build( $this->row( 1 ), 'Al', '$1', array( $this->def( 1 ) ), array(), static function ( int $id ): ?array { throw new \RuntimeException( 'db' ); } );
|
||||
$this->assertNull( $boom );
|
||||
}
|
||||
|
||||
public function test_reward_token_and_reward_priority(): void {
|
||||
$trig = array( array( 'action_id' => 5, 'amount_minor' => 500, 'title' => 'Eat bean' ), array( 'action_id' => 6, 'amount_minor' => 2500, 'title' => 'Pushups' ) );
|
||||
$defs = array( $this->def( 1, array( 'message' => 'amt {reward}' ) ), $this->def( 2, array( 'trigger_type' => 'reward', 'action_id' => 5, 'message' => 'rw {reward}' ) ) );
|
||||
$files = $this->files();
|
||||
$m = AlertMedia::build( $this->row( 1 ), 'Al', '$25.00', $defs, $trig, static fn( int $id ): ?array => $files[ $id ] ?? null );
|
||||
$this->assertSame( 'rw Eat bean', $m['message'] );
|
||||
$m = AlertMedia::build( $this->row( 1 ), 'Al', '$25.00', array( $defs[0] ), $trig, static fn( int $id ): ?array => $files[ $id ] ?? null );
|
||||
$this->assertSame( 'amt Pushups', $m['message'], 'amount def gets the highest triggered reward' );
|
||||
}
|
||||
|
||||
/** Service-level: one defs query, one triggered query, goal 0 for tests, anonymity/moderation intact. */
|
||||
private function svc( array $defs, array $db, array $triggered = array() ): array {
|
||||
$src = new class( $defs, $db, $triggered, $this->files() ) implements OverlayDataSource, RecentDonationsSource, ActionsSource, AlertMediaSource {
|
||||
public int $defQueries = 0; public int $trigQueries = 0;
|
||||
public function __construct( public array $defs, private array $db, private array $trig, private array $files ) {}
|
||||
public function activeGoal(): ?array { return array( 'id' => 7, 'currency' => 'USD' ); }
|
||||
public function raisedMinor( array $goal ): int { return 0; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); }
|
||||
public function bonusesFor( array $ids ): array { return array(); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return array_values( array_filter( $this->db, fn( $d ) => $d['id'] > (int) $sinceId ) ); }
|
||||
public function recentDonations( int $limit ): array { return $this->db; }
|
||||
public function menuActions( int $goalId ): array { return array(); }
|
||||
public function actionsFor( array $ids ): array { return array(); }
|
||||
public function alertDefs(): array { ++$this->defQueries; return $this->defs; }
|
||||
public function triggeredActionsFor( array $ids ): array { ++$this->trigQueries; return $this->trig; }
|
||||
public function attachment( int $id ): ?array { return $this->files[ $id ] ?? null; }
|
||||
};
|
||||
return array( new OverlayService( $src ), $src );
|
||||
}
|
||||
|
||||
public function test_payload_carries_media_in_recent_and_since_modes_with_single_queries(): void {
|
||||
[ $svc, $src ] = $this->svc( array( $this->def( 1 ) ), array( $this->row( 1 ), $this->row( 2 ), $this->row( 3, array( 'goal_id' => 0 ) ) ) );
|
||||
$out = $svc->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( 'https://cdn.test/a.gif', $out['alerts'][0]['media']['visual']['url'] );
|
||||
$this->assertSame( 1, $src->defQueries );
|
||||
$this->assertSame( 1, $src->trigQueries );
|
||||
[ $svc2 ] = $this->svc( array( $this->def( 1 ) ), array( $this->row( 1 ), $this->row( 2 ) ) );
|
||||
$this->assertSame( 60, $svc2->payload( 'alerts', 1, 0, false )['alerts'][1]['media']['volume'] );
|
||||
}
|
||||
|
||||
public function test_goal_scoping_in_payload_and_test_donations(): void {
|
||||
$defs = array( $this->def( 1, array( 'goal_id' => 7 ) ) );
|
||||
[ $svc ] = $this->svc( $defs, array( $this->row( 1 ), $this->row( 2, array( 'goal_id' => 0 ) ), $this->row( 3, array( 'goal_id' => 9 ) ) ) );
|
||||
$a = $svc->payload( 'alerts', 1, null, true )['alerts'];
|
||||
$this->assertNotNull( $a[0]['media'] );
|
||||
$this->assertNull( $a[1]['media'], 'test donation (goal 0) does not use goal-7 defs' );
|
||||
$this->assertNull( $a[2]['media'] );
|
||||
}
|
||||
|
||||
public function test_no_defs_means_media_null_and_no_trigger_query(): void {
|
||||
[ $svc, $src ] = $this->svc( array(), array( $this->row( 1 ) ) );
|
||||
$this->assertNull( $svc->payload( 'alerts', 1, null, true )['alerts'][0]['media'] );
|
||||
$this->assertSame( 0, $src->trigQueries );
|
||||
}
|
||||
|
||||
public function test_moderation_and_anonymity_unchanged(): void {
|
||||
$rows = array( $this->row( 1, array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ), $this->row( 2, array( 'moderation' => 'pending' ) ) );
|
||||
[ $svc ] = $this->svc( array( $this->def( 1, array( 'message' => '{name}!' ) ) ), $rows );
|
||||
$a = $svc->payload( 'alerts', 1, null, true )['alerts'];
|
||||
$this->assertCount( 1, $a );
|
||||
$this->assertSame( 'Anonymous', $a[0]['name'] );
|
||||
$this->assertSame( 'Anonymous!', $a[0]['media']['message'] );
|
||||
$this->assertStringNotContainsString( 'Secret', (string) json_encode( $a ) );
|
||||
}
|
||||
|
||||
public function test_etag_changes_with_media_definitions_even_without_alerts(): void {
|
||||
[ $a ] = $this->svc( array( $this->def( 1 ) ), array() );
|
||||
[ $b ] = $this->svc( array( $this->def( 1, array( 'volume' => 10 ) ) ), array() );
|
||||
[ $none ] = $this->svc( array(), array() );
|
||||
$pa = $a->payload( 'alerts', 1, 0, false );
|
||||
$ea = Payloads::etag( $pa, $a->etagSalt( 'alerts' ) );
|
||||
$this->assertNotSame( $ea, Payloads::etag( $pa, $b->etagSalt( 'alerts' ) ) );
|
||||
$this->assertNotSame( $ea, Payloads::etag( $pa, $none->etagSalt( 'alerts' ) ) );
|
||||
$this->assertSame( Payloads::etag( $pa ), Payloads::etag( $pa, $none->etagSalt( 'alerts' ) ), 'no defs: unchanged etag' );
|
||||
$this->assertSame( '', $a->etagSalt( 'goal' ) );
|
||||
}
|
||||
|
||||
public function test_etag_changes_when_attachment_url_changes(): void {
|
||||
$p1 = array( 'alerts' => array( array( 'id' => 1, 'media' => array( 'visual' => array( 'url' => 'https://a/1' ) ) ) ) );
|
||||
$p2 = array( 'alerts' => array( array( 'id' => 1, 'media' => array( 'visual' => array( 'url' => 'https://a/2' ) ) ) ) );
|
||||
$this->assertNotSame( Payloads::etag( $p1 ), Payloads::etag( $p2 ) );
|
||||
}
|
||||
|
||||
public function test_payloads_alerts_calls_media_callback_with_public_name_only_for_shown_rows(): void {
|
||||
$seen = array();
|
||||
$cb = static function ( array $r, string $name, string $amount ) use ( &$seen ): ?array { $seen[] = array( $r['id'], $name, $amount ); return null; };
|
||||
Payloads::alerts( array( $this->row( 1, array( 'is_anonymous' => 1 ) ), $this->row( 2, array( 'moderation' => 'rejected' ) ) ), null, 10, true, $cb );
|
||||
$this->assertSame( array( array( 1, 'Anonymous', '$25.00' ) ), $seen );
|
||||
}
|
||||
|
||||
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'] );
|
||||
}
|
||||
}
|
||||
@@ -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 );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Overlay\OverlayDataSource;
|
||||
use StreamGoals\Overlay\OverlayService;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\Overlay\RecentDonationsSource;
|
||||
use StreamGoals\Overlay\TiersSource;
|
||||
|
||||
final class OverlayTiersTest extends TestCase {
|
||||
|
||||
private function tiers( array $reached = array() ): array {
|
||||
$rows = array( array( 1, 10000, 'Giveaway' ), array( 2, 25000, 'Microphone' ), array( 3, 50000, '24h stream' ) );
|
||||
return array_map( static fn( $r ) => array( 'id' => $r[0], 'target_minor' => $r[1], 'title' => $r[2], 'description' => 'd' . $r[0], 'reached_at' => in_array( $r[0], $reached, true ) ? '2026-01-01 00:00:00' : null ), $rows );
|
||||
}
|
||||
|
||||
private function svc( array $tiers, int $raised, array $db = array(), array $unlocked = array(), ?object &$probe = null ): OverlayService {
|
||||
$probe = new class( $tiers, $raised, $db, $unlocked ) implements OverlayDataSource, RecentDonationsSource, TiersSource {
|
||||
public int $reachedQueries = 0;
|
||||
public function __construct( private array $tiers, private int $raised, private array $db, private array $unlocked ) {}
|
||||
public function activeGoal(): ?array { return array( 'id' => 7, 'title' => 'Stream', 'currency' => 'USD', 'target_minor' => 50000 ); }
|
||||
public function raisedMinor( array $goal ): int { return $this->raised; }
|
||||
public function stateValue( int $goalId, string $key ): ?string { return null; }
|
||||
public function counter( int $goalId ): array { return array( 'label' => '', 'value' => 0 ); }
|
||||
public function bonusesFor( array $ids ): array { return array(); }
|
||||
public function donations( ?int $sinceId, int $limit ): array { return $this->db; }
|
||||
public function recentDonations( int $limit ): array { return $this->db; }
|
||||
public function tiersFor( int $goalId ): array { return $this->tiers; }
|
||||
public function tiersReachedFor( array $ids ): array { ++$this->reachedQueries; return $this->unlocked; }
|
||||
};
|
||||
return new OverlayService( $probe );
|
||||
}
|
||||
|
||||
private function row( int $id ): array {
|
||||
return array( 'id' => $id, 'base_minor' => 2500, 'currency' => 'USD', 'donor_name' => 'Al', 'is_anonymous' => 0, 'message' => '', 'status' => 'completed', 'moderation' => 'approved' );
|
||||
}
|
||||
|
||||
public function test_untiered_goal_payload_is_unchanged(): void {
|
||||
$g = Payloads::goal( array( 'title' => 'G', 'currency' => 'USD', 'target_minor' => 20000 ), 5000 );
|
||||
$this->assertArrayNotHasKey( 'tiers', $g );
|
||||
$this->assertSame( 25, $g['percent'] );
|
||||
$this->assertSame( $g, Payloads::goal( array( 'title' => 'G', 'currency' => 'USD', 'target_minor' => 20000 ), 5000, array() ) );
|
||||
$this->assertArrayNotHasKey( 'tiers', $this->svc( array(), 100 )->payload( 'goal', 1 ) );
|
||||
}
|
||||
|
||||
public function test_tiered_goal_percent_is_within_tier_and_displays(): void {
|
||||
$g = $this->svc( $this->tiers( array( 1 ) ), 17500 )->payload( 'goal', 1 );
|
||||
$this->assertSame( 50, $g['percent'] );
|
||||
$this->assertSame( 17500, $g['raised_minor'] );
|
||||
$this->assertSame( '$175.00', $g['raised_display'] );
|
||||
$this->assertSame( 25000, $g['target_minor'] );
|
||||
$this->assertSame( '$250.00', $g['target_display'] );
|
||||
$t = $g['tiers'];
|
||||
$this->assertSame( 3, $t['count'] );
|
||||
$this->assertSame( 2, $t['index'] );
|
||||
$this->assertFalse( $t['all_reached'] );
|
||||
$this->assertSame( array( 'title' => 'Microphone', 'description' => 'd2', 'target_minor' => 25000, 'target_display' => '$250.00', 'floor_minor' => 10000 ), $t['current'] );
|
||||
}
|
||||
|
||||
public function test_tiered_goal_below_first_tier_and_all_reached(): void {
|
||||
$g = $this->svc( $this->tiers(), 2500 )->payload( 'goal', 1 );
|
||||
$this->assertSame( 25, $g['percent'] );
|
||||
$this->assertSame( 1, $g['tiers']['index'] );
|
||||
$this->assertSame( 0, $g['tiers']['current']['floor_minor'] );
|
||||
$all = $this->svc( $this->tiers( array( 1, 2, 3 ) ), 60000 )->payload( 'goal', 1 );
|
||||
$this->assertSame( 100, $all['percent'] );
|
||||
$this->assertTrue( $all['tiers']['all_reached'] );
|
||||
$this->assertNull( $all['tiers']['current'] );
|
||||
$this->assertSame( 3, $all['tiers']['index'] );
|
||||
$this->assertSame( '$500.00', $all['target_display'] );
|
||||
$this->assertSame( '$600.00', $all['raised_display'] );
|
||||
}
|
||||
|
||||
public function test_tier_text_is_sanitized(): void {
|
||||
$t = $this->tiers();
|
||||
$t[0]['title'] = '<script>x</script>Hi' . str_repeat( 'a', 300 );
|
||||
$g = $this->svc( $t, 0 )->payload( 'goal', 1 );
|
||||
$this->assertStringNotContainsString( '<', $g['tiers']['current']['title'] );
|
||||
$this->assertLessThanOrEqual( 120, mb_strlen( $g['tiers']['current']['title'] ) );
|
||||
}
|
||||
|
||||
public function test_alert_tiers_in_since_and_recent_with_one_query(): void {
|
||||
$probe = null;
|
||||
$svc = $this->svc( array(), 0, array( $this->row( 3 ), $this->row( 4 ) ), array( 3 => array( array( 'title' => 'Giveaway' ), array( 'title' => 'Microphone' ) ) ), $probe );
|
||||
$since = $svc->payload( 'alerts', 1, 0 );
|
||||
$this->assertSame( 1, $probe->reachedQueries );
|
||||
$recent = $svc->payload( 'alerts', 1, null, true );
|
||||
$this->assertSame( 2, $probe->reachedQueries );
|
||||
$this->assertSame( $since['alerts'], $recent['alerts'] );
|
||||
$this->assertSame( array( array( 'title' => 'Giveaway' ), array( 'title' => 'Microphone' ) ), $recent['alerts'][0]['tiers'] );
|
||||
$this->assertSame( array(), $recent['alerts'][1]['tiers'] );
|
||||
$svc->payload( 'alerts', 1, null ); // baseline poll: no lookup
|
||||
$this->assertSame( 2, $probe->reachedQueries );
|
||||
}
|
||||
|
||||
public function test_alert_tier_events_sanitized_and_capped(): void {
|
||||
$ev = array( array( 'title' => '<b>Hi</b>' ), array( 'title' => '' ), 'junk', array( 'title' => str_repeat( 'é', 200 ) ) );
|
||||
for ( $i = 0; $i < 9; $i++ ) {
|
||||
$ev[] = array( 'title' => "T$i" );
|
||||
}
|
||||
$out = Payloads::tierEvents( $ev );
|
||||
$this->assertCount( 5, $out );
|
||||
$this->assertSame( array( 'title' => 'Hi' ), $out[0] );
|
||||
$this->assertSame( 80, mb_strlen( $out[1]['title'] ) );
|
||||
$this->assertSame( array(), Payloads::tierEvents( 'nope' ) );
|
||||
}
|
||||
|
||||
public function test_etag_changes_when_a_tier_unlocks_or_current_tier_moves(): void {
|
||||
$a = Payloads::etag( $this->svc( array(), 0, array( $this->row( 3 ) ) )->payload( 'alerts', 1, null, true ) );
|
||||
$b = Payloads::etag( $this->svc( array(), 0, array( $this->row( 3 ) ), array( 3 => array( array( 'title' => 'X' ) ) ) )->payload( 'alerts', 1, null, true ) );
|
||||
$this->assertNotSame( $a, $b );
|
||||
$g1 = Payloads::etag( $this->svc( $this->tiers(), 9000 )->payload( 'goal', 1 ) );
|
||||
$g2 = Payloads::etag( $this->svc( $this->tiers( array( 1 ) ), 10000 )->payload( 'goal', 1 ) );
|
||||
$this->assertNotSame( $g1, $g2 );
|
||||
}
|
||||
}
|
||||
@@ -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'] );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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' ) ) );
|
||||
|
||||
@@ -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() ) );
|
||||
}
|
||||
}
|
||||
@@ -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 );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Overlay\Payloads;
|
||||
use StreamGoals\Overlay\Progress;
|
||||
|
||||
final class ProgressTest extends TestCase {
|
||||
|
||||
private function goal( array $over = array() ): array {
|
||||
return $over + array( 'id' => 7, 'title' => 'New mic', 'target_minor' => 10000, 'currency' => 'USD', 'status' => 'active', 'close_at_target' => 0, 'counts_fees' => 0 );
|
||||
}
|
||||
|
||||
/** @dataProvider flags */
|
||||
public function test_show_progress_attribute_parsing( $raw, bool $expected ): void {
|
||||
$this->assertSame( $expected, Progress::flag( $raw, true ) );
|
||||
}
|
||||
|
||||
public static function flags(): array {
|
||||
return array(
|
||||
array( 'yes', true ), array( 'YES', true ), array( 'true', true ), array( '1', true ), array( 1, true ), array( ' on ', true ),
|
||||
array( 'no', false ), array( 'No', false ), array( 'false', false ), array( '0', false ), array( 0, false ), array( 'off', false ),
|
||||
array( '', true ), array( null, true ), array( 'banana', true ), array( array( 'x' ), true ),
|
||||
);
|
||||
}
|
||||
|
||||
public function test_flag_default_is_respected_for_unknown_values(): void {
|
||||
$this->assertFalse( Progress::flag( 'banana', false ) );
|
||||
$this->assertFalse( Progress::flag( null, false ) );
|
||||
}
|
||||
|
||||
public function test_percentage_is_clamped_and_target_zero_is_safe(): void {
|
||||
$this->assertSame( 0, Progress::payload( $this->goal( array( 'target_minor' => 0 ) ), 500 )['percent'] );
|
||||
$this->assertSame( 100, Progress::payload( $this->goal(), 999999 )['percent'] );
|
||||
$this->assertSame( 0, Progress::payload( $this->goal(), -50 )['percent'] );
|
||||
$this->assertSame( 25, Progress::payload( $this->goal(), 2500 )['percent'] );
|
||||
}
|
||||
|
||||
public function test_numbers_match_the_overlay_goal_payload(): void {
|
||||
$p = Progress::payload( $this->goal(), 2500 );
|
||||
$o = Payloads::goal( $this->goal(), 2500 );
|
||||
foreach ( array( 'raised_minor', 'target_minor', 'percent', 'raised_display', 'target_display', 'currency', 'title' ) as $k ) {
|
||||
$this->assertSame( $o[ $k ], $p[ $k ], $k );
|
||||
}
|
||||
$this->assertSame( '$25.00', $p['raised_display'] );
|
||||
$this->assertSame( '$100.00', $p['target_display'] );
|
||||
$this->assertFalse( $p['reached'] );
|
||||
$this->assertNull( $p['tier'] );
|
||||
}
|
||||
|
||||
public function test_tiered_goal_shows_current_tier_and_matches_overlay(): void {
|
||||
$tiers = array(
|
||||
array( 'id' => 1, 'target_minor' => 5000, 'title' => 'Giveaway', 'description' => 'secret', 'reached_at' => '2026-01-01 00:00:00' ),
|
||||
array( 'id' => 2, 'target_minor' => 20000, 'title' => 'Microphone', 'description' => 'secret', 'reached_at' => null ),
|
||||
);
|
||||
$g = $this->goal( array( 'target_minor' => 20000 ) );
|
||||
$p = Progress::payload( $g, 8000, $tiers );
|
||||
$o = Payloads::goal( $g, 8000, $tiers );
|
||||
$this->assertSame( $o['percent'], $p['percent'] );
|
||||
$this->assertSame( 20000, $p['target_minor'] );
|
||||
$this->assertSame( array( 'index' => 2, 'count' => 2, 'title' => 'Microphone', 'target_minor' => 20000, 'target_display' => '$200.00' ), $p['tier'] );
|
||||
$this->assertFalse( $p['reached'] );
|
||||
$this->assertStringNotContainsString( 'secret', json_encode( $p ) );
|
||||
}
|
||||
|
||||
public function test_reached_states(): void {
|
||||
$closed = $this->goal( array( 'status' => 'complete', 'close_at_target' => 1 ) );
|
||||
$this->assertTrue( Progress::payload( $closed, 10000 )['reached'] );
|
||||
$this->assertTrue( Progress::payload( $closed, 0 )['reached'], 'closed at target wins even if numbers lag' );
|
||||
$this->assertTrue( Progress::payload( $this->goal(), 10000 )['reached'], 'raised >= target' );
|
||||
$this->assertFalse( Progress::payload( $this->goal( array( 'target_minor' => 0 ) ), 10000 )['reached'], 'no target never counts as reached' );
|
||||
$done = array( array( 'id' => 1, 'target_minor' => 5000, 'title' => 'A', 'reached_at' => 'x' ) );
|
||||
$p = Progress::payload( $this->goal( array( 'target_minor' => 5000 ) ), 5000, $done );
|
||||
$this->assertTrue( $p['reached'] );
|
||||
$this->assertNull( $p['tier'] );
|
||||
}
|
||||
|
||||
public function test_public_payload_has_exactly_the_whitelisted_non_pii_keys(): void {
|
||||
$goal = $this->goal() + array( 'paypal_secret' => 'x', 'notes' => 'private' );
|
||||
$p = Progress::payload( $goal, 100 );
|
||||
$this->assertSame(
|
||||
array( 'currency', 'goal_id', 'percent', 'raised_display', 'raised_minor', 'reached', 'target_display', 'target_minor', 'tier', 'title' ),
|
||||
( static function ( array $a ): array { ksort( $a ); return array_keys( $a ); } )( $p )
|
||||
);
|
||||
$json = json_encode( $p );
|
||||
foreach ( array( 'paypal', 'notes', 'email', 'donor', 'message', 'display_name' ) as $bad ) {
|
||||
$this->assertStringNotContainsString( $bad, $json );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_html_is_accessible_and_escaped(): void {
|
||||
$p = Progress::payload( $this->goal( array( 'title' => '<b>Mic</b>' ) ), 2500 );
|
||||
$html = Progress::html( $p, array( 'reached' => 'Goal reached', 'of' => '%1$s of %2$s', 'tier' => 'Tier: %1$s (%2$s)', 'label' => 'Progress: %s' ) );
|
||||
$this->assertStringContainsString( 'role="progressbar"', $html );
|
||||
$this->assertStringContainsString( 'aria-valuenow="25"', $html );
|
||||
$this->assertStringContainsString( 'aria-valuemin="0"', $html );
|
||||
$this->assertStringContainsString( 'aria-valuemax="100"', $html );
|
||||
$this->assertStringContainsString( 'aria-label="Progress: <b>Mic</b>"', $html );
|
||||
$this->assertStringContainsString( '$25.00 of $100.00', $html );
|
||||
$this->assertStringContainsString( 'width:25%', $html );
|
||||
$this->assertStringNotContainsString( '<b>', $html );
|
||||
}
|
||||
|
||||
public function test_html_reached_and_tier_lines(): void {
|
||||
$labels = array( 'reached' => 'Goal reached', 'of' => '%1$s of %2$s', 'tier' => 'Tier: %1$s (%2$s)', 'label' => 'Progress: %s' );
|
||||
$closed = Progress::html( Progress::payload( $this->goal( array( 'status' => 'complete', 'close_at_target' => 1 ) ), 10000 ), $labels );
|
||||
$this->assertStringContainsString( 'Goal reached', $closed );
|
||||
$this->assertStringContainsString( 'sg-progress-reached', $closed );
|
||||
$this->assertStringContainsString( 'aria-valuenow="100"', $closed );
|
||||
$tiers = array( array( 'id' => 2, 'target_minor' => 20000, 'title' => 'Mic', 'reached_at' => null ) );
|
||||
$t = Progress::html( Progress::payload( $this->goal( array( 'target_minor' => 20000 ) ), 100, $tiers ), $labels );
|
||||
$this->assertStringContainsString( 'Tier: Mic ($200.00)', $t );
|
||||
}
|
||||
|
||||
public function test_assets_support_reduced_motion_and_polling_rules(): void {
|
||||
$root = dirname( __DIR__, 2 ) . '/assets/donate/';
|
||||
$css = (string) file_get_contents( $root . 'donate.css' );
|
||||
$js = (string) file_get_contents( $root . 'donate.js' );
|
||||
$this->assertStringContainsString( 'prefers-reduced-motion', $css );
|
||||
$this->assertStringContainsString( 'visibilityState', $js );
|
||||
$this->assertStringContainsString( '30000', $js );
|
||||
$this->assertStringNotContainsString( 'innerHTML', $js );
|
||||
}
|
||||
|
||||
public function test_route_and_shortcodes_are_registered(): void {
|
||||
$php = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/Rest/DonateController.php' );
|
||||
$this->assertStringContainsString( "'/progress'", $php );
|
||||
$this->assertStringContainsString( "add_shortcode( 'streamgoals_progress'", $php );
|
||||
$this->assertStringContainsString( "'show_progress' => 'yes'", $php );
|
||||
$this->assertMatchesRegularExpression( "/function progress_route.*self::limit\( 'progress'/s", $php );
|
||||
}
|
||||
}
|
||||
@@ -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' ) );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Tiers\TierPolicy;
|
||||
|
||||
final class TierPolicyTest extends TestCase {
|
||||
|
||||
private function tiers( array $reachedIds = array() ): array {
|
||||
$rows = array( array( 1, 10000, 'Giveaway' ), array( 2, 25000, 'Microphone' ), array( 3, 50000, '24h stream' ) );
|
||||
$out = array();
|
||||
foreach ( $rows as [ $id, $t, $title ] ) {
|
||||
$out[] = array( 'id' => $id, 'target_minor' => $t, 'title' => $title, 'description' => '', 'reached_at' => in_array( $id, $reachedIds, true ) ? '2026-01-01 00:00:00' : null );
|
||||
}
|
||||
return array_reverse( $out ); // unsorted on purpose
|
||||
}
|
||||
|
||||
public function test_current_tier_and_index(): void {
|
||||
$this->assertSame( 1, TierPolicy::currentTier( $this->tiers() )['id'] );
|
||||
$this->assertSame( 1, TierPolicy::currentIndex( $this->tiers() ) );
|
||||
$this->assertSame( 3, TierPolicy::currentTier( $this->tiers( array( 1, 2 ) ) )['id'] );
|
||||
$this->assertSame( 3, TierPolicy::currentIndex( $this->tiers( array( 1, 2 ) ) ) );
|
||||
$this->assertNull( TierPolicy::currentTier( $this->tiers( array( 1, 2, 3 ) ) ) );
|
||||
$this->assertSame( 3, TierPolicy::currentIndex( $this->tiers( array( 1, 2, 3 ) ) ) );
|
||||
$this->assertTrue( TierPolicy::allReached( $this->tiers( array( 1, 2, 3 ) ) ) );
|
||||
$this->assertFalse( TierPolicy::allReached( $this->tiers( array( 1 ) ) ) );
|
||||
$this->assertFalse( TierPolicy::allReached( array() ) );
|
||||
$this->assertSame( 0, TierPolicy::currentIndex( array() ) );
|
||||
}
|
||||
|
||||
public function test_floor(): void {
|
||||
$this->assertSame( 0, TierPolicy::floorMinor( $this->tiers() ) );
|
||||
$this->assertSame( 10000, TierPolicy::floorMinor( $this->tiers( array( 1 ) ) ) );
|
||||
$this->assertSame( 25000, TierPolicy::floorMinor( $this->tiers( array( 1, 2 ) ) ) );
|
||||
$this->assertSame( 50000, TierPolicy::floorMinor( $this->tiers( array( 1, 2, 3 ) ) ), 'all reached: top target' );
|
||||
}
|
||||
|
||||
public function test_percent_within_tier_clamped(): void {
|
||||
$this->assertSame( 0, TierPolicy::percent( 0, 0, 10000 ) );
|
||||
$this->assertSame( 50, TierPolicy::percent( 5000, 0, 10000 ) );
|
||||
$this->assertSame( 50, TierPolicy::percent( 17500, 10000, 25000 ) );
|
||||
$this->assertSame( 0, TierPolicy::percent( 10000, 10000, 25000 ), 'exactly at the floor' );
|
||||
$this->assertSame( 0, TierPolicy::percent( 500, 10000, 25000 ), 'raised below the floor clamps to 0' );
|
||||
$this->assertSame( 100, TierPolicy::percent( 25000, 10000, 25000 ), 'exactly at the target' );
|
||||
$this->assertSame( 100, TierPolicy::percent( 99999, 10000, 25000 ), 'above clamps to 100' );
|
||||
$this->assertSame( 0, TierPolicy::percent( 5, 100, 100 ), 'degenerate range, not reached' );
|
||||
$this->assertSame( 100, TierPolicy::percent( 100, 100, 100 ), 'degenerate range, reached' );
|
||||
}
|
||||
|
||||
public function test_percent_for_walks_the_ladder(): void {
|
||||
$this->assertSame( 25, TierPolicy::percentFor( $this->tiers(), 2500 ) );
|
||||
$this->assertSame( 0, TierPolicy::percentFor( $this->tiers( array( 1 ) ), 10000 ) );
|
||||
$this->assertSame( 50, TierPolicy::percentFor( $this->tiers( array( 1 ) ), 17500 ) );
|
||||
$this->assertSame( 100, TierPolicy::percentFor( $this->tiers( array( 1, 2, 3 ) ), 60000 ) );
|
||||
$this->assertSame( 0, TierPolicy::percentFor( array(), 500 ) );
|
||||
$this->assertSame( 7500, TierPolicy::remainingMinor( $this->tiers(), 2500 ) );
|
||||
$this->assertSame( 0, TierPolicy::remainingMinor( $this->tiers( array( 1, 2, 3 ) ), 60000 ) );
|
||||
}
|
||||
|
||||
public function test_newly_reached_several_in_one_donation_in_order(): void {
|
||||
$ids = array_column( TierPolicy::newlyReached( $this->tiers(), 30000 ), 'id' );
|
||||
$this->assertSame( array( 1, 2 ), $ids );
|
||||
$this->assertSame( array( 1, 2, 3 ), array_column( TierPolicy::newlyReached( $this->tiers(), 50000 ), 'id' ), 'exactly at the last target counts' );
|
||||
$this->assertSame( array(), TierPolicy::newlyReached( $this->tiers(), 9999 ) );
|
||||
$this->assertSame( array( 2 ), array_column( TierPolicy::newlyReached( $this->tiers( array( 1 ) ), 30000 ), 'id' ), 'reached ones are skipped' );
|
||||
}
|
||||
|
||||
public function test_replay_is_idempotent_at_policy_level(): void {
|
||||
$tiers = $this->tiers();
|
||||
$first = TierPolicy::newlyReached( $tiers, 30000 );
|
||||
foreach ( $tiers as &$t ) {
|
||||
if ( in_array( $t['id'], array_column( $first, 'id' ), true ) ) {
|
||||
$t['reached_at'] = '2026-02-02 00:00:00';
|
||||
}
|
||||
}
|
||||
unset( $t );
|
||||
$this->assertSame( array(), TierPolicy::newlyReached( $tiers, 30000 ) );
|
||||
$this->assertSame( array(), TierPolicy::newlyReached( $tiers, 12000 ), 'a lower total (refund) never un-reaches or re-reaches' );
|
||||
}
|
||||
|
||||
public function test_derived_target_is_highest(): void {
|
||||
$this->assertSame( 50000, TierPolicy::derivedGoalTarget( $this->tiers() ) );
|
||||
$this->assertSame( 0, TierPolicy::derivedGoalTarget( array() ) );
|
||||
}
|
||||
|
||||
public function test_status(): void {
|
||||
$t = $this->tiers( array( 1 ) );
|
||||
$by = array();
|
||||
foreach ( $t as $row ) {
|
||||
$by[ $row['id'] ] = TierPolicy::status( $t, $row );
|
||||
}
|
||||
$this->assertSame( array( 3 => 'upcoming', 2 => 'current', 1 => 'reached' ), $by );
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ validation */
|
||||
|
||||
private function v( ?int $target, string $title = 'Mic', string $desc = '', ?int $edit = null, int $raised = 0, ?array $tiers = null ): array {
|
||||
return TierPolicy::validate( $tiers ?? $this->tiers( array( 1 ) ), $edit, $target, $title, $desc, $raised, 100, '$1.00' );
|
||||
}
|
||||
|
||||
public function test_valid_new_tier(): void {
|
||||
$r = $this->v( 70000, ' New desk ', ' nice ', null, 12000 );
|
||||
$this->assertNull( $r['error'] );
|
||||
$this->assertSame( array( 'target_minor' => 70000, 'title' => 'New desk', 'description' => 'nice' ), $r['data'] );
|
||||
}
|
||||
|
||||
public function test_rejects_bad_values(): void {
|
||||
$this->assertNotNull( $this->v( null )['error'] );
|
||||
$this->assertNotNull( $this->v( 0 )['error'] );
|
||||
$this->assertStringContainsString( 'minimum', (string) $this->v( 50 )['error'] );
|
||||
$this->assertStringContainsString( 'title', (string) $this->v( 70000, ' ' )['error'] . ' title' );
|
||||
$this->assertNotNull( $this->v( 70000, ' ' )['error'] );
|
||||
$this->assertNotNull( $this->v( 70000, str_repeat( 'a', 121 ) )['error'] );
|
||||
$this->assertNull( $this->v( 70000, str_repeat( 'a', 120 ) )['error'] );
|
||||
$this->assertNotNull( $this->v( 70000, 'x', str_repeat( 'd', 256 ) )['error'] );
|
||||
$this->assertNull( $this->v( 70000, 'x', str_repeat( 'd', 255 ) )['error'] );
|
||||
}
|
||||
|
||||
public function test_target_must_be_unique_and_above_raised(): void {
|
||||
$this->assertStringContainsString( 'already', (string) $this->v( 25000 )['error'] );
|
||||
$this->assertStringContainsString( 'already raised', (string) $this->v( 20000, 'x', '', null, 20000 )['error'], 'equal to raised unlocks instantly' );
|
||||
$this->assertNull( $this->v( 20001, 'x', '', null, 20000 )['error'] );
|
||||
}
|
||||
|
||||
public function test_reached_tier_target_is_locked_but_text_editable(): void {
|
||||
$r = $this->v( 999999, 'Renamed', 'd', 1, 12000 );
|
||||
$this->assertNull( $r['error'] );
|
||||
$this->assertSame( 10000, $r['data']['target_minor'] );
|
||||
$this->assertSame( 'Renamed', $r['data']['title'] );
|
||||
$r2 = $this->v( null, 'Renamed', '', 1, 12000 );
|
||||
$this->assertSame( 10000, $r2['data']['target_minor'] );
|
||||
}
|
||||
|
||||
public function test_edit_unreached_keeps_or_moves_target(): void {
|
||||
$this->assertNull( $this->v( 25000, 'Mic2', '', 2, 12000 )['error'], 'unchanged target is fine' );
|
||||
$this->assertNull( $this->v( 30000, 'Mic', '', 2, 12000 )['error'] );
|
||||
$this->assertStringContainsString( 'already', (string) $this->v( 50000, 'Mic', '', 2, 12000 )['error'] );
|
||||
$this->assertStringContainsString( 'no longer', (string) $this->v( 30000, 'Mic', '', 99, 12000 )['error'] );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?php
|
||||
declare( strict_types=1 );
|
||||
|
||||
namespace StreamGoals\Tests\Unit;
|
||||
|
||||
use PHPUnit\Framework\TestCase;
|
||||
use StreamGoals\Tiers\TierRepository;
|
||||
|
||||
final class TierRepositoryTest extends TestCase {
|
||||
|
||||
private function fake( array $rows = array(), $var = null ): object {
|
||||
if ( ! defined( 'ARRAY_A' ) ) {
|
||||
define( 'ARRAY_A', 'ARRAY_A' );
|
||||
}
|
||||
return new class( $rows, $var ) {
|
||||
public string $prefix = 'wp_';
|
||||
public array $sql = array();
|
||||
public int $insert_id = 9;
|
||||
public array $queryResults = array();
|
||||
public function __construct( public array $rows, public $var ) {}
|
||||
public function prepare( string $q, ...$args ): string {
|
||||
$i = 0;
|
||||
return (string) preg_replace_callback( '/%[dsf]/', static function ( $m ) use ( &$i, $args ) {
|
||||
$v = $args[ $i++ ];
|
||||
return '%s' === $m[0] ? "'" . $v . "'" : (string) $v;
|
||||
}, $q );
|
||||
}
|
||||
public function query( string $q ) { $this->sql[] = $q; return array_shift( $this->queryResults ) ?? 1; }
|
||||
public function get_results( string $q, $o = null ): array { $this->sql[] = $q; return $this->rows; }
|
||||
public function get_var( string $q ) { $this->sql[] = $q; return $this->var; }
|
||||
public function insert( string $t, array $d, array $f ) { $this->sql[] = 'INSERT ' . $t . ' ' . json_encode( $d ); return 1; }
|
||||
};
|
||||
}
|
||||
|
||||
private function row( int $id, int $target, ?string $reached = null ): array {
|
||||
return array( 'id' => (string) $id, 'goal_id' => '7', 'target_minor' => (string) $target, 'title' => "T$id", 'description' => '', 'reached_at' => $reached, 'reached_donation_id' => null, 'created_at' => '2026-01-01 00:00:00' );
|
||||
}
|
||||
|
||||
public function test_for_goal_orders_by_target_and_casts(): void {
|
||||
$db = $this->fake( array( $this->row( 1, 10000 ) ) );
|
||||
$rows = ( new TierRepository( $db ) )->forGoal( 7 );
|
||||
$this->assertStringContainsString( 'WHERE goal_id = 7 ORDER BY target_minor ASC', $db->sql[0] );
|
||||
$this->assertSame( 10000, $rows[0]['target_minor'] );
|
||||
$this->assertNull( $rows[0]['reached_at'] );
|
||||
}
|
||||
|
||||
public function test_mark_reached_is_atomic_per_tier_and_only_for_reachable(): void {
|
||||
$db = $this->fake( array( $this->row( 1, 10000 ), $this->row( 2, 25000 ), $this->row( 3, 50000 ), $this->row( 4, 5000, '2026-01-01 00:00:00' ) ) );
|
||||
$marked = ( new TierRepository( $db ) )->markReached( 7, 30000, 55 );
|
||||
$this->assertSame( array( 1, 2 ), $marked );
|
||||
$updates = array_values( array_filter( $db->sql, static fn( $q ) => str_starts_with( $q, 'UPDATE' ) ) );
|
||||
$this->assertCount( 2, $updates );
|
||||
foreach ( $updates as $q ) {
|
||||
$this->assertStringContainsString( 'reached_at IS NULL', $q );
|
||||
$this->assertStringContainsString( 'reached_donation_id = 55', $q );
|
||||
$this->assertStringContainsString( 'UPDATE wp_sg_goal_tiers', $q );
|
||||
}
|
||||
}
|
||||
|
||||
public function test_mark_reached_replay_loses_race_and_reports_nothing(): void {
|
||||
$db = $this->fake( array( $this->row( 1, 10000 ) ) );
|
||||
$db->queryResults = array( 0 ); // someone else already marked it
|
||||
$this->assertSame( array(), ( new TierRepository( $db ) )->markReached( 7, 30000, 55 ) );
|
||||
}
|
||||
|
||||
public function test_mark_reached_ignores_invalid_ids(): void {
|
||||
$db = $this->fake( array( $this->row( 1, 10000 ) ) );
|
||||
$this->assertSame( array(), ( new TierRepository( $db ) )->markReached( 0, 30000, 55 ) );
|
||||
$this->assertSame( array(), ( new TierRepository( $db ) )->markReached( 7, 30000, 0 ) );
|
||||
$this->assertSame( array(), $db->sql );
|
||||
}
|
||||
|
||||
public function test_reached_by_donation_is_one_query_and_grouped(): void {
|
||||
$db = $this->fake( array( array( 'reached_donation_id' => '5', 'title' => 'A' ), array( 'reached_donation_id' => '5', 'title' => 'B' ), array( 'reached_donation_id' => '6', 'title' => 'C' ) ) );
|
||||
$out = ( new TierRepository( $db ) )->reachedByDonation( array( 5, 6, 6, 0, -1 ) );
|
||||
$this->assertCount( 1, $db->sql );
|
||||
$this->assertStringContainsString( 'reached_donation_id IN (5,6)', $db->sql[0] );
|
||||
$this->assertSame( array( 5 => array( array( 'title' => 'A' ), array( 'title' => 'B' ) ), 6 => array( array( 'title' => 'C' ) ) ), $out );
|
||||
$this->assertSame( array(), ( new TierRepository( $this->fake() ) )->reachedByDonation( array() ) );
|
||||
}
|
||||
|
||||
public function test_sync_goal_target_sets_highest_and_skips_untiered(): void {
|
||||
$db = $this->fake( array(), '50000' );
|
||||
$this->assertTrue( ( new TierRepository( $db ) )->syncGoalTarget( 7 ) );
|
||||
$this->assertStringContainsString( 'MAX(target_minor)', $db->sql[0] );
|
||||
$this->assertStringContainsString( 'UPDATE wp_sg_goals SET target_minor = 50000 WHERE id = 7', $db->sql[1] );
|
||||
$none = $this->fake( array(), null );
|
||||
$this->assertFalse( ( new TierRepository( $none ) )->syncGoalTarget( 7 ) );
|
||||
$this->assertCount( 1, $none->sql, 'no UPDATE when the goal has no tiers' );
|
||||
}
|
||||
|
||||
public function test_installer_defines_tier_table_unique_key_and_version(): 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( 4, (int) $m[1] );
|
||||
$this->assertStringContainsString( 'CREATE TABLE {$p}goal_tiers (', $src );
|
||||
$this->assertStringContainsString( 'UNIQUE KEY goal_target (goal_id,target_minor)', $src );
|
||||
$this->assertStringContainsString( 'reached_donation_id BIGINT UNSIGNED NULL', $src );
|
||||
}
|
||||
|
||||
public function test_donation_store_marks_tiers_before_close_at_target(): void {
|
||||
$src = (string) file_get_contents( dirname( __DIR__, 2 ) . '/includes/PayPal/DonationStore.php' );
|
||||
$start = strpos( $src, 'function notify_applied' );
|
||||
$body = substr( $src, $start, strpos( $src, 'function close_goal_if_target_reached' ) - $start );
|
||||
$a = strpos( $body, 'Recorder::forDonation' );
|
||||
$tier = strpos( $body, 'Tiers\\Recorder::forDonation' );
|
||||
$close = strpos( $body, 'self::close_goal_if_target_reached' );
|
||||
$this->assertNotFalse( $tier );
|
||||
$this->assertNotFalse( $a );
|
||||
$this->assertLessThan( $tier, strpos( $body, 'call_engine' ), 'engine first' );
|
||||
$this->assertLessThan( $close, $tier, 'tiers before the close check' );
|
||||
}
|
||||
}
|
||||
@@ -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 ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 ) );
|
||||
}
|
||||
}
|
||||
@@ -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 ) );
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
Reference in new issue
Block a user