Initialize public HG Inschrijvingen source

This commit is contained in:
parkel committed 2026-11-18 15:51:55 +01:00
commit c84fea26a0
23 files changed
+1623

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
/dist/
__pycache__/
*.pyc
+338
View File
@@ -0,0 +1,338 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
<https://fsf.org/>
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, see <https://www.gnu.org/licenses/>.
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 Moe Ghoul>, 1 April 1989
Moe Ghoul, 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.
+43
View File
@@ -0,0 +1,43 @@
# HG Inschrijvingen
WordPress-plug-in voor activiteiten, cursusmomenten en inschrijvingen. Een aanvraag reserveert direct plaatsen. De beheerder bevestigt of weigert de deelname.
## Installatie
Vereist WordPress 6.5 of hoger, PHP 8.1 of hoger en InnoDB. Kies een Inschrijvingen-ZIP uit de releases of bouw `dist/hg-registrations.zip` met `python3 scripts/build.py`. Upload de ZIP via **Plugins → Nieuwe plugin → Plugin uploaden** en activeer de plug-in. [Openbare releases](https://code.hosting.hippogrief.nl/hippogrief/wp-plugins/releases)
## Gebruik
1. Publiceer een activiteit via **HG Plugins → Inschrijvingen → Activiteiten**.
2. Open **Momenten**, vul datum, tijd, locatie en capaciteit in en zet het moment open.
3. Plaats `[hg_registrations]` in een shortcodeblok voor de agenda. Gebruik `[hg_registrations activity="123"]` voor één activiteit.
4. Stel het organisatieadres in onder **Instellingen** en behandel aanvragen onder **Inschrijvingen**.
## Reserveringen en e-mail
- Zowel gereserveerde als bevestigde deelnemers tellen mee voor de capaciteit. Afwijzen of annuleren geeft plaatsen vrij.
- Een contactpersoon kan meerdere deelnemers aanmelden. Datums worden getoond in de WordPress-tijdzone.
- Activiteiten met momenten blijven beschikbaar voor beheer. Een concept of een activiteit in de prullenbak sluit nieuwe aanvragen.
- De plug-in gebruikt de WordPress-mailvoorziening voor nieuwe reserveringen en statuswijzigingen. Bij een mislukte verzending blijft de reservering bewaard en kan de beheerder de melding opnieuw versturen.
- Beheerders kunnen inschrijvingen exporteren met één rij per deelnemer. Gegevens blijven behouden bij deactiveren of verwijderen.
## Bouwen en testen
De build controleert de gebundelde HG-bestanden tegen `shared.lock.json`. Gebruik een geïsoleerde WordPress-installatie met `WP_ENVIRONMENT_TYPE` ingesteld op `staging` en de plug-in actief. Voer de commando’s uit vanuit de bronrepository als de gebruiker die WordPress beheert.
```sh
wp --path=/pad/naar/wordpress eval-file "$PWD/tests/integration.php"
python3 tests/concurrency.py --wp-path /pad/naar/wordpress
```
De integratietest onderschept e-mail en beide tests ruimen hun tijdelijke gegevens op. Kopieer voor de HTTP-test [de testfixture die e-mail blokkeert](tests/fixtures/disable-mail.php) naar `wp-content/mu-plugins/hgr-test-mail.php` op de geïsoleerde testsite. Zet `admin_user` en `admin_password` voor die site in een lokaal JSON-bestand buiten de repo. Bij HTTP Basic Auth voeg je `preview_user` en `preview_password` toe. De test gebruikt de WordPress-URL en maakt zelf een tijdelijke testpagina. Gebruik HTTPS of een loopbackadres en verwijder de MU-fixture na de test.
```sh
python3 tests/http_integration.py --wp-path /pad/naar/wordpress --credentials-file /pad/naar/staging-inlog.json
```
Open **HG Plugins → Updates** om openbare plug-inreleases te controleren. [Gedeelde code en releases](https://code.hosting.hippogrief.nl/hippogrief/wp-plugins)
## Licentie
GPL-2.0-or-later. Zie [LICENSE](LICENSE).
+5
View File
@@ -0,0 +1,5 @@
.hgr-admin{max-width:1160px}.hgr-admin-header,.hgr-panel-heading{display:flex;justify-content:space-between;align-items:center;gap:20px;margin:24px 0}.hgr-admin-header h1{font-size:25px}.hgr-admin-header p,.hgr-panel-heading p{margin:8px 0;color:#50575e}.hgr-language-status{background:#e8eef4;border:1px solid #d3dee9;padding:8px 13px;border-radius:20px;white-space:nowrap}.hgr-admin-tabs{display:flex;flex-wrap:wrap;gap:5px;border-bottom:1px solid #c3c4c7;margin-bottom:24px}.hgr-admin-tabs a{color:#50575e;text-decoration:none;padding:14px 22px;font-size:15px;font-weight:600;border-bottom:3px solid transparent}.hgr-admin-tabs a.is-active{color:#135e96;border-color:#2271b1}.hgr-admin-tabs span{background:#e2e4e7;border-radius:15px;padding:2px 7px;margin-left:6px}.hgr-admin-panel[hidden]{display:none}.hgr-admin-card,.hgr-workflow{background:#fff;border:1px solid #dcdcde;border-radius:8px;margin:0 0 20px}.hgr-admin-card{padding:24px 28px}.hgr-admin-card h2{margin-top:0}.hgr-admin-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px 26px}.hgr-admin-field{display:flex;flex-direction:column;gap:7px;margin:14px 0}.hgr-admin-field>span,.hgr-field-matrix label>span{font-weight:600;color:#1d2327}.hgr-admin-field input,.hgr-admin-field textarea{width:100%;max-width:none;min-height:38px}.hgr-admin-field small{font-weight:400;color:#646970;line-height:1.6}.hgr-admin-note{padding:15px 18px;background:#f0f6fc;border-left:3px solid #72aee6;margin-top:24px}.hgr-workflow>summary{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:20px 24px;cursor:pointer;font-size:16px;font-weight:600;list-style:none}.hgr-workflow>summary::before{content:'›';font-size:24px;margin-right:5px}.hgr-workflow[open]>summary::before{transform:rotate(90deg)}.hgr-workflow-name{flex:1}.hgr-workflow-badge{font-size:12px;background:#edf6ef;color:#245c31;padding:4px 9px;border-radius:15px}.hgr-workflow-body{padding:0 24px 24px;border-top:1px solid #e8e8ea}.hgr-workflow-toolbar{display:flex;justify-content:space-between;gap:20px;padding:20px 0}.hgr-field-matrix{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}.hgr-field-matrix label{display:flex;flex-direction:column;gap:8px}.hgr-field-matrix select{max-width:none;width:100%;min-height:36px}.hgr-checkbox{display:block;margin-top:20px}.hgr-flow-services,.hgr-flow-times{border-top:1px solid #e8e8ea;margin-top:24px;padding-top:6px}.hgr-service-row{display:flex;align-items:center;gap:16px}.hgr-service-row .hgr-admin-field{flex:1;min-width:0}.hgr-service-row button{white-space:nowrap;margin-top:18px}.hgr-workflow-texts{margin-top:24px;border-top:1px solid #e8e8ea;padding-top:18px}.hgr-workflow-texts summary{cursor:pointer;font-weight:600}.hgr-save-bar{position:sticky;bottom:0;display:flex;align-items:center;gap:18px;background:#fff;border:1px solid #dcdcde;border-radius:8px;padding:16px 24px;margin-top:25px;z-index:5;box-shadow:0 -2px 8px #00000008}.hgr-save-bar span{color:#646970}.hgr-admin [hidden]{display:none!important}@media(max-width:782px){.hgr-admin-header,.hgr-panel-heading{align-items:flex-start;flex-direction:column}.hgr-admin-grid{grid-template-columns:1fr}.hgr-field-matrix{grid-template-columns:1fr 1fr}.hgr-admin-card{padding:20px}.hgr-service-row{flex-wrap:wrap}.hgr-admin-tabs a{padding:12px}.hgr-save-bar{flex-wrap:wrap}.hgr-language-status{white-space:normal}}
.hgr-tech-table{overflow-x:auto}.hgr-tech-table th,.hgr-tech-table td{padding:12px 14px}.hgr-tech-table td:first-child{font-weight:600}
.hgr-table{overflow-x:auto}.hgr-admin table td,.hgr-admin table th{padding:12px 14px;vertical-align:top}.hgr-admin-field select{min-height:38px;width:100%;max-width:none}.hgr-badge{display:inline-block;border-radius:15px;padding:4px 9px;background:#edf2f7;font-size:12px;white-space:nowrap}.hgr-confirmed{background:#edf6ef;color:#245c31}.hgr-reserved{background:#fff5dc;color:#755019}.hgr-cancelled,.hgr-declined{background:#f4ecec;color:#833b3b}
+1
View File
@@ -0,0 +1 @@
.hgr{--hgr-accent:var(--wp--preset--color--primary,#155a6c);margin:2rem 0}.hgr-moment{border:1px solid #dce4e6;border-radius:10px;background:#fff;margin:0 0 1.4rem;padding:1.8rem;color:#26343b}.hgr-moment-head{display:flex;justify-content:space-between;gap:24px}.hgr h3{margin:0 0 .5rem}.hgr-moment p{margin:.5rem 0;line-height:1.7}.hgr-capacity{display:flex;flex-direction:column;text-align:right;white-space:nowrap}.hgr-capacity strong{color:var(--hgr-accent)}.hgr-capacity span,.hgr-help,.hgr-count{font-size:.9rem;color:#526168}.hgr-details{margin-top:1.25rem}.hgr-details summary{cursor:pointer;color:var(--hgr-accent);font-weight:700}.hgr-form{margin-top:1.5rem}.hgr-fields{display:grid;grid-template-columns:1fr 1fr;gap:20px}.hgr-form label{display:flex;flex-direction:column;gap:8px;font-weight:600}.hgr-form input:not([type=checkbox]){width:100%;box-sizing:border-box;padding:12px;border:1px solid #b8c6cb;border-radius:5px;font:inherit;background:white;color:#26343b}.hgr-participants{border:0;padding:0;margin:1.8rem 0 1rem}.hgr-participants legend{font-weight:700;margin-bottom:12px}.hgr-person{display:flex;gap:12px;align-items:end;margin-bottom:14px}.hgr-person label{flex:1}.hgr-form button{padding:11px 18px;font:inherit;border:1px solid #bdcbd0;border-radius:5px;cursor:pointer;background:#f3f7f8;color:#26343b}.hgr-form .hgr-submit{background:var(--hgr-accent);border-color:var(--hgr-accent);color:white;font-weight:700;margin-top:1rem}.hgr-form button:disabled{opacity:.6;cursor:default}.hgr-form .hgr-consent{display:flex;flex-direction:row;align-items:flex-start;font-weight:400;margin-top:1.6rem}.hgr-consent input{margin-top:5px}.hgr-honey{position:absolute;left:-10000px;opacity:0}.hgr-notice{border-left:4px solid #357b46;background:#eef8f1;padding:18px;margin-bottom:20px}.hgr-error{border-color:#b3261e;background:#fff2f0}.hgr-full{font-weight:700;color:#704328}.hgr :focus-visible{outline:3px solid #e5a23d;outline-offset:3px}.hgr-empty{padding:24px;background:#f4f7f8;border-radius:8px}.hgr [hidden]{display:none!important}@media(max-width:650px){.hgr-moment{padding:1.2rem}.hgr-moment-head{flex-direction:column;gap:8px}.hgr-capacity{text-align:left}.hgr-fields{grid-template-columns:1fr}.hgr-person{flex-wrap:wrap}}
+28
View File
@@ -0,0 +1,28 @@
document.querySelectorAll('.hgr-form').forEach(form => {
const list = form.querySelector('.hgr-participants');
const add = form.querySelector('.hgr-add');
const update = () => {
const people = [...list.querySelectorAll('.hgr-person')];
people.forEach((row, i) => {
row.querySelector('label').firstChild.textContent = `Naam deelnemer ${i + 1} `;
row.querySelector('button').hidden = people.length === 1;
});
add.disabled = people.length >= Number(form.dataset.max);
form.querySelector('.hgr-count').textContent = `${people.length} ${people.length === 1 ? 'deelnemer' : 'deelnemers'}`;
};
add.addEventListener('click', () => {
if (list.querySelectorAll('.hgr-person').length >= Number(form.dataset.max)) return;
const row = list.querySelector('.hgr-person').cloneNode(true);
row.querySelector('input').value = '';
list.append(row);update();row.querySelector('input').focus();
});
list.addEventListener('click', event => {
if (!event.target.matches('.hgr-remove') || list.querySelectorAll('.hgr-person').length < 2) return;
event.target.closest('.hgr-person').remove();update();add.focus();
});
form.addEventListener('submit', () => {
form.querySelector('[type=submit]').disabled = true;
form.querySelector('[type=submit]').textContent = 'Aanvraag wordt verstuurd…';
});
update();
});
+11
View File
@@ -0,0 +1,11 @@
/* HG navigation only; leave the rest of the WordPress admin color scheme intact. */
#adminmenu #toplevel_page_hg-plugins>a.menu-top{background:#173b37;color:#d8fff3;box-shadow:inset 3px 0 #56d5bb}
#adminmenu #toplevel_page_hg-plugins .wp-menu-image::before{color:#80e9d1}
#adminmenu #toplevel_page_hg-plugins:hover>a.menu-top,#adminmenu #toplevel_page_hg-plugins>a.menu-top:focus{background:#20574e;color:#fff}
#adminmenu #toplevel_page_hg-plugins.wp-has-current-submenu>a.menu-top,#adminmenu #toplevel_page_hg-plugins.current>a.menu-top{background:#126151;color:#fff}
#adminmenu #toplevel_page_hg-plugins .wp-submenu{background:#16332f}
#adminmenu #toplevel_page_hg-plugins .wp-submenu a{color:#d0e6de}
#adminmenu #toplevel_page_hg-plugins .wp-submenu a:hover,#adminmenu #toplevel_page_hg-plugins .wp-submenu a:focus{color:#fff;background:#24584e}
#adminmenu #toplevel_page_hg-plugins .wp-submenu li.current a{color:#fff;font-weight:600;background:#205147}
#adminmenu #toplevel_page_hg-plugins .wp-submenu .wp-submenu-head{color:#fff;background:#126151}
.hg-suite{max-width:1100px}.hg-suite-header{display:flex;align-items:center;gap:18px;margin:28px 0}.hg-suite-header h1{padding:0;font-size:26px}.hg-suite-header p{margin:7px 0 0;color:#50575e}.hg-suite-mark{display:grid;place-items:center;width:58px;height:58px;background:#126151;color:#fff;border-radius:10px;font-weight:750;font-size:21px;letter-spacing:-1px}.hg-suite-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:22px}.hg-suite-card{background:#fff;border:1px solid #dcdcde;border-radius:8px;padding:26px}.hg-suite-card h2{margin:12px 0;font-size:20px}.hg-suite-card p{color:#50575e;font-size:14px;line-height:1.7;min-height:48px}.hg-suite-version{display:inline-block;padding:4px 9px;border-radius:5px;color:#145c4c;background:#e9f5ee;font-size:12px}.hg-suite-card .button{margin-top:12px}@media(max-width:782px){.hg-suite-grid{grid-template-columns:1fr}.hg-suite-header{gap:14px}.hg-suite-card{padding:22px}}
+39
View File
@@ -0,0 +1,39 @@
<?php
/**
* Plugin Name: HG Inschrijvingen
* Description: Activiteiten, geplande momenten en inschrijvingen met reserveringen en handmatige bevestiging.
* Version: 0.1.2
* Update URI: https://code.hosting.hippogrief.nl/hippogrief/wp-plugins/src/branch/main/hg_registrations
* Requires at least: 6.5
* Requires PHP: 8.1
* Author: Hippogrief
* License: GPL-2.0-or-later
* Text Domain: hg-registrations
*/
if (!defined('ABSPATH')) exit;
require_once __DIR__ . '/includes/hg-plugin-updates.php';
define('HGR_VERSION', '0.1.2');
define('HGR_PATH', plugin_dir_path(__FILE__));
define('HGR_URL', plugin_dir_url(__FILE__));
require_once HGR_PATH . 'includes/hg-admin-menu.php';
require HGR_PATH . 'includes/model.php';
require HGR_PATH . 'includes/mail.php';
require HGR_PATH . 'includes/frontend.php';
require HGR_PATH . 'includes/admin.php';
register_activation_hook(__FILE__, 'hgr_install');
add_action('init', function () {
register_post_type('hgr_activity', [
'labels' => ['name'=>'Activiteiten', 'singular_name'=>'Activiteit', 'add_new_item'=>'Activiteit toevoegen', 'edit_item'=>'Activiteit bewerken'],
'public'=>false, 'show_ui'=>true, 'show_in_menu'=>false, 'show_in_rest'=>true,
'supports'=>['title','editor'], 'capability_type'=>'post', 'map_meta_cap'=>true,
'capabilities'=>['create_posts'=>'manage_options','edit_posts'=>'manage_options','edit_others_posts'=>'manage_options','edit_published_posts'=>'manage_options','edit_private_posts'=>'manage_options','publish_posts'=>'manage_options','delete_posts'=>'manage_options','delete_others_posts'=>'manage_options','delete_published_posts'=>'manage_options','delete_private_posts'=>'manage_options','read_private_posts'=>'manage_options'],
]);
});
add_action('admin_init', function () { if (get_option('hgr_schema') !== HGR_VERSION) hgr_install(); });
add_filter('pre_delete_post',function($delete,$post) {
if ($post->post_type==='hgr_activity') {
global $wpdb;
if ($wpdb->get_var($wpdb->prepare('SELECT id FROM '.hgr_table('moments').' WHERE activity_id=%d LIMIT 1',$post->ID))) return false;
}
return $delete;
},10,2);
+79
View File
@@ -0,0 +1,79 @@
<?php
if (!defined('ABSPATH')) exit;
HG_Plugin_Admin::register(['slug'=>'hg-registrations','title'=>'HG Inschrijvingen','label'=>'Inschrijvingen','callback'=>'hgr_admin','version'=>HGR_VERSION,'description'=>'Activiteiten, geplande momenten, capaciteit en inschrijvingen beheren.']);
add_action('admin_enqueue_scripts',function($hook) { if ($hook===HG_Plugin_Admin::hook('hg-registrations')) wp_enqueue_style('hgr-admin',HGR_URL.'assets/admin.css',[],HGR_VERSION); });
add_filter('parent_file',function($parent) { return get_current_screen()?->post_type==='hgr_activity' ? 'hg-plugins' : $parent; });
add_filter('submenu_file',function($submenu) { return get_current_screen()?->post_type==='hgr_activity' ? 'hg-registrations' : $submenu; });
function hgr_admin_url($tab,$args=[]) { return add_query_arg(array_merge(['page'=>'hg-registrations','tab'=>$tab],$args),admin_url('admin.php')); }
function hgr_admin_field($label,$name,$value='',$type='text',$extra='') {
?><label class="hgr-admin-field"><span><?php echo esc_html($label); ?></span><input type="<?php echo esc_attr($type); ?>" name="<?php echo esc_attr($name); ?>" value="<?php echo esc_attr($value); ?>" <?php echo $extra; ?>></label><?php
}
function hgr_admin_form($operation) { ?><form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>"><input type="hidden" name="action" value="hgr_admin"><input type="hidden" name="operation" value="<?php echo esc_attr($operation); ?>"><?php wp_nonce_field('hgr_admin_'.$operation); }
function hgr_capacity_text($cap) { return "$cap[capacity] plaatsen · $cap[reserved] gereserveerd · $cap[confirmed] bevestigd · $cap[available] beschikbaar"; }
function hgr_admin() {
if (!current_user_can('manage_options')) return;
global $wpdb;
$tabs=['activities'=>'Activiteiten','moments'=>'Momenten','registrations'=>'Inschrijvingen','settings'=>'Instellingen','info'=>'Over deze plugin'];
$tab=sanitize_key($_GET['tab']??'activities');if (!isset($tabs[$tab])) $tab='activities';
?>
<div class="wrap hgr-admin"><header class="hgr-admin-header"><div><h1>HG Inschrijvingen</h1><p>Beheer activiteiten, geplande momenten en deelnemers.</p></div><span class="hgr-language-status">Reserveren → handmatig bevestigen</span></header>
<?php if (isset($_GET['notice'])) { $msg=get_transient('hgr_admin_notice_'.get_current_user_id().'_'.sanitize_key($_GET['notice']));if($msg): ?><div class="notice notice-<?php echo $msg['error']?'error':'success'; ?>"><p><?php echo esc_html($msg['message']); ?></p></div><?php endif; } ?>
<nav class="hgr-admin-tabs" aria-label="Pluginonderdelen"><?php foreach($tabs as $key=>$label): ?><a <?php if($key===$tab) echo 'class="is-active" aria-current="page"'; ?> href="<?php echo esc_url(hgr_admin_url($key)); ?>"><?php echo esc_html($label); ?></a><?php endforeach; ?></nav>
<?php
if ($tab==='activities') {
$activities=get_posts(['post_type'=>'hgr_activity','post_status'=>['publish','draft','pending','private'],'numberposts'=>-1]);
?><div class="hgr-panel-heading"><div><h2>Activiteiten</h2><p>Een activiteit beschrijft wat je aanbiedt. Plan de datums onder Momenten.</p></div><a class="button button-secondary" href="<?php echo esc_url(admin_url('post-new.php?post_type=hgr_activity')); ?>">Activiteit toevoegen</a></div><div class="hgr-admin-card"><table class="widefat striped"><thead><tr><th>Activiteit</th><th>Publicatie</th><th>Agenda op een pagina plaatsen</th></tr></thead><tbody><?php foreach($activities as $a): ?><tr><td><a href="<?php echo esc_url(get_edit_post_link($a->ID)); ?>"><?php echo esc_html($a->post_title); ?></a></td><td><?php echo esc_html(get_post_status_object($a->post_status)->label); ?></td><td><code>[hg_registrations activity="<?php echo (int)$a->ID; ?>"]</code></td></tr><?php endforeach; if(!$activities): ?><tr><td colspan="3">Er zijn nog geen activiteiten. Voeg eerst een activiteit toe.</td></tr><?php endif; ?></tbody></table><p class="hgr-admin-note">Plaats <code>[hg_registrations]</code> voor een overzicht van alle open momenten. Alleen gepubliceerde activiteiten zijn zichtbaar voor bezoekers.</p></div><?php
} elseif ($tab==='moments') {
$rows=$wpdb->get_results('SELECT * FROM '.hgr_table('moments').' ORDER BY starts_at DESC LIMIT 500');
?><div class="hgr-admin-card hgr-table"><h2>Geplande momenten</h2><table class="widefat striped"><thead><tr><th>Activiteit en datum</th><th>Locatie</th><th>Capaciteit</th><th>Status</th><th></th></tr></thead><tbody><?php foreach($rows as $m): ?><tr><td><?php echo esc_html(get_the_title($m->activity_id)); ?><br><?php echo esc_html(hgr_local_time($m->starts_at)); ?></td><td><?php echo esc_html($m->location); ?></td><td><?php echo esc_html(hgr_capacity_text(hgr_capacity($m->id))); ?></td><td><?php echo esc_html(['draft'=>'Concept','open'=>'Open','closed'=>'Gesloten'][$m->state]??$m->state); ?></td><td><a href="<?php echo esc_url(hgr_admin_url('moments',['moment_id'=>$m->id])); ?>">Bewerken</a></td></tr><?php endforeach;if(!$rows): ?><tr><td colspan="5">Er zijn nog geen geplande momenten.</td></tr><?php endif; ?></tbody></table></div><?php
$edit=isset($_GET['moment_id'])?hgr_moment(absint($_GET['moment_id'])):null;
$activities=get_posts(['post_type'=>'hgr_activity','post_status'=>['publish','draft'],'numberposts'=>-1]);
hgr_admin_form('moment'); ?>
<div class="hgr-admin-card"><h2><?php echo $edit?'Moment bewerken':'Moment toevoegen'; ?></h2><input type="hidden" name="id" value="<?php echo (int)($edit->id??0); ?>"><div class="hgr-admin-grid">
<label class="hgr-admin-field"><span>Activiteit</span><select name="activity_id" required><option value="">Kies een activiteit</option><?php foreach($activities as $a): ?><option value="<?php echo $a->ID; ?>" <?php selected($edit->activity_id??0,$a->ID); ?>><?php echo esc_html($a->post_title); ?></option><?php endforeach; ?></select></label>
<?php hgr_admin_field('Locatie','location',$edit->location??'','text','required maxlength="250"');
foreach(['starts_at'=>'Begindatum en tijd','ends_at'=>'Einddatum en tijd'] as $name=>$label) hgr_admin_field($label,$name,$edit?wp_date('Y-m-d\TH:i',strtotime($edit->$name.' UTC')):'','datetime-local','required');
hgr_admin_field('Aantal plaatsen','capacity',$edit->capacity??12,'number','min="1" max="10000" required'); ?>
<label class="hgr-admin-field"><span>Status</span><select name="state"><?php foreach(['draft'=>'Concept','open'=>'Open voor inschrijving','closed'=>'Gesloten'] as $key=>$label): ?><option value="<?php echo $key; ?>" <?php selected($edit->state??'draft',$key); ?>><?php echo esc_html($label); ?></option><?php endforeach; ?></select></label></div>
<p class="hgr-admin-note">Datums gebruiken de tijdzone van deze website: <?php echo esc_html(wp_timezone_string()); ?>. Gereserveerde en bevestigde deelnemers tellen beide mee. Met bestaande aanvragen kun je de datum, activiteit en locatie niet wijzigen.</p></div>
<div class="hgr-save-bar"><?php submit_button('Moment opslaan','primary','submit',false); ?><a href="<?php echo esc_url(hgr_admin_url('moments')); ?>">Nieuw moment</a><span>Wijzigingen worden pas actief na opslaan.</span></div></form><?php
} elseif ($tab==='registrations') {
$rows=$wpdb->get_results('SELECT * FROM '.hgr_table('registrations').' ORDER BY created_at DESC LIMIT 500');
?><div class="hgr-panel-heading"><div><h2>Inschrijvingen</h2><p>Reserveringen blijven staan totdat je ze behandelt. Er is geen automatisch verloop.</p></div><a class="button button-secondary" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=hgr_export'),'hgr_export')); ?>">Deelnemers exporteren</a></div><div class="hgr-admin-card hgr-table"><table class="widefat striped"><thead><tr><th>Aanvraag</th><th>Contactpersoon</th><th>Activiteit en moment</th><th>Deelnemers</th><th>Status</th><th>E-mail</th></tr></thead><tbody><?php foreach($rows as $r): $m=hgr_moment($r->moment_id); ?><tr><td><a href="<?php echo esc_url(hgr_admin_url('registrations',['registration_id'=>$r->id])); ?>">#<?php echo (int)$r->id; ?></a><br><?php echo esc_html(hgr_local_time($r->created_at)); ?></td><td><?php echo esc_html($r->contact_name); ?><br><?php echo esc_html($r->organization); ?></td><td><?php echo esc_html($m?get_the_title($m->activity_id):''); ?><br><?php echo esc_html($m?hgr_local_time($m->starts_at):''); ?></td><td><?php echo (int)$r->seats; ?></td><td><span class="hgr-badge hgr-<?php echo esc_attr($r->status); ?>"><?php echo esc_html(hgr_statuses()[$r->status]??$r->status); ?></span></td><td><?php echo esc_html(['pending'=>'Nog versturen','sent'=>'Verstuurd','failed'=>'Verzending mislukt'][$r->notice_state]??$r->notice_state); ?></td></tr><?php endforeach;if(!$rows): ?><tr><td colspan="6">Er zijn nog geen inschrijvingen.</td></tr><?php endif; ?></tbody></table></div><?php
if (isset($_GET['registration_id']) && ($r=hgr_registration(absint($_GET['registration_id'])))) {
$m=hgr_moment($r->moment_id);hgr_admin_form('status'); ?>
<div class="hgr-admin-card"><h2>Inschrijving #<?php echo (int)$r->id; ?></h2><p><?php echo esc_html(get_the_title($m->activity_id).' · '.hgr_local_time($m->starts_at).' · '.$m->location); ?></p><p class="hgr-admin-note"><?php echo esc_html(hgr_capacity_text(hgr_capacity($m->id))); ?></p>
<div class="hgr-admin-grid"><div><h3>Contactpersoon</h3><p><?php echo esc_html($r->contact_name); ?><br><?php echo esc_html($r->contact_email); ?><br><?php echo esc_html($r->phone); ?><br><?php echo esc_html($r->organization); ?></p></div><div><h3>Deelnemers</h3><ol><?php foreach(json_decode($r->participants,true)?:[] as $name): ?><li><?php echo esc_html($name); ?></li><?php endforeach; ?></ol></div></div>
<input type="hidden" name="id" value="<?php echo (int)$r->id; ?>"><label class="hgr-admin-field"><span>Status</span><select name="status"><?php foreach(hgr_statuses() as $key=>$label): ?><option value="<?php echo $key; ?>" <?php selected($r->status,$key); ?>><?php echo esc_html($label); ?></option><?php endforeach; ?></select></label><p>Bij een statuswijziging ontvangt de contactpersoon een bericht. Afwijzen of annuleren geeft de plaatsen vrij.</p></div><div class="hgr-save-bar"><?php submit_button('Status opslaan en berichten versturen','primary','submit',false); ?></div></form><?php
if ($r->notice_state!=='sent') { hgr_admin_form('resend'); ?><input type="hidden" name="id" value="<?php echo (int)$r->id; ?>"><p><?php submit_button('Mislukte meldingen opnieuw versturen','secondary','submit',false); ?></p></form><?php }
}
} elseif ($tab==='settings') {
$s=hgr_settings();hgr_admin_form('settings'); ?><div class="hgr-admin-card"><h2>Algemeen en e-mail</h2><div class="hgr-admin-grid"><?php hgr_admin_field('Ontvangstadres organisatie','recipient',$s['recipient'],'email','required');hgr_admin_field('Maximaal deelnemers per aanvraag','max_participants',$s['max_participants'],'number','min="1" max="100" required');hgr_admin_field('Naam voor activiteit','activity_label',$s['activity_label'],'text','required maxlength="60"');hgr_admin_field('Naam voor gepland moment','moment_label',$s['moment_label'],'text','required maxlength="60"'); ?></div><p class="hgr-admin-note">Mailaflevering volgt de mailvoorziening van de website. Een gereserveerde plaats is nog geen bevestigde deelname. Zorg dat er een passende privacyverklaring is voor de gegevens die je verzamelt.</p></div><div class="hgr-save-bar"><?php submit_button('Wijzigingen opslaan','primary','submit',false); ?><span>Wijzigingen worden pas actief na opslaan.</span></div></form><?php
} else { ?><div class="hgr-admin-card"><h2>HG Inschrijvingen</h2><p>Versie <?php echo esc_html(HGR_VERSION); ?> · WordPress en PHP 8.1+</p><p>Herbruikbaar voor trainingen, workshops en andere activiteiten. Klantinstellingen staan uitsluitend in de website. Reserveringen en bevestigingen delen dezelfde capaciteitscontrole.</p><h3>Onderhoud en gegevens</h3><p>Gebruik databaseback-ups. Deactiveren verwijdert geen inschrijvingen. Er is geen automatische verwijdering of bewaartermijn; spreek deze vóór livegang af. Exports bevatten persoonsgegevens en zijn alleen beschikbaar voor beheerders.</p><p>Basis-antispam: honeypot, ondertekend formulier, wachttijd en verzendlimiet. Cache de inschrijfpagina niet langdurig. Er is geen online betaling of wachtlijst.</p></div><?php }
?></div><?php
}
function hgr_admin_action() {
if (!current_user_can('manage_options')) wp_die('Geen toegang.', '', ['response'=>403]);
$input=wp_unslash($_POST);$op=sanitize_key($input['operation']??'');check_admin_referer('hgr_admin_'.$op);
$tab='registrations';$args=[];$error=false;$message='Wijzigingen opgeslagen.';
if ($op==='moment') { $tab='moments';$result=hgr_save_moment($input);if(!is_wp_error($result))$args['moment_id']=$result; }
elseif ($op==='status') { $args['registration_id']=absint($input['id']??0);$result=hgr_set_status($args['registration_id'],$input['status']??'');if($result===true && !hgr_notify($args['registration_id'])) $message='Status opgeslagen, maar niet alle e-mails zijn verstuurd. Probeer opnieuw vanuit de aanvraag.'; }
elseif ($op==='resend') { $args['registration_id']=absint($input['id']??0);$result=hgr_notify($args['registration_id']);$message=$result?'Meldingen verstuurd.':'Verzending is niet gelukt. Controleer de mailvoorziening.';$error=!$result; }
elseif ($op==='settings') {
$tab='settings';$s=hgr_settings();$recipient=sanitize_email($input['recipient']??'');$max=filter_var($input['max_participants']??null,FILTER_VALIDATE_INT,['options'=>['min_range'=>1,'max_range'=>100]]);
$activity=sanitize_text_field($input['activity_label']??'');$moment=sanitize_text_field($input['moment_label']??'');
if (!is_email($recipient)||!$max||!$activity||!$moment||strlen($activity)>60||strlen($moment)>60) $result=new WP_Error('settings','Controleer de instellingen.');
else { update_option('hgr_settings',array_merge($s,['recipient'=>$recipient,'max_participants'=>$max,'activity_label'=>$activity,'moment_label'=>$moment]));$result=true; }
} else $result=new WP_Error('operation','Ongeldige actie.');
if (is_wp_error($result)) { $error=true;$message=$result->get_error_message(); }
$key=str_replace('-','',wp_generate_uuid4());set_transient('hgr_admin_notice_'.get_current_user_id().'_'.$key,['error'=>$error,'message'=>$message],5*MINUTE_IN_SECONDS);
wp_safe_redirect(hgr_admin_url($tab,array_merge($args,['notice'=>$key])));exit;
}
add_action('admin_post_hgr_admin','hgr_admin_action');
add_action('admin_post_hgr_export',function() {
if (!current_user_can('manage_options')) wp_die('Geen toegang.','',['response'=>403]);check_admin_referer('hgr_export');
global $wpdb;nocache_headers();header('Content-Type: text/csv; charset=utf-8');header('Content-Disposition: attachment; filename="inschrijvingen-'.gmdate('Y-m-d').'.csv"');
$out=fopen('php://output','w');fwrite($out,"\xEF\xBB\xBF");fputcsv($out,['Nummer','Activiteit','Datum','Locatie','Status','Deelnemer','Contactpersoon','E-mail','Telefoon','Organisatie'],';', '"','');
// One participant per row; neutralize spreadsheet formulas in user supplied values.
$offset=0;do { $rows=$wpdb->get_results($wpdb->prepare('SELECT * FROM '.hgr_table('registrations').' ORDER BY id LIMIT 200 OFFSET %d',$offset));foreach($rows as $r) { $m=hgr_moment($r->moment_id);foreach(json_decode($r->participants,true)?:[] as $person) { $row=[$r->id,get_the_title($m->activity_id),hgr_local_time($m->starts_at),$m->location,hgr_statuses()[$r->status],$person,$r->contact_name,$r->contact_email,$r->phone,$r->organization];$row=array_map(fn($v)=>preg_match('/^[\s]*[=+@-]/u',(string)$v)?"'".$v:$v,$row);fputcsv($out,$row,';', '"',''); } }$offset+=200; } while(count($rows)===200);fclose($out);exit;
});
+62
View File
@@ -0,0 +1,62 @@
<?php
if (!defined('ABSPATH')) exit;
function hgr_form_token($id,$issued=null,$uuid=null) {
$payload=$id.'.'.($issued??time()).'.'.($uuid??wp_generate_uuid4());
return $payload.'.'.hash_hmac('sha256',$payload,wp_salt('nonce'));
}
function hgr_check_token($token,$id) {
if (!is_string($token) || strlen($token)>200) return false;
$bits=explode('.',$token);
if (count($bits)!==4 || !ctype_digit($bits[0]) || !ctype_digit($bits[1]) || (int)$bits[0]!==$id || !preg_match('/^[a-f0-9-]{36}$/',$bits[2])) return false;
$age=time()-(int)$bits[1];
return $age>=3 && $age<=7200 && hash_equals(hash_hmac('sha256',implode('.',array_slice($bits,0,3)),wp_salt('nonce')),$bits[3]);
}
add_shortcode('hg_registrations',function($attrs) {
global $wpdb;
$attrs=shortcode_atts(['activity'=>'0'],$attrs,'hg_registrations');$activity=absint($attrs['activity']);
$sql=$wpdb->prepare('SELECT m.* FROM '.hgr_table('moments')." m INNER JOIN $wpdb->posts p ON p.ID=m.activity_id WHERE m.state='open' AND m.starts_at>%s AND p.post_status='publish' AND p.post_type='hgr_activity'",current_time('mysql',true));
if ($activity) $sql.=$wpdb->prepare(' AND m.activity_id=%d',$activity);
$rows=$wpdb->get_results($sql.' ORDER BY m.starts_at LIMIT 100');
wp_enqueue_style('hgr-frontend',HGR_URL.'assets/frontend.css',[],HGR_VERSION);
wp_enqueue_script('hgr-frontend',HGR_URL.'assets/frontend.js',[],HGR_VERSION,true);
if (!headers_sent()) { nocache_headers(); }
ob_start(); ?>
<section class="hgr" aria-label="<?php echo esc_attr(hgr_settings()['moment_label']); ?>">
<?php if (isset($_GET['hgr_reserved'])): ?><div class="hgr-notice" role="status"><strong>Je aanvraag is ontvangen.</strong> De plaatsen zijn gereserveerd. Je deelname is pas definitief nadat de organisatie deze heeft bevestigd.</div><?php endif; ?>
<?php if (isset($_GET['hgr_error']) && is_scalar($_GET['hgr_error'])): $message=get_transient('hgr_error_'.sanitize_key(wp_unslash($_GET['hgr_error'])));if($message): ?><div class="hgr-notice hgr-error" role="alert"><?php echo esc_html($message); ?></div><?php endif;endif; ?>
<?php if (!$rows): ?><p class="hgr-empty">Er zijn momenteel geen geplande momenten waarvoor je kunt inschrijven.</p><?php endif; ?>
<?php foreach($rows as $m): $cap=hgr_capacity($m->id);$title=get_the_title($m->activity_id);$max=min($cap['available'],(int)hgr_settings()['max_participants']); ?>
<article class="hgr-moment"><div class="hgr-moment-head"><div><h3><?php echo esc_html($title); ?></h3><p><?php echo esc_html(hgr_local_time($m->starts_at)); ?> – <?php echo esc_html(wp_date('H:i',strtotime($m->ends_at.' UTC'))); ?><br><?php echo esc_html($m->location); ?></p></div><div class="hgr-capacity"><strong><?php echo (int)$cap['available']; ?> beschikbaar</strong><span>van <?php echo (int)$cap['capacity']; ?> plaatsen</span></div></div>
<?php if (!$max): ?><p class="hgr-full">Volgeboekt</p><?php else: ?>
<details class="hgr-details"><summary>Plaatsen reserveren</summary>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="hgr-form" data-max="<?php echo $max; ?>">
<input type="hidden" name="action" value="hgr_reserve"><input type="hidden" name="moment_id" value="<?php echo (int)$m->id; ?>"><input type="hidden" name="hgr_token" value="<?php echo esc_attr(hgr_form_token((int)$m->id)); ?>"><input type="hidden" name="return_url" value="<?php echo esc_url(get_permalink()); ?>">
<?php wp_nonce_field('hgr_reserve','hgr_nonce'); ?>
<div class="hgr-honey" aria-hidden="true"><label>Website<input name="website" tabindex="-1" autocomplete="off"></label></div>
<div class="hgr-fields"><label>Naam contactpersoon <span aria-hidden="true">*</span><input name="contact_name" autocomplete="name" required maxlength="150"></label><label>E-mailadres <span aria-hidden="true">*</span><input type="email" name="contact_email" autocomplete="email" required maxlength="254"></label><label>Telefoonnummer<input type="tel" name="phone" autocomplete="tel" maxlength="60"></label><label>Organisatie<input name="organization" autocomplete="organization" maxlength="150"></label></div>
<fieldset class="hgr-participants"><legend>Deelnemers</legend><div class="hgr-person"><label>Naam deelnemer 1 <span aria-hidden="true">*</span><input name="participants[]" required maxlength="150"></label><button type="button" class="hgr-remove" hidden>Verwijderen</button></div></fieldset>
<button type="button" class="hgr-add">Deelnemer toevoegen</button><p class="hgr-count" aria-live="polite">1 deelnemer</p>
<label class="hgr-consent"><input type="checkbox" name="consent" value="1" required> Ik ga akkoord met verwerking van deze gegevens voor mijn inschrijving.</label>
<p class="hgr-help">Je reserveert plaatsen. De organisatie bevestigt je deelname afzonderlijk. Vul geen medische of andere gevoelige gegevens in.</p>
<button type="submit" class="hgr-submit">Reservering aanvragen</button>
</form></details><?php endif; ?></article><?php endforeach; ?></section>
<?php return ob_get_clean();
});
function hgr_submission() {
$input=wp_unslash($_POST);$id=absint($input['moment_id']??0);
$return=wp_validate_redirect(is_scalar($input['return_url']??null)?$input['return_url']: '',home_url('/'));
$return=remove_query_arg(['hgr_error','hgr_reserved'],$return);
$error=null;
if (!wp_verify_nonce(is_scalar($input['hgr_nonce']??null)?$input['hgr_nonce']:'','hgr_reserve') || !hgr_check_token($input['hgr_token']??null,$id) || !empty($input['website']) || ($input['consent']??'')!=='1') $error='Controleer het formulier. Vernieuw de pagina als deze lang open heeft gestaan.';
$ip=hash_hmac('sha256',$_SERVER['REMOTE_ADDR']??'',wp_salt('auth'));$rate='hgr_rate_'.$ip;
if (!$error && (int)get_transient($rate)>=10) $error='Er zijn te veel aanvragen verstuurd. Probeer het over enkele minuten opnieuw.';
if (!$error) {
$result=hgr_reserve($id,$input,hash('sha256',$input['hgr_token']));
if (is_wp_error($result)) $error=$result->get_error_message();
else { if ($result['new']) { set_transient($rate,(int)get_transient($rate)+1,10*MINUTE_IN_SECONDS);hgr_notify($result['id']); } wp_safe_redirect(add_query_arg('hgr_reserved','1',$return));exit; }
}
$key=str_replace('-','',wp_generate_uuid4());set_transient('hgr_error_'.$key,$error,5*MINUTE_IN_SECONDS);
wp_safe_redirect(add_query_arg('hgr_error',$key,$return));exit;
}
add_action('admin_post_hgr_reserve','hgr_submission');
add_action('admin_post_nopriv_hgr_reserve','hgr_submission');
+52
View File
@@ -0,0 +1,52 @@
<?php
/**
* HG admin navigation, bundled identically in each standalone HG plugin.
* Shared component version: 1.0.0. Update both copies together.
*/
if (!defined('ABSPATH')) exit;
if (!class_exists('HG_Plugin_Admin', false)) {
final class HG_Plugin_Admin {
private static array $plugins = [];
private static array $hooks = [];
public static function register(array $plugin): void {
self::$plugins[$plugin['slug']] = $plugin;
}
public static function hook(string $slug): string {
return self::$hooks[$slug] ?? '';
}
public static function menu(): void {
if (!self::$plugins) return;
add_menu_page('HG Plugins', 'HG Plugins', 'manage_options', 'hg-plugins', [self::class, 'overview'], 'dashicons-screenoptions', 58);
add_submenu_page('hg-plugins', 'HG Plugins', 'Overzicht', 'manage_options', 'hg-plugins', [self::class, 'overview']);
uasort(self::$plugins, fn($a, $b) => strcasecmp($a['label'], $b['label']));
foreach (self::$plugins as $slug => $plugin) {
self::$hooks[$slug] = (string) add_submenu_page('hg-plugins', $plugin['title'], $plugin['label'], 'manage_options', $slug, $plugin['callback']);
}
}
public static function styles(): void {
if (!self::$plugins || !current_user_can('manage_options')) return;
wp_enqueue_style('hg-admin-menu', plugins_url('../assets/hg-admin-menu.css', __FILE__), [], '1.0.0');
}
public static function overview(): void {
if (!current_user_can('manage_options')) wp_die('Geen toegang.', '', ['response' => 403]);
?>
<div class="wrap hg-suite">
<header class="hg-suite-header"><span class="hg-suite-mark" aria-hidden="true">HG</span><div><h1>HG Plugins</h1><p>De Hippogrief-modules op deze website.</p></div></header>
<div class="hg-suite-grid">
<?php foreach (self::$plugins as $slug => $plugin): ?>
<section class="hg-suite-card"><span class="hg-suite-version">Versie <?php echo esc_html($plugin['version']); ?></span><h2><?php echo esc_html($plugin['title']); ?></h2><p><?php echo esc_html($plugin['description']); ?></p><a class="button button-primary" href="<?php echo esc_url(add_query_arg('page', $slug, admin_url('admin.php'))); ?>">Beheren</a></section>
<?php endforeach; ?>
</div>
</div>
<?php
}
}
add_action('admin_menu', [HG_Plugin_Admin::class, 'menu'], 20);
add_action('admin_enqueue_scripts', [HG_Plugin_Admin::class, 'styles']);
}
+317
View File
@@ -0,0 +1,317 @@
<?php
/** HG release updates, bundled identically in each standalone HG plugin. */
if (!defined('ABSPATH')) exit;
if (!class_exists('HG_Plugin_Updates_1_0_0', false)) {
// Bump this class suffix and VERSION together when changing the bundled updater.
final class HG_Plugin_Updates_1_0_0 {
private const VERSION = '1.0.0';
private const REPOSITORY = 'https://code.hosting.hippogrief.nl/hippogrief/wp-plugins';
private const RELEASE_API = 'https://code.hosting.hippogrief.nl/api/v1/repos/hippogrief/wp-plugins/releases';
private const CACHE = 'hg_plugin_releases';
private const PAGE = 'hg-plugin-updates';
private const MODULES = [
'hg-contactform' => ['HG Contactformulier', 'hg-contactform'],
'hg-hephaestusaperture' => ['HG Hephaestus Aperture', 'hg-hephaestusaperture'],
'hg-registrations' => ['HG Inschrijvingen', 'hg-registrations'],
'hg-socialfeed' => ['HG Social Feed', 'hg_socialfeed'],
];
private static array $downloads = [];
public static function prefer(array $selected): array {
return version_compare(self::VERSION, $selected['version'], '>')
? ['class' => self::class, 'version' => self::VERSION]
: $selected;
}
public static function boot(): void {
$selected = apply_filters('hg_plugin_updates_implementation', ['class' => '', 'version' => '0']);
if ($selected['class'] !== self::class) return;
add_filter('update_plugins_code.hosting.hippogrief.nl', [self::class, 'native_update'], 10, 3);
add_filter('upgrader_pre_download', [self::class, 'verify_download'], 10, 4);
add_filter('upgrader_source_selection', [self::class, 'verify_package'], 9, 4);
add_filter('http_request_args', [self::class, 'download_args'], 10, 2);
add_action('admin_menu', [self::class, 'menu'], 21);
add_action('admin_post_hg_plugin_updates_refresh', [self::class, 'refresh']);
}
private static function package_base(): string {
return self::REPOSITORY . '/releases/download/';
}
private static function update_uri(string $slug): string {
return self::REPOSITORY . '/src/branch/main/' . str_replace('-', '_', $slug);
}
private static function module(string $file, array $data): ?string {
$slug = basename($file, '.php');
if (!isset(self::MODULES[$slug]) || dirname($file) === '.' || basename($file) !== "$slug.php" || validate_file($file) !== 0) {
return null;
}
$uri = $data['UpdateURI'] ?? '';
// Recognize installed releases from before the updater was bundled.
if ($uri === self::update_uri($slug) || ($uri === '' && ($data['Name'] ?? '') === self::MODULES[$slug][0])) {
return $slug;
}
return null;
}
private static function releases(bool $refresh = false): array {
$cached = get_site_transient(self::CACHE);
if (!$refresh && is_array($cached)) {
return $cached;
}
$result = self::fetch_releases();
set_site_transient(self::CACHE, $result, $result['error'] ? 5 * MINUTE_IN_SECONDS : 6 * HOUR_IN_SECONDS);
return $result;
}
private static function fetch_releases(): array {
$updates = [];
$limit = 50;
for ($page = 1; $page <= 20; $page++) {
$response = wp_safe_remote_get(add_query_arg(['limit' => $limit, 'page' => $page], self::RELEASE_API), [
'headers' => ['Accept' => 'application/json'],
'timeout' => 5,
'redirection' => 0,
'limit_response_size' => 2 * MB_IN_BYTES,
]);
$status = (int) wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
$releases = json_decode($body, true);
if ($status !== 200 || !is_array($releases) || !str_starts_with(ltrim($body), '[')) {
return ['error' => $status === 404 ? 'Ontoegankelijk' : 'Onbereikbaar', 'updates' => []];
}
foreach ($releases as $release) {
self::add_release($release, $updates);
}
$link = wp_remote_retrieve_header($response, 'link');
if (count($releases) < $limit && !str_contains(implode(',', (array) $link), 'rel="next"')) {
return ['error' => '', 'updates' => $updates];
}
}
return ['error' => 'Onbereikbaar', 'updates' => []];
}
private static function add_release(mixed $release, array &$updates): void {
if (!is_array($release) || ($release['draft'] ?? null) !== false || ($release['prerelease'] ?? null) !== false) {
return;
}
$tag = $release['tag_name'] ?? '';
$assets = $release['assets'] ?? null;
if (!is_string($tag) || !is_array($assets) || !preg_match('/^([a-z-]+)-v([0-9]+\.[0-9]+\.[0-9]+)$/D', $tag, $matches)) {
return;
}
[, $slug, $version] = $matches;
if (!isset(self::MODULES[$slug]) || (isset($updates[$slug]) && version_compare($version, $updates[$slug]['version'], '<='))) {
return;
}
$asset_urls = [];
foreach ($assets as $asset) {
$name = $asset['name'] ?? '';
if ($name !== "$slug-$version.zip" && $name !== "$slug.zip") continue;
$package = self::package_base() . "$tag/$name";
if (($asset['browser_download_url'] ?? '') === $package) {
$asset_urls[$name] = $package;
}
}
$package = $asset_urls["$slug-$version.zip"] ?? $asset_urls["$slug.zip"] ?? null;
if ($package) {
$updates[$slug] = [
'id' => self::update_uri($slug),
'slug' => $slug,
'version' => $version,
'new_version' => $version,
'url' => self::REPOSITORY . '/releases/tag/' . $tag,
'package' => $package,
];
}
}
public static function native_update($update, array $data, string $file) {
$slug = self::module($file, $data);
if (!$slug) return $update;
// WordPress can run its own update check during an anonymous admin-post request.
$can_fetch = wp_doing_cron() || current_user_can('update_plugins') || (defined('WP_CLI') && WP_CLI);
$releases = $can_fetch ? self::releases() : get_site_transient(self::CACHE);
return $releases['updates'][$slug] ?? $update;
}
private static function sync_updates(array $plugins, array $releases): void {
$transient = get_site_transient('update_plugins');
$transient = is_object($transient) ? clone $transient : new stdClass();
$previous = $transient->response ?? [];
$previous_no_update = $transient->no_update ?? [];
$transient->response = $previous;
$transient->no_update = $previous_no_update;
foreach ($plugins as $file => $data) {
$release = $releases[$data['slug']] ?? null;
if ($release && version_compare($release['version'], $data['Version'], '>')) {
$transient->response[$file] = (object) ($release + ['plugin' => $file]);
unset($transient->no_update[$file]);
} else {
unset($transient->response[$file]);
}
}
if ($previous != $transient->response || $previous_no_update != $transient->no_update) {
set_site_transient('update_plugins', $transient);
}
}
private static function installed(): array {
$installed = [];
foreach (get_plugins() as $file => $data) {
$slug = self::module($file, $data);
if ($slug) {
$installed[$file] = $data + ['slug' => $slug];
}
}
uasort($installed, static fn ($a, $b) => strcasecmp($a['Name'], $b['Name']));
return $installed;
}
public static function verify_download($reply, string $package, $upgrader, array $context) {
// WordPress bulk updates pass the plugin file without an action or type in this hook.
$file = $context['plugin'] ?? '';
if (is_wp_error($reply) || $file === '' || !str_starts_with($package, self::package_base())) {
return $reply;
}
$data = get_plugins()[$file] ?? [];
$slug = self::module($file, $data);
$release = $slug ? self::releases()['updates'][$slug] ?? null : null;
if (!$release || $package !== $release['package'] || !version_compare($release['version'], $data['Version'], '>')) {
return new WP_Error('hg_update_unavailable', 'Deze HG-update is niet meer beschikbaar. Controleer opnieuw op updates.');
}
// Keep a working installation active if native single-plugin validation rejects the update.
remove_filter('upgrader_pre_install', [$upgrader, 'deactivate_plugin_before_upgrade']);
self::$downloads[$file] = $release;
return $reply;
}
public static function download_args(array $args, string $url): array {
if (str_starts_with($url, self::package_base())) {
$args['redirection'] = 0;
}
return $args;
}
public static function verify_package($source, string $remote_source, $upgrader, array $context) {
global $wp_filesystem;
$file = $context['plugin'] ?? '';
$release = self::$downloads[$file] ?? null;
if (!$release || is_wp_error($source)) {
return $source;
}
unset(self::$downloads[$file]);
$slug = $release['slug'];
$source = trailingslashit($source);
$contents = $wp_filesystem->get_contents($source . basename($file));
$headers = str_replace("\r", "\n", substr((string) $contents, 0, 8 * KB_IN_BYTES));
$read = static function (string $field) use ($headers): string {
preg_match('/^(?:[ \t]*<\?php)?[ \t\/*#@]*' . $field . ':(.*)$/mi', $headers, $matches);
return _cleanup_header_comment($matches[1] ?? '');
};
if (basename($source) !== self::MODULES[$slug][1] || !$read('Plugin Name')
|| $read('Version') !== $release['version'] || $read('Update URI') !== $release['id']) {
return new WP_Error('hg_update_package', 'Het ZIP-bestand komt niet overeen met de gekozen HG-release.');
}
if (!is_php_version_compatible($read('Requires PHP')) || !is_wp_version_compatible($read('Requires at least'))) {
return new WP_Error('hg_update_requirements', 'Deze HG-release vereist een nieuwere versie van WordPress of PHP.');
}
// Keep the active plugin basename when an existing installation renamed its directory.
if (basename($source) !== dirname($file)) {
$destination = trailingslashit($remote_source) . dirname($file);
if (!$wp_filesystem->move(untrailingslashit($source), $destination)) {
return new WP_Error('hg_update_directory', 'De bestaande plug-inmap kon niet worden behouden.');
}
return trailingslashit($destination);
}
return $source;
}
public static function menu(): void {
add_submenu_page('hg-plugins', 'HG Plugin-updates', 'Updates', 'update_plugins', self::PAGE, [self::class, 'screen']);
}
private static function authorize(): void {
if (!current_user_can('manage_options') || !current_user_can('update_plugins')) {
wp_die('Geen toegang.', '', ['response' => 403]);
}
}
public static function refresh(): void {
self::authorize();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
wp_die('Ongeldig verzoek.', '', ['response' => 405]);
}
check_admin_referer('hg_plugin_updates_refresh');
$releases = self::releases(true);
self::sync_updates(self::installed(), $releases['updates']);
wp_safe_redirect(add_query_arg('page', self::PAGE, admin_url('admin.php')), 303);
exit;
}
public static function screen(): void {
self::authorize();
$plugins = self::installed();
$releases = self::releases();
self::sync_updates($plugins, $releases['updates']);
?>
<div class="wrap hg-suite">
<header class="hg-suite-header">
<span class="hg-suite-mark" aria-hidden="true">HG</span>
<div><h1>HG Plugin-updates</h1><p>Controleer de geïnstalleerde HG-plug-ins op nieuwe releases.</p></div>
</header>
<hr class="wp-header-end">
<?php if ($releases['error']) : ?>
<div class="notice notice-warning inline"><p><?php echo $releases['error'] === 'Ontoegankelijk'
? 'De releasebron is niet openbaar toegankelijk. Probeer het opnieuw zodra de repository en releases openbaar zijn.'
: 'De releases konden niet worden opgehaald. Probeer het later opnieuw.'; ?></p></div>
<?php endif; ?>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<input type="hidden" name="action" value="hg_plugin_updates_refresh">
<?php wp_nonce_field('hg_plugin_updates_refresh'); ?>
<p><button type="submit" class="button button-primary">Op updates controleren</button>
<a class="button" href="<?php echo esc_url(self::REPOSITORY . '/releases'); ?>">Releases bekijken</a></p>
</form>
<div style="overflow-x:auto" role="region" aria-label="Geïnstalleerde HG-plug-ins" tabindex="0">
<table class="widefat striped">
<thead><tr><th scope="col">Plug-in</th><th scope="col">Geïnstalleerd</th><th scope="col">Laatste release</th><th scope="col">Status</th></tr></thead>
<tbody>
<?php foreach ($plugins as $file => $plugin) :
$release = $releases['updates'][$plugin['slug']] ?? null;
$available = $release && version_compare($release['version'], $plugin['Version'], '>');
?>
<tr>
<th scope="row"><?php echo esc_html($plugin['Name']); ?></th>
<td><?php echo esc_html($plugin['Version']); ?></td>
<td><?php if ($release) : ?><a href="<?php echo esc_url($release['url']); ?>"><?php echo esc_html($release['version']); ?></a><?php else : ?>—<?php endif; ?></td>
<td>
<?php if ($available) : ?>
<?php // The bulk upgrader keeps the active state even when updating one plugin. ?>
<a class="button" aria-label="<?php echo esc_attr($plugin['Name'] . ' bijwerken'); ?>" href="<?php echo esc_url(wp_nonce_url(add_query_arg([
'action' => 'update-selected', 'plugins' => $file,
], network_admin_url('update.php')), 'bulk-update-plugins')); ?>">Nu bijwerken</a>
<?php elseif ($release) : ?>Actueel
<?php elseif ($releases['error']) : ?>Onbekend
<?php else : ?>Geen installatiepakket
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<?php
}
}
add_filter('hg_plugin_updates_implementation', [HG_Plugin_Updates_1_0_0::class, 'prefer']);
add_action('plugins_loaded', [HG_Plugin_Updates_1_0_0::class, 'boot'], 5);
}
+33
View File
@@ -0,0 +1,33 @@
<?php
if (!defined('ABSPATH')) exit;
function hgr_notify($id) {
global $wpdb;
$r=hgr_registration($id);if (!$r) return false;
$m=hgr_moment($r->moment_id);if (!$m) return false;
$version=(int)$r->notice_version;
// Serialize sends and re-read state so duplicate HTTP/admin requests cannot double-send.
$lock='hgr-mail-'.md5(hgr_table('registrations').':'.$id);
if ((int)$wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, 0)',$lock))!==1) return false;
try {
$r=hgr_registration($id);$version=(int)$r->notice_version;
if ($r->notice_state==='sent') return true;
$activity=get_the_title($m->activity_id);$status=hgr_statuses()[$r->status];
$people=implode("\n",array_map(fn($name)=>'- '.$name,json_decode($r->participants,true)?:[]));
$details="Activiteit: $activity\nDatum: ".hgr_local_time($m->starts_at)."\nLocatie: $m->location\nContactpersoon: $r->contact_name\nE-mail: $r->contact_email\nTelefoon: $r->phone\nOrganisatie: $r->organization\nAantal deelnemers: $r->seats\nStatus: $status\n\nDeelnemers:\n$people\n";
$link=admin_url('admin.php?page=hg-registrations&tab=registrations&registration_id='.$id);
$customer_sent=(int)$r->customer_notice_version===$version;
if (!$customer_sent) {
$customer_sent=wp_mail(hgr_settings()['recipient'],"[$activity] Inschrijving #$id — $status",$details."\nBehandelen in WordPress: $link\n");
if ($customer_sent) $wpdb->update(hgr_table('registrations'),['customer_notice_version'=>$version],['id'=>$id,'notice_version'=>$version]);
}
$intro=match($r->status){'reserved'=>'Je aanvraag is ontvangen. De plaatsen zijn gereserveerd; de organisatie bevestigt je deelname afzonderlijk.','confirmed'=>'Je deelname is bevestigd.','declined'=>'Je aanvraag is afgewezen. De gereserveerde plaatsen zijn vrijgegeven.','cancelled'=>'Je inschrijving is geannuleerd. De plaatsen zijn vrijgegeven.'};
$participant_sent=(int)$r->participant_notice_version===$version;
if (!$participant_sent) {
$participant_sent=wp_mail($r->contact_email,"[$activity] $status — inschrijving #$id",$intro."\n\n".$details);
if ($participant_sent) $wpdb->update(hgr_table('registrations'),['participant_notice_version'=>$version],['id'=>$id,'notice_version'=>$version]);
}
$sent=$customer_sent && $participant_sent;
$wpdb->update(hgr_table('registrations'),['notice_state'=>$sent?'sent':'failed'],['id'=>$id,'notice_version'=>$version]);
return $sent;
} finally { $wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)',$lock)); }
}
+145
View File
@@ -0,0 +1,145 @@
<?php
if (!defined('ABSPATH')) exit;
function hgr_table($name) { global $wpdb; return $wpdb->prefix . 'hgr_' . $name; }
function hgr_install() {
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$collate=$wpdb->get_charset_collate();
dbDelta('CREATE TABLE '.hgr_table('moments')." (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
activity_id bigint(20) unsigned NOT NULL,
starts_at datetime NOT NULL,
ends_at datetime NOT NULL,
location varchar(250) NOT NULL DEFAULT '',
capacity int unsigned NOT NULL,
state varchar(20) NOT NULL DEFAULT 'draft',
created_at datetime NOT NULL,
PRIMARY KEY (id),
KEY activity_start (activity_id,starts_at)
) ENGINE=InnoDB $collate;");
dbDelta('CREATE TABLE '.hgr_table('registrations')." (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
moment_id bigint(20) unsigned NOT NULL,
request_key char(64) NOT NULL,
contact_name varchar(150) NOT NULL,
contact_email varchar(254) NOT NULL,
phone varchar(60) NOT NULL DEFAULT '',
organization varchar(150) NOT NULL DEFAULT '',
participants longtext NOT NULL,
seats int unsigned NOT NULL,
status varchar(20) NOT NULL DEFAULT 'reserved',
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
notice_state varchar(20) NOT NULL DEFAULT 'pending',
notice_version int unsigned NOT NULL DEFAULT 1,
customer_notice_version int unsigned NOT NULL DEFAULT 0,
participant_notice_version int unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (id),
UNIQUE KEY request_key (request_key),
KEY moment_status (moment_id,status)
) ENGINE=InnoDB $collate;");
update_option('hgr_schema', HGR_VERSION);
}
function hgr_settings() {
return array_replace(['recipient'=>get_option('admin_email'),'activity_label'=>'Activiteit','moment_label'=>'Moment','max_participants'=>20], (array)get_option('hgr_settings',[]));
}
function hgr_statuses() { return ['reserved'=>'Gereserveerd','confirmed'=>'Bevestigd','declined'=>'Afgewezen','cancelled'=>'Geannuleerd']; }
function hgr_moment($id, $lock=false) {
global $wpdb;
return $wpdb->get_row($wpdb->prepare('SELECT * FROM '.hgr_table('moments').' WHERE id=%d'.($lock?' FOR UPDATE':''),$id));
}
function hgr_registration($id) { global $wpdb; return $wpdb->get_row($wpdb->prepare('SELECT * FROM '.hgr_table('registrations').' WHERE id=%d',$id)); }
function hgr_capacity($id) {
global $wpdb;
$m=hgr_moment($id);
if (!$m) return ['capacity'=>0,'reserved'=>0,'confirmed'=>0,'available'=>0];
$counts=$wpdb->get_results($wpdb->prepare('SELECT status,SUM(seats) AS seats FROM '.hgr_table('registrations')." WHERE moment_id=%d AND status IN ('reserved','confirmed') GROUP BY status",$id),OBJECT_K);
$reserved=(int)($counts['reserved']->seats??0);$confirmed=(int)($counts['confirmed']->seats??0);
return ['capacity'=>(int)$m->capacity,'reserved'=>$reserved,'confirmed'=>$confirmed,'available'=>max(0,(int)$m->capacity-$reserved-$confirmed)];
}
function hgr_local_time($date) { return wp_date('j F Y, H:i', strtotime($date.' UTC')); }
function hgr_begin() { global $wpdb; if ($wpdb->query('START TRANSACTION')===false) throw new RuntimeException('Transactie kon niet starten.'); }
function hgr_commit() { global $wpdb; if ($wpdb->query('COMMIT')===false) throw new RuntimeException('Opslaan is niet gelukt.'); }
function hgr_clean_registration($input) {
foreach (['contact_name','contact_email','phone','organization'] as $field) {
if (isset($input[$field]) && !is_scalar($input[$field])) return new WP_Error('contact','Controleer de contactgegevens.');
}
$name=sanitize_text_field($input['contact_name']??'');$email=sanitize_email($input['contact_email']??'');
if (!$name || strlen($name)>150 || !is_email($email) || strlen($email)>254) return new WP_Error('contact','Vul een geldige naam en e-mailadres in.');
$names=$input['participants']??[];$participants=[];
if (!is_array($names) || count($names)<1 || count($names)>(int)hgr_settings()['max_participants']) return new WP_Error('participants','Controleer het aantal deelnemers.');
foreach ($names as $person) {
if (!is_scalar($person)) return new WP_Error('participants','Vul voor iedere deelnemer een naam in.');
$person=sanitize_text_field($person);
if (!$person || strlen($person)>150) return new WP_Error('participants','Vul voor iedere deelnemer een naam in (maximaal 150 tekens).');
$participants[]=$person;
}
$phone=sanitize_text_field($input['phone']??'');$organization=sanitize_text_field($input['organization']??'');
if (strlen($phone)>60 || strlen($organization)>150) return new WP_Error('contact','Telefoon of organisatie is te lang.');
return ['contact_name'=>$name,'contact_email'=>$email,'phone'=>$phone,'organization'=>$organization,'participants'=>wp_json_encode($participants),'seats'=>count($participants)];
}
function hgr_reserve($moment_id,$input,$key) {
global $wpdb;
$data=hgr_clean_registration($input);if (is_wp_error($data)) return $data;
if (!preg_match('/^[a-f0-9]{64}$/',$key)) return new WP_Error('key','Ongeldige aanvraag.');
try {
hgr_begin();$m=hgr_moment($moment_id,true);
if (!$m) throw new RuntimeException('Dit moment bestaat niet.');
$existing=$wpdb->get_row($wpdb->prepare('SELECT id,moment_id FROM '.hgr_table('registrations').' WHERE request_key=%s',$key));
if ($existing) { if ((int)$existing->moment_id !== (int)$moment_id) throw new RuntimeException('Ongeldige aanvraag.'); hgr_commit();return ['id'=>(int)$existing->id,'new'=>false]; }
if ($m->state!=='open' || strtotime($m->starts_at.' UTC')<=time() || get_post_status($m->activity_id)!=='publish') throw new RuntimeException('Dit moment is niet open voor inschrijvingen.');
$cap=hgr_capacity($moment_id);
if ($data['seats']>$cap['available']) throw new RuntimeException('Er zijn niet genoeg plaatsen beschikbaar. Kies minder deelnemers of een ander moment.');
$now=current_time('mysql',true);
$data=array_merge($data,['moment_id'=>$moment_id,'request_key'=>$key,'created_at'=>$now,'updated_at'=>$now,'status'=>'reserved']);
if (!$wpdb->insert(hgr_table('registrations'),$data)) throw new RuntimeException('Opslaan is niet gelukt. Probeer het opnieuw.');
$id=(int)$wpdb->insert_id;hgr_commit();return ['id'=>$id,'new'=>true];
} catch (Throwable $e) { $wpdb->query('ROLLBACK');return new WP_Error('reservation',$e->getMessage()); }
}
function hgr_set_status($id,$status) {
global $wpdb;
if (!isset(hgr_statuses()[$status])) return new WP_Error('status','Ongeldige status.');
$initial=hgr_registration($id);if (!$initial) return new WP_Error('missing','Inschrijving niet gevonden.');
try {
hgr_begin();$m=hgr_moment($initial->moment_id,true);
$r=$wpdb->get_row($wpdb->prepare('SELECT * FROM '.hgr_table('registrations').' WHERE id=%d FOR UPDATE',$id));
if (!$m || !$r) throw new RuntimeException('Inschrijving niet gevonden.');
if ($r->status===$status) { hgr_commit();return false; }
$active=['reserved','confirmed'];
if (in_array($status,$active,true) && !in_array($r->status,$active,true)) {
if (strtotime($m->starts_at.' UTC')<=time() || $r->seats>hgr_capacity($m->id)['available']) throw new RuntimeException('Geen ruimte om deze inschrijving opnieuw te activeren.');
}
if ($wpdb->update(hgr_table('registrations'),['status'=>$status,'updated_at'=>current_time('mysql',true),'notice_state'=>'pending','notice_version'=>(int)$r->notice_version+1],['id'=>$id])===false) throw new RuntimeException('Opslaan is niet gelukt.');
hgr_commit();return true;
} catch(Throwable $e) { $wpdb->query('ROLLBACK');return new WP_Error('status',$e->getMessage()); }
}
function hgr_save_moment($input) {
global $wpdb;
$id=absint($input['id']??0);$activity=absint($input['activity_id']??0);
if (get_post_type($activity)!=='hgr_activity' || get_post_status($activity)==='trash') return new WP_Error('activity','Kies een geldige activiteit.');
$dates=[];
foreach(['starts_at','ends_at'] as $field) {
$value=(string)($input[$field]??'');
$date=DateTimeImmutable::createFromFormat('!Y-m-d\TH:i',$value,wp_timezone());
if (!$date || $date->format('Y-m-d\TH:i')!==$value) return new WP_Error('date','Vul een geldige datum en tijd in.');
$dates[$field]=$date->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
}
if ($dates['ends_at']<=$dates['starts_at']) return new WP_Error('date','De eindtijd moet na de begintijd liggen.');
$capacity=filter_var($input['capacity']??null,FILTER_VALIDATE_INT,['options'=>['min_range'=>1,'max_range'=>10000]]);
$state=$input['state']??'draft';$location=sanitize_text_field($input['location']??'');
if (!$capacity || !in_array($state,['draft','open','closed'],true) || !$location || strlen($location)>250) return new WP_Error('moment','Controleer capaciteit, locatie en status.');
try {
hgr_begin();$old=$id?hgr_moment($id,true):null;
if ($id && !$old) throw new RuntimeException('Moment niet gevonden.');
if ($old) {
$cap=hgr_capacity($id);
if ($capacity<$cap['reserved']+$cap['confirmed']) throw new RuntimeException('Capaciteit kan niet lager zijn dan het aantal gereserveerde en bevestigde deelnemers.');
$registrations=(int)$wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM '.hgr_table('registrations').' WHERE moment_id=%d',$id));
if ($registrations && ($old->activity_id!=$activity || $old->starts_at!==$dates['starts_at'] || $old->ends_at!==$dates['ends_at'] || $old->location!==$location)) throw new RuntimeException('Dit moment heeft inschrijvingen. Maak voor een gewijzigde datum, locatie of activiteit een nieuw moment aan en behandel bestaande aanvragen apart.');
}
$data=array_merge($dates,['activity_id'=>$activity,'location'=>$location,'capacity'=>$capacity,'state'=>$state]);
$ok=$old?$wpdb->update(hgr_table('moments'),$data,['id'=>$id]):$wpdb->insert(hgr_table('moments'),array_merge($data,['created_at'=>current_time('mysql',true)]));
if ($ok===false) throw new RuntimeException('Opslaan is niet gelukt.');
$saved=$old?$id:(int)$wpdb->insert_id;hgr_commit();return $saved;
} catch(Throwable $e) { $wpdb->query('ROLLBACK');return new WP_Error('moment',$e->getMessage()); }
}
+25
View File
@@ -0,0 +1,25 @@
=== HG Inschrijvingen ===
Contributors: hippogrief
Requires at least: 6.5
Requires PHP: 8.1
Stable tag: 0.1.2
License: GPLv2 or later
Activiteiten en momenten beheren met meerdere deelnemers per reservering en handmatige bevestiging.
== Gebruik ==
Voeg een activiteit toe via HG Plugins → Inschrijvingen → Activiteiten, publiceer deze en plan een moment.
Plaats [hg_registrations] of [hg_registrations activity="123"] in een shortcodeblok.
Gereserveerde en bevestigde deelnemers tellen mee voor de beschikbare capaciteit.
Stel het ontvangstadres in en configureer de mailvoorziening van de website.
== Gegevens ==
Inschrijvingen worden lokaal opgeslagen, niet bij een externe leverancier.
Deactiveren verwijdert geen gegevens. Spreek een bewaartermijn af voordat je live gaat.
Basis-antispam inbegrepen; geen online betalingen of automatische wachtlijst.
== Changelog ==
= 0.1.2 =
Openbare releases controleren via HG Plugins → Updates.
= 0.1.1 =
Gegroepeerd HG Plugins-menu met eigen zijbalkaccent en herkenning van de activiteiteneditor.
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env python3
"""Build the standalone WordPress plugin, without tests or customer data."""
from pathlib import Path
import zipfile
from sync_shared import verify_shared
root = Path(__file__).resolve().parents[1]
verify_shared(root)
target = root / 'dist/hg-registrations.zip'
target.parent.mkdir(exist_ok=True)
with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as archive:
files = [root / 'hg-registrations.php', root / 'readme.txt', root / 'LICENSE']
for folder in ['includes', 'assets']:
files.extend(sorted((root / folder).rglob('*')))
for path in files:
if path.is_file():
archive.write(path, Path('hg-registrations') / path.relative_to(root))
print(target)
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Sync or verify the shared HG files bundled by a standalone plugin."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import subprocess
SOURCE_URL = 'https://code.hosting.hippogrief.nl/hippogrief/wp-plugins'
SHARED_FILES = (
'assets/hg-admin-menu.css',
'includes/hg-admin-menu.php',
'includes/hg-plugin-updates.php',
'scripts/sync_shared.py',
)
def verify_shared(root: Path) -> None:
try:
lock = json.loads((root / 'shared.lock.json').read_text())
if lock['source'] != SOURCE_URL or not re.fullmatch(r'[0-9a-f]{40}', lock['commit']):
raise ValueError('invalid source or commit')
if set(lock['sha256']) != set(SHARED_FILES):
raise ValueError('unexpected shared file list')
for name in SHARED_FILES:
checksum = hashlib.sha256((root / name).read_bytes()).hexdigest()
if checksum != lock['sha256'][name]:
raise ValueError(f'checksum differs for {name}')
except (OSError, ValueError, TypeError, KeyError) as error:
raise SystemExit(f'HG shared files failed verification: {error}') from error
def sync_shared(root: Path, source: Path, ref: str) -> None:
git = ['git', '-C', str(source)]
commit = subprocess.check_output(
git + ['rev-parse', '--verify', '--end-of-options', f'{ref}^{{commit}}'],
text=True,
).strip()
shared_paths = {name: f'shared/{name}' for name in SHARED_FILES}
shared_paths['scripts/sync_shared.py'] = 'shared/sync_shared.py'
files = {
name: subprocess.check_output(git + ['show', f'{commit}:{remote_path}'])
for name, remote_path in shared_paths.items()
}
for name, contents in files.items():
(root / name).write_bytes(contents)
lock = {
'source': SOURCE_URL,
'commit': commit,
'sha256': {name: hashlib.sha256(contents).hexdigest() for name, contents in files.items()},
}
(root / 'shared.lock.json').write_text(json.dumps(lock, indent=2) + '\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', type=Path, help='Path to a checkout of wp-plugins')
parser.add_argument('--ref', help='Tag or commit to copy from the shared checkout')
options = parser.parse_args()
if bool(options.source) != bool(options.ref):
parser.error('--source and --ref must be supplied together')
plugin_root = Path(__file__).resolve().parents[1]
if options.source:
sync_shared(plugin_root, options.source, options.ref)
verify_shared(plugin_root)
+10
View File
@@ -0,0 +1,10 @@
{
"source": "https://code.hosting.hippogrief.nl/hippogrief/wp-plugins",
"commit": "bd66360fb9dba7de1731c5b7585ecd278055deb4",
"sha256": {
"assets/hg-admin-menu.css": "a2af6a52dc9abef9127a9d26903b9809c1001720a89f7d85f4c22bc7d8b7f581",
"includes/hg-admin-menu.php": "0723f681aeb651f1737de686ba8657e8f7adc7c53073a47025fcd1565bbe1047",
"includes/hg-plugin-updates.php": "337705f1a5f1901080c5a5450a8f2e4f394a9fa8a4a7975ec5a2371fe2e55a52",
"scripts/sync_shared.py": "a803f6d9dbcd34e6023397d9a61cd028bd04867cd0309c5b709e4282be752871"
}
}
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env python3
"""Verify that concurrent reservations cannot exceed capacity on staging."""
import argparse
from concurrent.futures import ThreadPoolExecutor
from wordpress import WordPress, add_wordpress_arguments
def main():
parser = argparse.ArgumentParser(description=__doc__)
add_wordpress_arguments(parser)
wp = WordPress(parser.parse_args())
fixture = wp.json(r"""
$activity = wp_insert_post(['post_type' => 'hgr_activity', 'post_status' => 'publish',
'post_title' => 'Temporary capacity test'], true);
if (is_wp_error($activity)) WP_CLI::error($activity->get_error_message());
$moment = hgr_save_moment(['activity_id' => $activity,
'starts_at' => wp_date('Y-m-d\TH:i', time() + 172800),
'ends_at' => wp_date('Y-m-d\TH:i', time() + 176400),
'location' => 'Test location', 'capacity' => 3, 'state' => 'open']);
if (is_wp_error($moment)) {
wp_delete_post($activity, true);
WP_CLI::error($moment->get_error_message());
}
echo wp_json_encode(['activity' => $activity, 'moment' => $moment]);
""")
moment = int(fixture['moment'])
activity = int(fixture['activity'])
try:
def attempt(_index):
return wp.json(f"""
$result = hgr_reserve({moment}, ['contact_name' => 'Test contact',
'contact_email' => 'registrant@example.test', 'participants' => ['Test participant']],
hash('sha256', wp_generate_uuid4()));
echo wp_json_encode(!is_wp_error($result));
""")
with ThreadPoolExecutor(max_workers=8) as pool:
results = list(pool.map(attempt, range(8)))
capacity = wp.json(f'echo wp_json_encode(hgr_capacity({moment}));')
assert sum(results) == 3, results
assert capacity['reserved'] == 3 and capacity['available'] == 0, capacity
print('Eight parallel requests respected the three-place capacity.')
finally:
wp.eval(f"""
global $wpdb;
$wpdb->delete(hgr_table('registrations'), ['moment_id' => {moment}]);
$wpdb->delete(hgr_table('moments'), ['id' => {moment}]);
wp_delete_post({activity}, true);
""")
if __name__ == '__main__':
main()
+11
View File
@@ -0,0 +1,11 @@
<?php
/** Isolated staging fixture for the HTTP integration test. */
if (!defined('ABSPATH')) exit;
if (wp_get_environment_type() !== 'staging') return;
define('HGR_TEST_MAIL_BLOCKED', true);
add_filter('pre_wp_mail', '__return_true', PHP_INT_MAX);
add_action('send_headers', static function (): void {
header('X-HGR-Test-Mail: blocked');
});
+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""Exercise registration and admin workflows on an isolated WordPress site."""
import argparse
import base64
from html.parser import HTMLParser
from http.cookiejar import CookieJar
import json
from pathlib import Path
import time
from urllib.parse import urlencode, urljoin, urlsplit
from urllib.request import build_opener, HTTPCookieProcessor, HTTPRedirectHandler
from wordpress import WordPress, add_wordpress_arguments
class Forms(HTMLParser):
def __init__(self):
super().__init__(convert_charrefs=True)
self.forms = []
self.current = None
self.export_url = None
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == 'form':
self.current = {
'action': attrs.get('action', ''), 'classes': attrs.get('class', '').split(), 'fields': [],
}
if self.current is not None and tag == 'input' and attrs.get('type') == 'hidden':
self.current['fields'].append((attrs['name'], attrs.get('value', '')))
if tag == 'a' and 'action=hgr_export' in attrs.get('href', ''):
self.export_url = attrs['href']
def handle_endtag(self, tag):
if tag == 'form' and self.current is not None:
self.forms.append(self.current)
self.current = None
def origin(url):
parts = urlsplit(url)
if not parts.hostname or parts.username or parts.password:
raise ValueError('Expected a WordPress URL without embedded credentials.')
if parts.scheme != 'https' and (parts.scheme != 'http' or parts.hostname not in ('localhost', '127.0.0.1', '::1')):
raise ValueError('Use HTTPS or an HTTP loopback staging URL.')
return parts.scheme, parts.hostname, parts.port or (443 if parts.scheme == 'https' else 80)
class StagingClient:
def __init__(self, home, credentials):
self.expected_origin = origin(home)
class SameOriginRedirect(HTTPRedirectHandler):
def redirect_request(handler, req, fp, code, msg, headers, newurl):
self.check_url(newurl)
return super().redirect_request(req, fp, code, msg, headers, newurl)
self.client = build_opener(HTTPCookieProcessor(CookieJar()), SameOriginRedirect())
if 'preview_user' in credentials or 'preview_password' in credentials:
pair = f"{credentials['preview_user']}:{credentials['preview_password']}"
self.client.addheaders = [('Authorization', 'Basic ' + base64.b64encode(pair.encode()).decode())]
def check_url(self, url):
if origin(url) != self.expected_origin:
raise ValueError('The staging test encountered a different HTTP origin.')
def open(self, url, fields=None):
self.check_url(url)
data = urlencode(fields).encode() if fields is not None else None
return self.client.open(url, data, timeout=15)
def create_fixture(wp):
return wp.json(r"""
$activity = wp_insert_post(['post_type' => 'hgr_activity', 'post_status' => 'publish',
'post_title' => 'Temporary HTTP test'], true);
if (is_wp_error($activity)) WP_CLI::error($activity->get_error_message());
$moment = hgr_save_moment(['activity_id' => $activity,
'starts_at' => wp_date('Y-m-d\TH:i', time() + 259200),
'ends_at' => wp_date('Y-m-d\TH:i', time() + 262800),
'location' => 'Test location', 'capacity' => 2, 'state' => 'open']);
if (is_wp_error($moment)) {
wp_delete_post($activity, true);
WP_CLI::error($moment->get_error_message());
}
$marker = wp_generate_uuid4();
$page = wp_insert_post(['post_type' => 'page', 'post_status' => 'publish',
'post_title' => 'Temporary registration fixture ' . $marker,
'post_content' => '[hg_registrations activity="' . $activity . '"]'], true);
if (is_wp_error($page)) {
global $wpdb;
$wpdb->delete(hgr_table('moments'), ['id' => $moment]);
wp_delete_post($activity, true);
WP_CLI::error($page->get_error_message());
}
echo wp_json_encode(['activity' => $activity, 'moment' => $moment, 'page' => $page,
'url' => get_permalink($page), 'marker' => $marker]);
""")
def exercise(wp, client, credentials, fixture):
with client.open(fixture['url']) as response:
assert response.headers.get('X-HGR-Test-Mail') == 'blocked', 'Staging HTTP mail fixture is inactive.'
html = response.read().decode()
assert fixture['marker'] in html, 'The HTTP site did not render the staging fixture.'
forms = Forms()
forms.feed(html)
form = next(form for form in forms.forms if 'hgr-form' in form['classes'])
assert any(key == 'hgr_token' for key, _value in form['fields'])
assert '2 beschikbaar' in html and 'van 2 plaatsen' in html
time.sleep(4)
form_url = urljoin(fixture['url'], form['action'])
fields = form['fields'] + [
('contact_name', 'Temporary HTTP test'), ('contact_email', 'registrant@example.test'),
('participants[]', 'Testdeelnemer A'), ('participants[]', 'Testdeelnemer B'),
('consent', '1'), ('website', ''),
]
with client.open(form_url, fields) as response:
assert 'hgr_reserved=1' in response.url
html = response.read().decode()
assert 'Je aanvraag is ontvangen' in html and '0 beschikbaar' in html and 'Volgeboekt' in html
with client.open(form_url, fields) as response:
response.read()
moment = int(fixture['moment'])
current = wp.json(f"""
global $wpdb;
$query = $wpdb->prepare('SELECT id,seats,status FROM ' . hgr_table('registrations') . ' WHERE moment_id=%d', {moment});
echo wp_json_encode($wpdb->get_results($query));
""")
assert len(current) == 1 and int(current[0]['seats']) == 2 and current[0]['status'] == 'reserved'
print('HTTP submission, duplicate retry and sold-out state verified.')
admin = wp.info['admin']
details = urljoin(admin, 'admin.php?' + urlencode({
'page': 'hg-registrations', 'tab': 'registrations', 'registration_id': current[0]['id'],
}))
client.check_url(details)
with client.open(wp.info['login']) as response:
response.read()
with client.open(wp.info['login'], {
'log': credentials['admin_user'], 'pwd': credentials['admin_password'],
'redirect_to': details, 'testcookie': '1',
}) as response:
assert '/wp-admin/' in response.url
html = response.read().decode()
assert '2 gereserveerd' in html and '0 beschikbaar' in html and 'Status opslaan' in html
forms = Forms()
forms.feed(html)
status = next(form for form in forms.forms if ('operation', 'status') in form['fields'])
with client.open(urljoin(details, status['action']), status['fields'] + [('status', 'confirmed')]) as response:
assert '2 bevestigd' in response.read().decode()
assert wp.json(f'echo wp_json_encode(hgr_capacity({moment}));')['confirmed'] == 2
print('Authenticated storage of the registration status verified.')
registrations = urljoin(admin, 'admin.php?page=hg-registrations&tab=registrations')
with client.open(registrations) as response:
forms = Forms()
forms.feed(response.read().decode())
assert forms.export_url, 'Export link missing.'
with client.open(urljoin(registrations, forms.export_url)) as response:
assert 'text/csv' in response.headers['Content-Type']
assert 'Testdeelnemer A' in response.read().decode('utf-8-sig')
print('Authenticated participant export verified.')
def main():
parser = argparse.ArgumentParser(description=__doc__)
add_wordpress_arguments(parser)
parser.add_argument('--credentials-file', type=Path, required=True, help='Local JSON with staging credentials')
args = parser.parse_args()
wp = WordPress(args)
if not wp.info['mail_blocked']:
raise RuntimeError('Install the HTTP test mail fixture on the isolated staging site first.')
credentials = json.loads(args.credentials_file.read_text())
for key in ('admin_user', 'admin_password'):
if not isinstance(credentials.get(key), str) or not credentials[key]:
raise ValueError(f'Missing staging credential {key}.')
client = StagingClient(wp.info['home'], credentials)
client.check_url(wp.info['login'])
client.check_url(wp.info['admin'])
fixture = create_fixture(wp)
try:
exercise(wp, client, credentials, fixture)
finally:
activity, moment, page = (int(fixture[key]) for key in ('activity', 'moment', 'page'))
wp.eval(f"""
global $wpdb;
$wpdb->delete(hgr_table('registrations'), ['moment_id' => {moment}]);
$wpdb->delete(hgr_table('moments'), ['id' => {moment}]);
wp_delete_post({activity}, true);
wp_delete_post({page}, true);
""")
if __name__ == '__main__':
main()
+49
View File
@@ -0,0 +1,49 @@
<?php
// Run only on a disposable development/staging installation: wp eval-file tests/integration.php.
if (!defined('WP_CLI') || !WP_CLI || wp_get_environment_type()!=='staging') throw new RuntimeException('Alleen via WP-CLI op staging uitvoeren.');
global $wpdb;
$activity=0;$moments=[];
$assert=function($ok,$message){if(!$ok)throw new RuntimeException($message);};
$old=get_option('hgr_settings',null);$mail=[];$mail_mode='ok';
$mail_filter=function($pre,$args)use(&$mail,&$mail_mode){$mail[]=$args;if($mail_mode==='fail')return false;if($mail_mode==='partial')return count($mail)%2===1;return true;};
add_filter('pre_wp_mail',$mail_filter,PHP_INT_MAX,2);
try {
update_option('hgr_settings',['recipient'=>'organizer@example.test','max_participants'=>20]);
$activity=wp_insert_post(['post_type'=>'hgr_activity','post_status'=>'publish','post_title'=>'HG tijdelijke integratietest']);
$start=wp_date('Y-m-d\TH:i',time()+DAY_IN_SECONDS);$end=wp_date('Y-m-d\TH:i',time()+DAY_IN_SECONDS+3600);
$moment_input=['activity_id'=>$activity,'starts_at'=>$start,'ends_at'=>$end,'location'=>'Tijdelijke testlocatie','capacity'=>3,'state'=>'open'];
$id=hgr_save_moment($moment_input);$assert(!is_wp_error($id),'Moment aanmaken');$moments[]=$id;
$input=['contact_name'=>'Testcontact','contact_email'=>'registrant@example.test','phone'=>'','organization'=>'','participants'=>['Persoon A','Persoon B']];
$key=hash('sha256',wp_generate_uuid4());$result=hgr_reserve($id,$input,$key);$assert(!is_wp_error($result)&&$result['new'],'Reserveren');$rid=$result['id'];
$assert(hgr_capacity($id)['reserved']===2 && hgr_capacity($id)['available']===1,'Capaciteit na reserveren');
$replay=hgr_reserve($id,$input,$key);$assert(!$replay['new']&&$replay['id']===$rid,'Idempotente dubbele aanvraag');
$assert(is_wp_error(hgr_reserve($id,$input,hash('sha256',wp_generate_uuid4()))),'Overboeking geweigerd');
$assert(is_wp_error(hgr_save_moment(array_merge($moment_input,['id'=>$id,'capacity'=>1]))),'Capaciteit verkleinen geweigerd');
$assert(is_wp_error(hgr_save_moment(array_merge($moment_input,['id'=>$id,'location'=>'Andere locatie']))),'Geboekt moment verplaatsen geweigerd');
$assert(hgr_set_status($rid,'confirmed')===true,'Bevestigen');$assert(hgr_capacity($id)['confirmed']===2&&hgr_capacity($id)['reserved']===0,'Bevestiging houdt plaatsen vast');
$assert(hgr_notify($rid),'Mailinhoud en verzending');$assert(count($mail)===2,'Twee meldingen');
$expected=apply_filters('wp_mail',['to'=>'registrant@example.test','subject'=>'','message'=>'','headers'=>[]]);
$assert($mail[0]['to']==='organizer@example.test' && $mail[1]['to']===$expected['to'],'Mailontvangers en eventuele staging-omleiding');
$assert(str_contains($mail[0]['message'],'Aantal deelnemers: 2') && str_contains($mail[1]['message'],'Je deelname is bevestigd.'),'Mail bevat deelnemers en status');
hgr_notify($rid);$assert(count($mail)===2,'Meldingen niet dubbel verstuurd');
$assert(hgr_set_status($rid,'cancelled')===true,'Annuleren');$assert(hgr_capacity($id)['available']===3,'Annulering geeft plaatsen vrij');
$input['participants']=['Persoon C','Persoon D','Persoon E'];$next=hgr_reserve($id,$input,hash('sha256',wp_generate_uuid4()));$assert(!is_wp_error($next),'Vrijgekomen plaatsen reserveren');
$assert(is_wp_error(hgr_set_status($rid,'confirmed')),'Geen overboeking bij heractiveren');
$assert(hgr_capacity($id)['available']===0,'Volgeboekt');
$html=do_shortcode('[hg_registrations activity="'.$activity.'"]');$assert(str_contains($html,'Volgeboekt')&&!str_contains($html,'name="participants[]"'),'Geen formulier bij vol');
$mail_mode='fail';$assert(!hgr_notify($next['id']),'Mailfalen zichtbaar');$assert(hgr_registration($next['id'])->notice_state==='failed','Mailstatus bewaard');$assert(hgr_capacity($id)['reserved']===3,'Mailfalen verliest reservering niet');
$mail_mode='ok';$assert(hgr_notify($next['id']),'Mislukte berichten opnieuw versturen');
hgr_set_status($next['id'],'declined');$assert(hgr_capacity($id)['available']===3,'Afwijzing geeft plaatsen vrij');
$assert(hgr_check_token(hgr_form_token($id,time()-4),$id),'Geldig ondertekend formulier');
$assert(!hgr_check_token(hgr_form_token($id,time()-8000),$id),'Verlopen formulier geweigerd');
$assert(!hgr_check_token(hgr_form_token($id,time()-4),$id+1),'Formulier aan moment gebonden');
$assert(is_wp_error(hgr_clean_registration(['contact_name'=>['x'],'participants'=>['x']])),'Ongeldige gegevens geweigerd');
$assert(wp_delete_post($activity,true)===false,'Activiteit met momenten niet permanent verwijderen');
$caps=map_meta_cap('edit_post',0,$activity);$assert(in_array('manage_options',$caps,true),'Activiteiten alleen door beheerders bewerken');
WP_CLI::success('Reserveringen, capaciteit, statussen, mail, duplicaten en validatie gecontroleerd; geen echte e-mails verzonden.');
} finally {
foreach($moments as $id){$wpdb->delete(hgr_table('registrations'),['moment_id'=>$id]);$wpdb->delete(hgr_table('moments'),['id'=>$id]);}
if($activity)wp_delete_post($activity,true);
if($old===null)delete_option('hgr_settings');else update_option('hgr_settings',$old);
remove_filter('pre_wp_mail',$mail_filter,PHP_INT_MAX);
}
+32
View File
@@ -0,0 +1,32 @@
"""WP-CLI access for the isolated registrations test scripts."""
import json
import subprocess
def add_wordpress_arguments(parser):
parser.add_argument('--wp-path', required=True, help='WordPress root of the staging installation')
parser.add_argument('--wp-cli', default='wp', help='WP-CLI executable')
class WordPress:
def __init__(self, args):
self.command = [args.wp_cli, '--path=' + args.wp_path, 'eval', 'eval(stream_get_contents(STDIN));']
self.info = self.json("""
if (wp_get_environment_type() !== 'staging' || !function_exists('hgr_reserve')) {
WP_CLI::error('Use a staging installation with HG Inschrijvingen active.');
}
echo wp_json_encode([
'home' => home_url(), 'admin' => admin_url(), 'login' => wp_login_url(),
'mail_blocked' => defined('HGR_TEST_MAIL_BLOCKED'),
]);
""")
def eval(self, code):
result = subprocess.run(self.command, input=code, text=True, capture_output=True, timeout=20)
if result.returncode:
raise RuntimeError(result.stderr.strip())
return result.stdout
def json(self, code):
return json.loads(self.eval(code))