Add reusable NL/EN contact form with configurable admin settings

This commit is contained in:
parkel committed 2026-10-11 21:15:13 +02:00
commit 3e598b4bae
11 files changed
+633

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
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 Contactformulier
Herbruikbaar NL/EN-contactformulier voor WordPress. Ontwikkeling gebeurt in deze Git-repository; klantinstellingen staan uitsluitend in de eigen WordPress-database.
## Installatie en gebruik
1. Maak het installatiebestand met `python3 scripts/build.py`.
2. Upload `dist/hg-contactform.zip` via Plugins → Nieuwe plugin → Plugin uploaden en activeer HG Contactformulier.
3. Open **Contactformulier** in de beheerzijbalk en configureer het ontvangstadres, de naam en de teksten.
4. Plaats `[hg_contactform]` in een shortcodeblok op een pagina of bericht. Gebruik `lang="nl"` of `lang="en"` voor een vaste taal.
Polylang wordt gebruikt voor automatische taalkeuze wanneer beschikbaar; anders volgt de plugin de WordPress-sitetaal. Het bestaande `[mlh_contact]` blijft als compatibiliteitsalias beschikbaar. De plugin heeft eigen CSS en werkt zonder het oorspronkelijke klantthema. Gebruik één formulier per pagina. Directe shortcodes in de inhoud worden ondersteund; plaats het formulier niet alleen in een template, widget of gesynchroniseerd patroon.
## Instellingen
- Ontvangstadres en naam voor het e-mailonderwerp.
- Contactnaam, beschikbaar als `{contact_name}` in de configureerbare teksten.
- Vraagmodus en optionele afspraakaanvragen, optioneel telefoonveld.
- Vroegste en laatste voorkeurtijd; dit controleert een tijdvoorkeur, geen beschikbaarheid.
- Diensten per regel als `code|Nederlandse naam|Engelse naam`; maximaal 50 unieke codes. `unsure` wordt automatisch toegevoegd.
- NL/EN-formuliertitel, aanvraaglabel, dienstenlabel, toestemming, toelichting en bevestigingstekst.
Instellingen worden opgeslagen via de WordPress Settings API en zijn alleen te wijzigen door gebruikers met `manage_options`. Ongeldige e-mailadressen, tijdsbereiken en dienstenlijsten behouden de vorige geldige waarde.
## Gedrag en beheer
Berichten worden met `wp_mail()` verstuurd, niet als inzendingen opgeslagen. De bestaande mailvoorziening bepaalt aflevering; de plugin configureert geen SMTP. Gebruik geen gevoelige medische gegevens in dit formulier. Antispam bestaat uit noncecontrole, honeypot, een getekend tijdstip en een limiet per gehashte IP-identificatie. Tijdelijke rate-limitgegevens blijven maximaal vijftien minuten na de laatste poging bestaan. Cache pagina’s met het formulier niet langdurig: nonces en tijdstempels verlopen.
Een aanvraag is pas een afspraak na bevestiging. Er is geen agenda, beschikbaarheidscontrole of automatische boeking. De plugin bevat geen klantadres, serverpad of vereiste klantoptie.
## Verificatie
`node --check assets/contact.js` controleert de JavaScript-syntax. Voer de integratiechecks uit in een WordPress-installatie met de plugin actief:
```sh
wp eval-file /pad/naar/hg_contactform/tests/integration.php
```
De checks injecteren tijdelijke instellingen via filters, onderscheppen e-mail en schrijven geen formulierinzendingen of permanente testinstellingen. PHP-syntax kan met `php -l` worden gecontroleerd. Test echte mailaflevering apart met een expliciet afgesproken testadres.
## Uitrollen
Maak een nieuw ZIP vanuit een geteste commit. Bewaar vóór vervanging de bestaande plugin en instellingen van de doelwebsite. Upload en activeer alleen binnen die website; stel per installatie het ontvangstadres en de teksten in. Draai deze plugin niet gelijktijdig met de oude klantplugin omdat beide dezelfde compatibiliteitsshortcode registreren. Bij de bestaande website zijn de klantinstellingen expliciet overgenomen bij de overstap.
+4
View File
@@ -0,0 +1,4 @@
.hgcf-contact{--ink:#382b31;--muted:#715e65;--rose:#a62e62;--cream:#fcf9f6;--line:#e6d7db;box-sizing:border-box;font-family:system-ui,sans-serif}.hgcf-contact *{box-sizing:border-box}.hgcf-contact [hidden]{display:none!important}.hgcf-contact .button{background:var(--rose);color:white;border-radius:5px;padding:13px 23px;font:600 15px/1.5 system-ui,sans-serif}
.contact-form{margin-top:40px;padding:30px;background:#fff;border:1px solid var(--line);border-radius:12px;max-width:850px}.contact-form h2{font-size:1.8rem}.mlhc-form label{display:block;font-size:14px;font-weight:600;margin:0 0 18px}.mlhc-form input:not([type=radio]):not([type=checkbox]):not([type=hidden]),.mlhc-form select,.mlhc-form textarea{display:block;width:100%;border:1px solid #ad98a1;border-radius:5px;padding:11px 12px;margin:7px 0 0;font:400 16px/1.5 system-ui,sans-serif;color:var(--ink);background:#fcf9f6}.mlhc-form input:focus-visible,.mlhc-form select:focus-visible,.mlhc-form textarea:focus-visible{outline:2px solid var(--rose);outline-offset:2px}.mlhc-form fieldset{border:0;margin:0 0 20px;padding:0}.mlhc-form legend{font-size:14px;font-weight:600;margin-bottom:12px}.form-mode{display:flex;flex-wrap:wrap;gap:12px 25px}.form-mode label{font-weight:400;margin:0;display:flex;gap:9px;align-items:center}.mlhc-form input[type=radio],.mlhc-form input[type=checkbox]{accent-color:var(--rose);width:18px;height:18px;flex-shrink:0}.form-fields{display:grid;grid-template-columns:1fr 1fr;gap:18px}.request-fields{background:var(--cream);padding:18px!important;border-radius:8px}.request-fields[hidden]{display:none}.mlhc-form .consent{display:flex;gap:10px;align-items:start;font-weight:400}.form-note{font-size:12px;color:var(--muted);line-height:1.6}.mlhc-form button{border:0;cursor:pointer}.mlhc-form button:disabled{opacity:.7;cursor:wait}.mlhc-trap{position:absolute;left:-10000px;width:1px;height:1px;overflow:hidden}.form-errors{border:1px solid var(--rose);background:#fff0f5;border-radius:6px;padding:18px;margin-bottom:22px;font-size:14px}.form-errors p{margin-bottom:8px}.form-errors ul{margin:0;padding-left:20px}.form-success{border-color:#497653}.form-success h2{color:#315a3a}
@media(max-width:540px){.hgcf-contact .form-fields{grid-template-columns:1fr;gap:0}.hgcf-contact{padding:20px}}
+18
View File
@@ -0,0 +1,18 @@
(() => {
const labels=window.hgcfLabels||{};
document.querySelectorAll('.mlhc-form').forEach(form=>{
const requestFields=form.querySelector('.request-fields');
const message=form.querySelector('[name="mlhc_message"]');
function update(){
const request=form.querySelector('[name="mlhc_mode"]:checked').value==='request';
if(requestFields)requestFields.hidden=!request;
if(requestFields)requestFields.disabled=!request;
message.required=!request;
if(request) message.removeAttribute('minlength'); else message.minLength=5;
form.querySelector('.message-label').textContent=request?labels.request:labels.question;
}
form.querySelectorAll('[name="mlhc_mode"]').forEach(input=>input.addEventListener('change',update));update();
form.addEventListener('submit',()=>{const button=form.querySelector('[type="submit"]');button.disabled=true;button.textContent=labels.sending;});
});
const errors=document.querySelector('.form-errors');if(errors)errors.focus();
})();
+106
View File
@@ -0,0 +1,106 @@
<?php
/**
* Plugin Name: HG Contactformulier
* Description: Tweetalig contactformulier voor vragen en massageaanvragen, zonder inzendingen in WordPress op te slaan.
* Version: 1.0.0
* Requires at least: 6.5
* Requires PHP: 8.0
* Text Domain: hg-contactform
*/
if (!defined('ABSPATH')) { exit; }
require_once __DIR__.'/includes/settings.php';
require_once __DIR__.'/includes/language.php';
function hgcf_text($nl,$en,$lang) { return $lang==='en'?$en:$nl; }
function hgcf_types() { return hgcf_setting('services')+['unsure'=>['Ik weet het nog niet','Not sure yet']]; }
function hgcf_validate(array $source, $lang='nl') {
$errors=new WP_Error(); $data=[];
foreach(['name','email','phone','message','mode','massage','preferred_date','preferred_time'] as $key) {
if(isset($source[$key]) && !is_string($source[$key])) { $errors->add('invalid',hgcf_text('Controleer de ingevulde velden.','Please check the form fields.',$lang)); return $errors; }
$data[$key]=trim(wp_unslash($source[$key]??''));
}
if(strlen($data['name'])<2 || strlen($data['name'])>120) $errors->add('name',hgcf_text('Vul je naam in (2 tot 120 tekens).','Enter your name (2 to 120 characters).',$lang));
if(strlen($data['email'])>254 || !is_email($data['email']) || preg_match('/[\r\n]/',$data['email'])) $errors->add('email',hgcf_text('Vul een geldig e-mailadres in.','Enter a valid email address.',$lang));
if(!in_array($data['mode'],['question','request'],true)) $errors->add('mode',hgcf_text('Kies een vraag of afspraakaanvraag.','Choose a question or appointment request.',$lang));
if(hgcf_setting('show_phone') && (strlen($data['phone'])>40 || (hgcf_setting('show_phone') && $data['phone']!=='' && !preg_match('/^[0-9+() .-]{5,40}$/',$data['phone'])))) $errors->add('phone',hgcf_text('Controleer je telefoonnummer.','Please check your phone number.',$lang));
if(strlen($data['message'])>5000 || ($data['mode']==='question' && strlen($data['message'])<5)) $errors->add('message',hgcf_text('Schrijf je vraag (5 tot 5000 tekens).','Write your question (5 to 5000 characters).',$lang));
if($data['mode']==='request' && !hgcf_setting('enable_requests')) $errors->add('mode',hgcf_text('Afspraakaanvragen zijn niet ingeschakeld.','Appointment requests are not enabled.',$lang));
if(!hgcf_setting('show_phone')) $data['phone']='';
if($data['mode']==='request') {
if(!isset(hgcf_types()[$data['massage']])) $errors->add('massage',hgcf_text('Kies een dienst of “Ik weet het nog niet”.','Choose a service or “Not sure yet”.',$lang));
if($data['preferred_date']!=='') {
$date=DateTimeImmutable::createFromFormat('!Y-m-d',$data['preferred_date'],wp_timezone());
if(!$date || $date->format('Y-m-d')!==$data['preferred_date'] || $data['preferred_date']<wp_date('Y-m-d')) $errors->add('preferred_date',hgcf_text('Kies vandaag of een datum in de toekomst.','Choose today or a future date.',$lang));
}
if($data['preferred_time']!=='' && (!preg_match('/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/',$data['preferred_time']) || $data['preferred_time']<hgcf_setting('opening_time') || $data['preferred_time']>hgcf_setting('closing_time'))) $errors->add('preferred_time',sprintf(hgcf_text('Kies een tijd tussen %s en %s.','Choose a time between %s and %s.',$lang),hgcf_setting('opening_time'),hgcf_setting('closing_time')));
} else { $data['massage']=$data['preferred_date']=$data['preferred_time']=''; }
if(empty($source['consent']) || !is_string($source['consent']) || $source['consent']!=='1') $errors->add('consent',hgcf_text('Geef toestemming om je gegevens voor een reactie te gebruiken.','Allow me to use your details to reply.',$lang));
if($errors->has_errors()) return $errors;
foreach($data as $key=>$value) $data[$key]=$key==='message'?sanitize_textarea_field($value):sanitize_text_field($value);
return $data;
}
function hgcf_send(array $data, $lang) {
$request=$data['mode']==='request';
$body="Contactformulier ".sanitize_text_field(hgcf_setting('site_name'))."\nTaal: ".$lang."\nType: ".($request?'Afspraakaanvraag':'Vraag')."\nNaam: ".$data['name']."\nE-mail: ".$data['email']."\nTelefoon: ".($data['phone']?:'Niet opgegeven')."\n";
if($request) { $type=hgcf_types()[$data['massage']]; $body.="Dienst: ".$type[0]."\nVoorkeursdatum: ".($data['preferred_date']?:'Geen voorkeur')."\nVoorkeurstijd: ".($data['preferred_time']?:'Geen voorkeur')."\nDit is een aanvraag, geen bevestigde afspraak.\n"; }
$body.="\nBericht:\n".$data['message'];
return wp_mail(hgcf_setting('recipient'),sanitize_text_field(hgcf_setting('site_name')).': '.($request?'afspraakaanvraag':'vraag'),$body,['Content-Type: text/plain; charset=UTF-8','Reply-To: '.$data['email']]);
}
add_action('template_redirect', function () {
if(($_SERVER['REQUEST_METHOD']??'')!=='POST' || ($_POST['mlhc_action']??'')!=='send') return;
$id=get_queried_object_id(); $post=get_post($id);
if(!is_singular() || !$post || (!has_shortcode($post->post_content,'hg_contactform') && !has_shortcode($post->post_content,'mlh_contact'))) wp_die('Invalid form page', '', ['response'=>403]);
$lang=hgcf_language($post->post_content);
$error=hgcf_text('Het versturen is niet gelukt. Probeer het opnieuw of gebruik een andere contactmogelijkheid.','Your message could not be sent. Please try again or use another contact option.',$lang);
$nonce=$_POST['mlhc_nonce']??''; $started=$_POST['mlhc_started']??''; $signature=$_POST['mlhc_signature']??'';
if(!is_string($nonce) || !wp_verify_nonce($nonce,'hgcf_send') || !is_string($started) || !ctype_digit($started) || !is_string($signature) || !hash_equals(hash_hmac('sha256',$started,wp_salt('nonce')),$signature) || time()-(int)$started<2 || time()-(int)$started>DAY_IN_SECONDS || !empty($_POST['mlhc_website'])) {
$GLOBALS['mlhc_errors']=new WP_Error('security',$error); return;
}
$submitted=[]; foreach(['name','email','phone','message','mode','massage','preferred_date','preferred_time','consent'] as $field) { if(isset($_POST['mlhc_'.$field])) $submitted[$field]=$_POST['mlhc_'.$field]; }
$data=hgcf_validate($submitted,$lang);
if(is_wp_error($data)) { $GLOBALS['mlhc_errors']=$data; return; }
$ip=$_SERVER['REMOTE_ADDR']??'unknown';
$rate_key='mlhc_rate_'.hash_hmac('sha256',$ip,wp_salt('auth'));
$rate=get_transient($rate_key);
if($rate && ($rate['count']>=5 || time()-$rate['last']<30)) { $GLOBALS['mlhc_errors']=new WP_Error('rate',hgcf_text('Even geduld: probeer het over een minuut opnieuw of gebruik een andere contactmogelijkheid.','Please wait a minute before trying again, or use another contact option.',$lang)); return; }
$rate=$rate?:['count'=>0,'last'=>0]; $rate['count']++;$rate['last']=time();set_transient($rate_key,$rate,15*MINUTE_IN_SECONDS);
if(!hgcf_send($data,$lang)) { $GLOBALS['mlhc_errors']=new WP_Error('mail',$error); return; }
$url=add_query_arg(['contact_status'=>'received','receipt'=>wp_create_nonce('mlhc_received_'.$id)],get_permalink($id));
wp_safe_redirect($url.'#contact-form',303);exit;
});
function hgcf_render($atts=[]) {
$atts=shortcode_atts(['lang'=>'auto'],$atts);$lang=in_array($atts['lang'],['nl','en'],true)?$atts['lang']:hgcf_language();
$t=function($nl,$en)use($lang){return hgcf_text($nl,$en,$lang);};
$errors=$GLOBALS['mlhc_errors']??null;
$receipt=$_GET['receipt']??'';
if(($_GET['contact_status']??'')==='received' && is_string($receipt) && wp_verify_nonce($receipt,'mlhc_received_'.get_queried_object_id())) return '<section id="contact-form" class="contact-form hgcf-contact form-success" role="status"><h2>'.esc_html($t('Bedankt voor je bericht.','Thank you for your message.')).'</h2><p>'.esc_html(hgcf_local_setting('success',$lang).(hgcf_setting('enable_requests')?' '.$t('Een aanvraag is pas een afspraak na bevestiging.','A request becomes an appointment only after confirmation.'):'')).'</p><a href="'.esc_url(get_permalink()).'">'.esc_html($t('Nog een bericht sturen','Send another message')).'</a></section>';
$value=function($key)use($errors){return $errors && isset($_POST['mlhc_'.$key]) && is_string($_POST['mlhc_'.$key])?wp_unslash($_POST['mlhc_'.$key]):'';};
$mode=hgcf_setting('enable_requests') && $value('mode')==='request'?'request':'question';$started=(string)time();
ob_start(); ?>
<section class="contact-form hgcf-contact" id="contact-form"><h2><?php echo esc_html(hgcf_local_setting('title',$lang)); ?></h2>
<?php if($errors): ?><div class="form-errors" role="alert" tabindex="-1"><p><strong><?php echo esc_html($t('Controleer je bericht:','Please check your message:')); ?></strong></p><ul><?php foreach($errors->get_error_messages() as $message): ?><li><?php echo esc_html($message); ?></li><?php endforeach; ?></ul></div><?php endif; ?>
<form class="mlhc-form" action="<?php echo esc_url(get_permalink()); ?>#contact-form" method="post">
<input type="hidden" name="mlhc_action" value="send"><?php wp_nonce_field('hgcf_send','mlhc_nonce',false); ?>
<input type="hidden" name="mlhc_started" value="<?php echo esc_attr($started); ?>"><input type="hidden" name="mlhc_signature" value="<?php echo esc_attr(hash_hmac('sha256',$started,wp_salt('nonce'))); ?>">
<div class="mlhc-trap" aria-hidden="true"><label for="mlhc-website">Website</label><input tabindex="-1" autocomplete="off" id="mlhc-website" name="mlhc_website" type="text"></div>
<fieldset class="form-mode"><legend><?php echo esc_html($t('Ik wil…','I would like to…')); ?></legend><label><input type="radio" name="mlhc_mode" value="question" <?php checked($mode,'question'); ?>><?php echo esc_html($t('Een vraag stellen','Ask a question')); ?></label><?php if(hgcf_setting('enable_requests')): ?><label><input type="radio" name="mlhc_mode" value="request" <?php checked($mode,'request'); ?>><?php echo esc_html(hgcf_local_setting('request_label',$lang)); ?></label><?php endif; ?></fieldset>
<div class="form-fields"><label for="mlhc-name"><?php echo esc_html($t('Naam *','Name *')); ?><input id="mlhc-name" name="mlhc_name" autocomplete="name" required minlength="2" maxlength="120" value="<?php echo esc_attr($value('name')); ?>"></label><label for="mlhc-email"><?php echo esc_html($t('E-mailadres *','Email address *')); ?><input id="mlhc-email" type="email" name="mlhc_email" autocomplete="email" required maxlength="254" value="<?php echo esc_attr($value('email')); ?>"></label></div>
<?php if(hgcf_setting('show_phone')): ?><label for="mlhc-phone"><?php echo esc_html($t('Telefoonnummer (optioneel)','Phone number (optional)')); ?><input id="mlhc-phone" type="tel" name="mlhc_phone" autocomplete="tel" maxlength="40" value="<?php echo esc_attr($value('phone')); ?>"></label>
<?php endif; ?>
<?php if(hgcf_setting('enable_requests')): ?><fieldset class="request-fields"><legend><?php echo esc_html($t('Voor je afspraakaanvraag','For your appointment request')); ?></legend><label for="mlhc-massage"><?php echo esc_html(hgcf_local_setting('service_label',$lang)); ?><select id="mlhc-massage" name="mlhc_massage"><?php foreach(hgcf_types() as $key=>$name): ?><option value="<?php echo esc_attr($key); ?>" <?php selected($value('massage')?:'unsure',$key); ?>><?php echo esc_html($name[$lang==='en'?1:0]); ?></option><?php endforeach; ?></select></label>
<div class="form-fields"><label for="mlhc-date"><?php echo esc_html($t('Voorkeursdatum (optioneel)','Preferred date (optional)')); ?><input id="mlhc-date" name="mlhc_preferred_date" type="date" min="<?php echo esc_attr(wp_date('Y-m-d')); ?>" value="<?php echo esc_attr($value('preferred_date')); ?>"></label><label for="mlhc-time"><?php echo esc_html($t('Voorkeurstijd (optioneel)','Preferred time (optional)')); ?><input id="mlhc-time" name="mlhc_preferred_time" type="time" min="<?php echo esc_attr(hgcf_setting('opening_time')); ?>" max="<?php echo esc_attr(hgcf_setting('closing_time')); ?>" value="<?php echo esc_attr($value('preferred_time')); ?>"></label></div><p class="form-note"><?php echo esc_html($t('Dit is een voorkeur, geen reservering. We stemmen de datum en tijd met je af.','This is a preference, not a reservation. We will confirm the date and time with you.')); ?></p></fieldset><?php endif; ?>
<label for="mlhc-message"><span class="message-label"><?php echo esc_html($t('Je vraag *','Your question *')); ?></span><textarea id="mlhc-message" name="mlhc_message" rows="5" maxlength="5000"><?php echo esc_textarea($value('message')); ?></textarea></label>
<label class="consent"><input type="checkbox" name="mlhc_consent" value="1" required <?php checked($value('consent'),'1'); ?>><span><?php echo esc_html(hgcf_local_setting('consent',$lang)); ?></span></label>
<p class="form-note"><?php echo esc_html(hgcf_local_setting('note',$lang)); ?></p>
<button class="button" type="submit"><?php echo esc_html($t('Verstuur bericht','Send message')); ?></button>
</form></section>
<?php
wp_enqueue_style('hgcf',plugins_url('assets/contact.css',__FILE__),[],'1.0.0');
wp_enqueue_script('hgcf',plugins_url('assets/contact.js',__FILE__),[], '1.0.0',true);
wp_add_inline_script('hgcf','window.hgcfLabels='.wp_json_encode(['question'=>$t('Je vraag *','Your question *'),'request'=>$t('Toelichting (optioneel)','Message (optional)'),'send'=>$t('Verstuur bericht','Send message'),'sending'=>$t('Wordt verstuurd…','Sending…')]).';','before');
return ob_get_clean();
}
add_shortcode('hg_contactform','hgcf_render');
add_shortcode('mlh_contact','hgcf_render');
add_action('wp_enqueue_scripts',function(){
$post=get_post();if(is_singular()&&$post&&(has_shortcode($post->post_content,'hg_contactform')||has_shortcode($post->post_content,'mlh_contact')))wp_enqueue_style('hgcf',plugins_url('assets/contact.css',__FILE__),[],'1.0.0');
});
+9
View File
@@ -0,0 +1,9 @@
<?php
if(!defined('ABSPATH'))exit;
function hgcf_language($content='') {
if($content!=='' && preg_match('/'.get_shortcode_regex(['hg_contactform','mlh_contact']).'/s',$content,$match)) {
$attrs=shortcode_parse_atts($match[3]);if(is_array($attrs)&&in_array($attrs['lang']??'',['nl','en'],true))return $attrs['lang'];
}
if(function_exists('pll_current_language')){ $language=pll_current_language('slug');if(in_array($language,['nl','en'],true))return $language; }
return str_starts_with(get_locale(),'en')?'en':'nl';
}
+55
View File
@@ -0,0 +1,55 @@
<?php
if (!defined('ABSPATH')) exit;
function hgcf_defaults() {
return ['recipient'=>get_option('admin_email'),'site_name'=>get_bloginfo('name'),'contact_name'=>'','enable_requests'=>false,'show_phone'=>true,'opening_time'=>'09:00','closing_time'=>'21:00','services'=>[],
'title_nl'=>'Waarmee kunnen we je helpen?','title_en'=>'How can we help?',
'request_label_nl'=>'Een afspraak aanvragen','request_label_en'=>'Request an appointment',
'service_label_nl'=>'Waarvoor wil je een afspraak?','service_label_en'=>'Which service would you like?',
'consent_nl'=>'Mijn gegevens mogen worden gebruikt om op dit bericht te reageren.','consent_en'=>'My details may be used to reply to this message.',
'note_nl'=>'Je bericht wordt per e-mail verstuurd en niet op deze website opgeslagen. Deel hier geen medische of andere gevoelige gegevens.','note_en'=>'Your message is sent by email and is not stored on this website. Please do not include medical or other sensitive details.',
'success_nl'=>'Je bericht is aangeboden voor verzending. We nemen zo snel mogelijk contact met je op.','success_en'=>'Your message has been submitted for sending. We will get back to you as soon as possible.'];
}
function hgcf_settings() { $saved=get_option('hgcf_settings',[]); return array_replace(hgcf_defaults(),is_array($saved)?$saved:[]); }
function hgcf_setting($key) { return hgcf_settings()[$key]??''; }
function hgcf_local_setting($key,$lang) { return str_replace('{contact_name}',hgcf_setting('contact_name')?:hgcf_setting('site_name'),hgcf_setting($key.'_'.($lang==='en'?'en':'nl'))); }
function hgcf_sanitize_settings($input) {
$old=hgcf_settings(); if(!is_array($input))return $old;
$out=$old;
if(!isset($input['recipient']) || !is_string($input['recipient']) || !is_email($input['recipient']) || preg_match('/[\r\n]/',$input['recipient'])) {add_settings_error('hgcf_settings','recipient','Vul een geldig ontvangstadres in.');} else {$out['recipient']=sanitize_email($input['recipient']);}
foreach(['site_name','contact_name','title_nl','title_en','request_label_nl','request_label_en','service_label_nl','service_label_en','consent_nl','consent_en','note_nl','note_en','success_nl','success_en'] as $key) {
if(isset($input[$key]) && is_string($input[$key])) {$value=sanitize_textarea_field($input[$key]); if(strlen($value)<=1500 && ($key==='contact_name'||$value!==''))$out[$key]=$value;else add_settings_error('hgcf_settings',$key,'Controleer het veld '.$key.'.');}
}
foreach(['enable_requests','show_phone'] as $key)$out[$key]=isset($input[$key])&&$input[$key]==='1';
$start=$input['opening_time']??'';$end=$input['closing_time']??'';
if(is_string($start)&&is_string($end)&&preg_match('/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/',$start)&&preg_match('/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/',$end)&&$start<$end){$out['opening_time']=$start;$out['closing_time']=$end;}else add_settings_error('hgcf_settings','times','Vul geldige tijden in, met de begintijd vóór de eindtijd.');
if(isset($input['services_text'])&&is_string($input['services_text'])) {
$services=[];$valid=strlen($input['services_text'])<=12000;
foreach(preg_split('/\r\n|\r|\n/',$input['services_text']) as $line) {
if(trim($line)==='')continue;
$parts=array_map('trim',explode('|',$line));
if(count($parts)!==3 || !preg_match('/^[a-z][a-z0-9_-]{0,39}$/',$parts[0]) || $parts[0]==='unsure' || isset($services[$parts[0]]) || $parts[1]==='' || $parts[2]==='' || strlen($parts[1])>150 || strlen($parts[2])>150){$valid=false;break;}
$services[$parts[0]]=[sanitize_text_field($parts[1]),sanitize_text_field($parts[2])];
}
if($valid&&count($services)<=50)$out['services']=$services;else add_settings_error('hgcf_settings','services','Gebruik maximaal 50 unieke regels: code|Nederlandse naam|Engelse naam. De code unsure is gereserveerd.');
}
return $out;
}
add_action('admin_menu',function(){add_menu_page('HG Contactformulier','Contactformulier','manage_options','hg-contactform','hgcf_admin_page','dashicons-email-alt',58);});
add_action('admin_init',function(){register_setting('hgcf','hgcf_settings',['type'=>'array','sanitize_callback'=>'hgcf_sanitize_settings','default'=>hgcf_defaults()]);});
function hgcf_admin_page() {
if(!current_user_can('manage_options'))wp_die('Geen toegang.', '', ['response'=>403]);
$s=hgcf_settings();
?>
<div class="wrap"><h1>HG Contactformulier</h1><p>Gebruik <code>[hg_contactform]</code> op een pagina. De taal wordt automatisch gekozen; je kunt ook <code>[hg_contactform lang="nl"]</code> of <code>[hg_contactform lang="en"]</code> gebruiken.</p>
<?php settings_errors('hgcf_settings'); ?><form action="options.php" method="post"><?php settings_fields('hgcf'); ?>
<h2>Algemeen</h2><table class="form-table" role="presentation">
<?php foreach(['recipient'=>['Ontvangstadres','email'],'site_name'=>['Naam in e-mailonderwerp','text'],'contact_name'=>['Contactnaam (optioneel)','text'],'opening_time'=>['Vroegste voorkeurtijd','time'],'closing_time'=>['Laatste voorkeurtijd','time']] as $key=>$field): ?>
<tr><th scope="row"><label for="hgcf-<?php echo esc_attr($key); ?>"><?php echo esc_html($field[0]); ?></label></th><td><input id="hgcf-<?php echo esc_attr($key); ?>" class="regular-text" type="<?php echo esc_attr($field[1]); ?>" name="hgcf_settings[<?php echo esc_attr($key); ?>]" value="<?php echo esc_attr($s[$key]); ?>" <?php if($key==='recipient')echo 'required'; ?>></td></tr>
<?php endforeach; ?>
<?php foreach(['enable_requests'=>'Afspraakaanvragen inschakelen','show_phone'=>'Optioneel telefoonveld tonen'] as $key=>$label): ?><tr><th scope="row"><?php echo esc_html($label); ?></th><td><label><input type="checkbox" name="hgcf_settings[<?php echo esc_attr($key); ?>]" value="1" <?php checked($s[$key]); ?>> Ingeschakeld</label></td></tr><?php endforeach; ?>
<tr><th scope="row"><label for="hgcf-services">Diensten / behandelingen</label></th><td><textarea id="hgcf-services" name="hgcf_settings[services_text]" class="large-text code" rows="8"><?php $lines=[];foreach($s['services'] as $key=>$names)$lines[]=$key.'|'.$names[0].'|'.$names[1];echo esc_textarea(implode("\n",$lines)); ?></textarea><p class="description">Eén dienst per regel: <code>code|Nederlandse naam|Engelse naam</code>. Bijvoorbeeld <code>consultation|Kennismaking|Introduction</code>. “Ik weet het nog niet” wordt automatisch toegevoegd.</p></td></tr>
</table><h2>Teksten per taal</h2><p>Gebruik eventueel <code>{contact_name}</code> voor de ingestelde contactnaam. De aanvraag is een voorkeur, geen bevestigde reservering. Inzendingen worden niet als berichten in de database opgeslagen. Antispambeveiliging blijft actief.</p>
<table class="form-table" role="presentation"><?php foreach(['title'=>'Formuliertitel','request_label'=>'Naam van aanvraagmodus','service_label'=>'Label dienstenkeuze','consent'=>'Toestemmingstekst','note'=>'Toelichting onder formulier','success'=>'Bevestigingstekst'] as $key=>$label): ?><tr><th scope="row"><?php echo esc_html($label); ?></th><td><?php foreach(['nl'=>'Nederlands','en'=>'English'] as $lang=>$name): $field=$key.'_'.$lang; ?><p><label for="hgcf-<?php echo esc_attr($field); ?>"><?php echo esc_html($name); ?></label><br><textarea id="hgcf-<?php echo esc_attr($field); ?>" name="hgcf_settings[<?php echo esc_attr($field); ?>]" class="large-text" rows="2" maxlength="1500"><?php echo esc_textarea($s[$field]); ?></textarea></p><?php endforeach; ?></td></tr><?php endforeach; ?></table>
<?php submit_button(); ?></form><p>Verzending gebruikt de bestaande e-mailvoorziening van deze website. Een succesvolle verzending betekent niet automatisch dat de e-mail is afgeleverd.</p></div>
<?php
}
+14
View File
@@ -0,0 +1,14 @@
=== HG Contactformulier ===
Requires at least: 6.5
Requires PHP: 8.0
Stable tag: 1.0.0
License: GPLv2 or later
Configureerbaar NL/EN-contactformulier met vraagmodus en optionele afspraakaanvragen.
== Installation ==
Upload en activeer de plugin. Stel Contactformulier in de beheerzijbalk in en plaats [hg_contactform] op een pagina.
== Changelog ==
= 1.0.0 =
Herbruikbare plugin met eigen instellingenpagina, standalone styling, NL/EN-teksten en compatibele legacy-shortcode.
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
"""Build a WordPress-installable ZIP from this checkout."""
from pathlib import Path
import zipfile
root=Path(__file__).resolve().parents[1]
destination=root/'dist/hg-contactform.zip'
destination.parent.mkdir(exist_ok=True)
files=[root/'hg-contactform.php',root/'readme.txt',root/'LICENSE']
for directory in ['assets','includes']:files.extend(sorted((root/directory).rglob('*')))
with zipfile.ZipFile(destination,'w',zipfile.ZIP_DEFLATED) as archive:
for path in files:
if path.is_file():archive.write(path,Path('hg-contactform')/path.relative_to(root))
print(destination)
+30
View File
@@ -0,0 +1,30 @@
<?php
// Run with wp eval-file tests/integration.php. No options, posts or email are written.
if(!defined('WP_CLI')||!WP_CLI)exit;
if(!function_exists('hgcf_validate'))WP_CLI::error('Activate HG Contactformulier first.');
function hgcf_assert($ok,$name){if(!$ok)WP_CLI::error($name);WP_CLI::log('PASS '.$name);}
$config=hgcf_defaults();$config['recipient']='recipient@example.com';$config['site_name']='Example practice';$config['enable_requests']=true;$config['services']=['consultation'=>['Kennismaking','Introduction']];$config['opening_time']='10:00';$config['closing_time']='18:00';
$override=function()use(&$config){return $config;};add_filter('pre_option_hgcf_settings',$override);
$question=['name'=>'Test Visitor','email'=>'visitor@example.com','message'=>'A useful question','mode'=>'question','consent'=>'1'];
hgcf_assert(!is_wp_error(hgcf_validate($question)),'generic question');
$request=array_replace($question,['mode'=>'request','message'=>'','massage'=>'consultation','preferred_time'=>'11:30','preferred_date'=>wp_date('Y-m-d',time()+DAY_IN_SECONDS)]);
hgcf_assert(!is_wp_error(hgcf_validate($request,'en')),'configured service with optional empty message');
foreach([['email'=>"attacker@example.com\r\nBcc: target@example.com"],['name'=>['array']],['consent'=>'0'],['message'=>'']] as $patch)hgcf_assert(is_wp_error(hgcf_validate(array_replace($question,$patch))),'reject '.array_key_first($patch));
foreach([['massage'=>'unknown'],['preferred_time'=>'09:30'],['preferred_time'=>'18:30'],['preferred_date'=>'2000-01-01'],['preferred_date'=>'2027-02-30']] as $patch)hgcf_assert(is_wp_error(hgcf_validate(array_replace($request,$patch))),'reject request '.array_key_first($patch));
$config['enable_requests']=false;hgcf_assert(is_wp_error(hgcf_validate($request)),'reject forged disabled request');
$html=hgcf_render(['lang'=>'en']);hgcf_assert(!str_contains($html,'class="request-fields"')&&!str_contains($html,'value="request"'),'disabled request hidden');
$config['show_phone']=false;$result=hgcf_validate(array_replace($question,['phone'=>'not a phone']));hgcf_assert(!is_wp_error($result)&&$result['phone']==='','hidden phone ignored');
$html=hgcf_render(['lang'=>'nl']);hgcf_assert(!str_contains($html,'name="mlhc_phone"'),'disabled phone hidden');
$config['enable_requests']=true;$config['contact_name']='Taylor';$config['title_en']='Ask {contact_name}';hgcf_assert(str_contains(hgcf_render(['lang'=>'en']),'Ask Taylor'),'contact name placeholder');
hgcf_assert(hgcf_language('[hg_contactform lang="en"]')==='en'&&hgcf_language('[mlh_contact lang="nl"]')==='nl','explicit language and legacy shortcode');
$messages=[];$mock=function($result,$atts)use(&$messages){$messages[]=$atts;return true;};add_filter('pre_wp_mail',$mock,PHP_INT_MAX,2);
hgcf_assert(hgcf_send(hgcf_validate($request),'en')===true,'mocked email');remove_filter('pre_wp_mail',$mock,PHP_INT_MAX);
hgcf_assert(count($messages)===1&&$messages[0]['to']==='recipient@example.com'&&str_contains($messages[0]['subject'],'Example practice')&&str_contains($messages[0]['message'],'Kennismaking'),'mail recipient, brand and service from config');
require_once ABSPATH.'wp-admin/includes/template.php';
$input=array_merge($config,['enable_requests'=>'1','show_phone'=>'1','services_text'=>'consultation|Kennismaking|Introduction']);
$clean=hgcf_sanitize_settings($input);hgcf_assert($clean['services']===['consultation'=>['Kennismaking','Introduction']],'services sanitization');
$bad=hgcf_sanitize_settings(array_replace($input,['recipient'=>'invalid','opening_time'=>'20:00','closing_time'=>'10:00','services_text'=>"duplicate|Een|One\nduplicate|Twee|Two"]));hgcf_assert($bad['recipient']===$config['recipient']&&$bad['opening_time']===$config['opening_time']&&$bad['services']===$config['services'],'bad settings retain previous valid values');
$clean=hgcf_sanitize_settings(array_replace($input,['title_nl'=>'<script>alert(1)</script>Hallo']));hgcf_assert(!str_contains($clean['title_nl'],'<script>'),'settings strip HTML');
require_once ABSPATH.'wp-admin/includes/plugin.php';$admin=get_users(['role'=>'administrator','number'=>1]);if($admin){wp_set_current_user($admin[0]->ID);do_action('admin_menu');global $menu;hgcf_assert((bool)array_filter($menu,fn($item)=>($item[2]??'')==='hg-contactform'&&($item[1]??'')==='manage_options'),'sidebar menu restricted to administrators');ob_start();hgcf_admin_page();$html=ob_get_clean();hgcf_assert(str_contains($html,'options.php')&&str_contains($html,'hgcf_settings[services_text]'),'settings page renders native form');}
remove_filter('pre_option_hgcf_settings',$override);
WP_CLI::success('Reusable form, settings, admin menu and mail handling verified; no message sent.');