Compare commits

...
13 Commits
Author SHA1 Message Date
parkel 7713955795 Add configurable free euro amounts and multiline appointment preferences 2026-11-18 16:28:35 +01:00
parkel 93520382bb Clarify installation and maintenance for public readers 2026-11-18 15:51:55 +01:00
parkel 22f58839ec Pin shared HG code to the independent repository history 2026-11-18 15:31:32 +01:00
parkel d72ccf8ea6 Build the standalone plugin with pinned HG shared files 2026-11-18 15:21:05 +01:00
parkel 50a4dd2ad6 updater options 2026-11-18 01:46:55 +01:00
parkel 54042efb44 Support safe workflow links and configurable mail field labels 2026-11-18 00:11:27 +01:00
parkel 548f04a5dc Add configurable daypart preferences and order neutral choice last 2026-11-17 23:42:08 +01:00
parkel e1df255b0b Make consent checkbox and form note configurable
Add independent admin controls for the consent checkbox and explanatory note. Keep both enabled by default so existing installations retain their current behavior.

Render the optional elements conditionally and require consent in server validation only when the checkbox is enabled. Bump the plugin and stable release version to 1.3.4, document the controls, and cover enabled/disabled rendering, validation, and invalid settings in the integration suite.

Validation: PHP syntax and NL/EN integration checks passed on Hephaestus, with mail intercepted during tests. Staged whitespace checks passed. No changes to antispam behavior or other website configurations.
2026-11-09 23:41:55 +01:00
parkel 0cad18c757 Group HG plugins under a shared branded admin menu 2026-10-13 00:44:12 +02:00
parkel 9e9133c93e Use effective WordPress locale for contact form language 2026-10-12 23:42:55 +02:00
parkel b9e7d0fdce Move technical details into plugin information tab 2026-10-12 14:15:23 +02:00
parkel 2a2f1d5878 Add optional self-hosted ALTCHA protection and dependency maintenance 2026-10-12 14:10:08 +02:00
parkel 3b558409f3 Redesign settings with configurable workflows and detected languages 2026-10-12 13:38:59 +02:00
73 changed files with 3654 additions and 202 deletions

No files matched your search

+56 -15
View File
@@ -1,44 +1,85 @@
# HG Contactformulier # HG Contactformulier
Herbruikbaar NL/EN-contactformulier voor WordPress. Ontwikkeling gebeurt in deze Git-repository; klantinstellingen staan uitsluitend in de eigen WordPress-database. Voeg een contactformulier met configureerbare workflows en meertalige teksten toe aan WordPress. Inzendingen gaan per e-mail naar het ingestelde adres.
## Installatie en gebruik ## Installatie en gebruik
1. Maak het installatiebestand met `python3 scripts/build.py`. Vereist WordPress 6.5 of hoger en PHP 8.1 of hoger.
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. 1. Kies een Contactformulier-ZIP uit de [HG WordPress Plugins-releases](https://code.hosting.hippogrief.nl/hippogrief/wp-plugins/releases) of bouw `dist/hg-contactform.zip` met `python3 scripts/build.py`.
2. Upload de ZIP via **Plugins → Nieuwe plugin → Plugin uploaden** en activeer HG Contactformulier.
3. Open **HG Plugins → Contactformulier** 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. 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. Met Polylang volgt het formulier de taal van de pagina. Zonder Polylang volgt het de WordPress-sitetaal. `[mlh_contact]` blijft beschikbaar als compatibiliteitsalias. Gebruik één formulier per pagina en plaats de shortcode rechtstreeks in de pagina-inhoud.
## Instellingen ## Instellingen
Het beheer bestaat uit **Algemeen**, **Workflows**, **Teksten** en **Over deze plugin**. Het laatste tabblad toont de gebruikte techniek, de actuele versies en informatie over onderhoud.
- Ontvangstadres en naam voor het e-mailonderwerp. - Ontvangstadres en naam voor het e-mailonderwerp.
- Optioneel afzenderadres en afzendernaam voor uitsluitend formuliermails. Een leeg adres behoudt de bestaande standaardafzender. Reply-To is altijd het bezoekersadres. Kies een adres op een domein waarvoor de mailserver via SPF/DKIM mag versturen. Het technische envelope/Return-Path-adres wordt niet door deze instelling aangepast; een mailserver of SMTP-plugin kan de uiteindelijke afzender overschrijven. - Optioneel afzenderadres en afzendernaam voor uitsluitend formuliermails. Een leeg adres behoudt de bestaande standaardafzender. Reply-To is altijd het bezoekersadres. Kies een adres op een domein waarvoor de mailserver via SPF/DKIM mag versturen. Het technische envelope/Return-Path-adres wordt niet door deze instelling aangepast; een mailserver of SMTP-plugin kan de uiteindelijke afzender overschrijven.
- Contactnaam, beschikbaar als `{contact_name}` in de configureerbare teksten. - Contactnaam, beschikbaar als `{contact_name}` in de configureerbare teksten.
- Vraagmodus en optionele afspraakaanvragen, optioneel telefoonveld. - Toestemmingsvinkje en toelichting afzonderlijk aan- of uitzetten onder Algemeen → Formulierweergave. Bij uitgeschakeld vinkje vraagt ook de server geen toestemmingveld. Beide opties staan standaard aan; bestaande websites behouden hun huidige gedrag.
- Vroegste en laatste voorkeurtijd; dit controleert een tijdvoorkeur, geen beschikbaarheid. - Eén tot twintig workflows met eigen naam, onderwerp en eventueel een afwijkend ontvangstadres. Workflows kunnen worden uitgeschakeld of verwijderd; minstens één blijft actief.
- Diensten per regel als `code|Nederlandse naam|Engelse naam`; maximaal 50 unieke codes. `unsure` wordt automatisch toegevoegd. - Per workflow: telefoon, dienst, datum en tijd verbergen, optioneel maken of verplicht stellen. Ook het bericht kan verplicht of optioneel zijn.
- NL/EN-formuliertitel, aanvraaglabel, dienstenlabel, toestemming, toelichting en bevestigingstekst. - Het dienstenveld kan een keuzelijst of een vrij eurobedrag zijn. Vrije bedragen accepteren een punt of komma en maximaal twee decimalen; bedragen moeten positief zijn. Bestaande workflows behouden hun keuzelijst.
- De tijdvoorkeur kan ook vrije tekst zijn voor bijvoorbeeld twee of drie voorkeursmomenten. Regelafbrekingen blijven in de e-mail behouden; er is geen kalender- of beschikbaarheidscontrole op deze vrije tekst. Stel de datum op “Niet tonen” als je alleen dit tekstveld wilt gebruiken.
- Per workflow een exact tijdstip of dagdeel (ochtend, middag, avond), met een vroegste en laatste voorkeurtijd. Alleen dagdelen die overlappen met dit bereik worden aangeboden. Dit controleert een tijdvoorkeur, geen beschikbaarheid. Bestaande workflows behouden standaard de exacte tijdkeuze.
- Diensten toevoegen en verwijderen via losse invoerrijen, met maximaal 50 unieke keuzes per workflow. Bij een optionele dienst verschijnt ook “Ik weet het nog niet”.
- Algemene formulierteksten en eigen workflowteksten per actieve taal. Met Polylang verschijnen de ingestelde talen; zonder Polylang uitsluitend de WordPress-sitetaal. Andere taalplugins worden niet automatisch gedetecteerd.
Bestaande vraag- en aanvraaginstellingen worden automatisch naar workflows vertaald. Ontvangers, afzenderinstellingen, diensten en teksten blijven behouden. De nieuwe structuur wordt bij het opslaan vastgelegd. Een nieuwe installatie begint met één vraagworkflow.
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. 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.
## Antispam
Onder **Algemeen → Antispam** kun je ALTCHA met één vinkje inschakelen. Nieuwe installaties beginnen met de bestaande basisbescherming; ALTCHA is optioneel. Er zijn geen API-sleutels, accounts, betaalde abonnementen of wijzigingen aan de hosting nodig. PHP 8.1+ en een moderne browser met JavaScript en HTTPS (Web Crypto) zijn vereist. De lokale widget volgt de formuliertaal. Zonder JavaScript toont het formulier een verwijzing naar andere contactmogelijkheden en wordt verzending met ingeschakelde ALTCHA geweigerd.
De plugin bundelt ALTCHA-widget 3.3.0 en PHP-library 2.3.0 (MIT), inclusief licenties en een privé-namespace voor de PHP-library om conflicten met andere plugins te vermijden. Alle runtime-assets en controles blijven op de eigen website. De standaard PBKDF2-uitdaging verloopt na twintig minuten en is gebonden aan de formulierpagina. Geldige oplossingen worden vóór verzending atomair als gebruikt vastgelegd; hergebruik wordt geweigerd. Alleen een hash en vervaltijd worden opgeslagen, geen formuliergegevens. WordPress Cron ruimt verlopen records periodiek op zolang de plugin actief is. Het challenge-endpoint levert niet-cachebare antwoorden en begrenst aanvragen per gehashte IP-identificatie tot dertig per vijf minuten. De bestaande honeypot, tijdcontrole en verzendlimiet blijven actief. Dit is een extra drempel voor bots, geen garantie dat een bezoeker een mens is.
## ALTCHA bijwerken
Versies, officiële downloadbronnen en hashes staan in `includes/vendor/altcha/versions.json`. Er zijn geen automatische dependency-updates op websites. Controleer bij pluginonderhoud en bij beveiligingsmeldingen of een nieuwe upstreamversie beschikbaar is:
```sh
python3 scripts/update_altcha.py --check
```
Lees de upstream changelogs, kies expliciete versies en werk de lokale bestanden bij:
```sh
python3 scripts/update_altcha.py --widget-version 3.3.0 --php-version 2.3.0
```
Het script controleert de npm-integriteit, bewaart licenties en legt hashes vast. Voor het PHP-archief legt het de SHA-256-hash van de officiële GitHub-download vast. Daarmee kun je de inhoud later met die download vergelijken. De PHP-namespace wordt bij het bundelen geïsoleerd. Controleer de diff en draai de tests voordat je een nieuwe plug-inversie en ZIP maakt.
## Direct naar een workflow
Een link naar de formulierpagina kan `?hgcf_workflow=code#contact-form` gebruiken om een actieve workflow vooraf te kiezen. De code is de bestaande interne workflow-ID. Alleen actieve, bestaande codes worden geaccepteerd; onbekende, uitgeschakelde of ongeldige waarden gebruiken de standaardworkflow. Na een validatiefout heeft de ingestuurde keuze voorrang. Dit wijzigt uitsluitend de aanvankelijke selectie; alle servercontroles blijven actief.
## Gedrag en beheer ## 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. 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. Een bezoeker kan een datum en tijd als voorkeur opgeven. De organisator bevestigt een afspraak apart.
## Verificatie ## Verificatie
`node --check assets/contact.js` controleert de JavaScript-syntax. Voer de integratiechecks uit in een WordPress-installatie met de plugin actief: `node --check assets/contact.js` en `node --check assets/admin.js` controleren de JavaScript-syntax. `php tests/language-without-plugin.php` controleert de taalkeuze zonder taalplugin. Voer de integratiechecks uit in een WordPress-installatie met de plugin actief:
```sh ```sh
wp eval-file /pad/naar/hg_contactform/tests/integration.php wp --path=/pad/naar/wordpress eval-file "$PWD/tests/integration.php"
wp --path=/pad/naar/wordpress eval-file "$PWD/tests/antispam.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. De checks injecteren tijdelijke instellingen via filters en onderscheppen e-mail. De ALTCHA-checks gebruiken en verwijderen eigen tijdelijke replay- en limietrecords; er worden geen formulierinzendingen of permanente testinstellingen opgeslagen. De testsite moet een gepubliceerde pagina met het formulier bevatten. `tests/browser.cjs` controleert de echte widget, taal, workflowkeuze en POST-validatie met Playwright; geldige verzendingen worden in de browser onderschept voordat ze de server bereiken. PHP-syntax kan met `php -l` worden gecontroleerd. Test echte mailaflevering apart met een expliciet afgesproken testadres.
## Uitrollen ## Updaten
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. Controleer updates via **HG Plugins → Updates**. Bewaar voor een update de vorige ZIP en een back-up van de site. Gebruik voor `[mlh_contact]` één actieve plug-in die deze shortcode registreert. [Openbare releases](https://code.hosting.hippogrief.nl/hippogrief/wp-plugins/releases)
## Gedeeld HG-beheer
De installatie-ZIP bevat het HG-beheermenu en de updater. De build controleert de vastgelegde bestanden in `shared.lock.json`. [Gedeelde code](https://code.hosting.hippogrief.nl/hippogrief/wp-plugins)
+3
View File
@@ -0,0 +1,3 @@
.hgcf-admin{max-width:1160px}.hgcf-admin-header,.hgcf-panel-heading{display:flex;justify-content:space-between;align-items:center;gap:20px;margin:24px 0}.hgcf-admin-header h1{font-size:25px}.hgcf-admin-header p,.hgcf-panel-heading p{margin:8px 0;color:#50575e}.hgcf-language-status{background:#e8eef4;border:1px solid #d3dee9;padding:8px 13px;border-radius:20px;white-space:nowrap}.hgcf-admin-tabs{display:flex;flex-wrap:wrap;gap:5px;border-bottom:1px solid #c3c4c7;margin-bottom:24px}.hgcf-admin-tabs a{color:#50575e;text-decoration:none;padding:14px 22px;font-size:15px;font-weight:600;border-bottom:3px solid transparent}.hgcf-admin-tabs a.is-active{color:#135e96;border-color:#2271b1}.hgcf-admin-tabs span{background:#e2e4e7;border-radius:15px;padding:2px 7px;margin-left:6px}.hgcf-admin-panel[hidden]{display:none}.hgcf-admin-card,.hgcf-workflow{background:#fff;border:1px solid #dcdcde;border-radius:8px;margin:0 0 20px}.hgcf-admin-card{padding:24px 28px}.hgcf-admin-card h2{margin-top:0}.hgcf-admin-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px 26px}.hgcf-admin-field{display:flex;flex-direction:column;gap:7px;margin:14px 0}.hgcf-admin-field>span,.hgcf-field-matrix label>span{font-weight:600;color:#1d2327}.hgcf-admin-field input,.hgcf-admin-field textarea{width:100%;max-width:none;min-height:38px}.hgcf-admin-field small{font-weight:400;color:#646970;line-height:1.6}.hgcf-admin-note{padding:15px 18px;background:#f0f6fc;border-left:3px solid #72aee6;margin-top:24px}.hgcf-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}.hgcf-workflow>summary::before{content:'›';font-size:24px;margin-right:5px}.hgcf-workflow[open]>summary::before{transform:rotate(90deg)}.hgcf-workflow-name{flex:1}.hgcf-workflow-badge{font-size:12px;background:#edf6ef;color:#245c31;padding:4px 9px;border-radius:15px}.hgcf-workflow-body{padding:0 24px 24px;border-top:1px solid #e8e8ea}.hgcf-workflow-toolbar{display:flex;justify-content:space-between;gap:20px;padding:20px 0}.hgcf-field-matrix{display:grid;grid-template-columns:repeat(4,1fr);gap:16px}.hgcf-field-matrix label{display:flex;flex-direction:column;gap:8px}.hgcf-field-matrix select{max-width:none;width:100%;min-height:36px}.hgcf-checkbox{display:block;margin-top:20px}.hgcf-flow-services,.hgcf-flow-times{border-top:1px solid #e8e8ea;margin-top:24px;padding-top:6px}.hgcf-service-row{display:flex;align-items:center;gap:16px}.hgcf-service-row .hgcf-admin-field{flex:1;min-width:0}.hgcf-service-row button{white-space:nowrap;margin-top:18px}.hgcf-workflow-texts{margin-top:24px;border-top:1px solid #e8e8ea;padding-top:18px}.hgcf-workflow-texts summary{cursor:pointer;font-weight:600}.hgcf-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}.hgcf-save-bar span{color:#646970}.hgcf-admin [hidden]{display:none!important}@media(max-width:782px){.hgcf-admin-header,.hgcf-panel-heading{align-items:flex-start;flex-direction:column}.hgcf-admin-grid{grid-template-columns:1fr}.hgcf-field-matrix{grid-template-columns:1fr 1fr}.hgcf-admin-card{padding:20px}.hgcf-service-row{flex-wrap:wrap}.hgcf-admin-tabs a{padding:12px}.hgcf-save-bar{flex-wrap:wrap}.hgcf-language-status{white-space:normal}}
.hgcf-tech-table{overflow-x:auto}.hgcf-tech-table th,.hgcf-tech-table td{padding:12px 14px}.hgcf-tech-table td:first-child{font-weight:600}
+18
View File
@@ -0,0 +1,18 @@
(() => {
const app=document.querySelector('.hgcf-admin');if(!app)return;
const panels=[...app.querySelectorAll('.hgcf-admin-panel')];const tabs=[...app.querySelectorAll('.hgcf-admin-tabs a')];
function selectTab(id){if(!panels.some(p=>p.id===id))id='hgcf-general';panels.forEach(p=>p.hidden=p.id!==id);const saveBar=app.querySelector('.hgcf-save-bar');if(saveBar)saveBar.hidden=id==='hgcf-info';tabs.forEach(t=>{const active=t.hash==='#'+id;t.classList.toggle('is-active',active);if(active)t.setAttribute('aria-current','page');else t.removeAttribute('aria-current');});}
tabs.forEach(tab=>tab.addEventListener('click',()=>selectTab(tab.hash.slice(1))));selectTab(location.hash.slice(1));window.addEventListener('hashchange',()=>selectTab(location.hash.slice(1)));
let sequence=0;const unique=prefix=>prefix+Date.now().toString(36)+(++sequence).toString(36);
function initCard(card){
const update=()=>{const state=key=>card.querySelector(`[data-hgcf-state="${key}"]`).value;card.querySelector('.hgcf-flow-services').hidden=state('service')==='hidden';card.querySelector('.hgcf-flow-times').hidden=state('time')==='hidden';card.querySelector('.hgcf-flow-time-range').hidden=card.querySelector('[data-hgcf-time-kind]').value==='text';card.querySelector('.hgcf-service-choices').hidden=card.querySelector('[data-hgcf-service-kind]').value==='amount';const enabled=card.querySelector('.hgcf-workflow-enabled').checked;card.querySelector('.hgcf-workflow-badge').textContent=enabled?'Actief':'Uitgeschakeld';};
card.querySelectorAll('[data-hgcf-state],[data-hgcf-time-kind],[data-hgcf-service-kind],.hgcf-workflow-enabled').forEach(input=>input.addEventListener('change',update));
const name=card.querySelector('input[name*="[label]"]');name.addEventListener('input',()=>card.querySelector('.hgcf-workflow-name').textContent=name.value||'Workflow');
card.querySelector('.hgcf-remove-workflow').addEventListener('click',()=>{if(confirm('Deze workflow verwijderen? De wijziging wordt pas actief na opslaan.'))card.remove();});
const initRow=row=>row.querySelector('.hgcf-remove-service').addEventListener('click',()=>row.remove());card.querySelectorAll('.hgcf-service-row').forEach(initRow);
card.querySelector('.hgcf-add-service').addEventListener('click',()=>{const list=card.querySelector('.hgcf-service-list');if(list.children.length>=50){alert('Maximaal 50 keuzemogelijkheden per workflow.');return;}const index=Number(card.dataset.nextService);card.dataset.nextService=index+1;const template=card.querySelector('.hgcf-service-template');const wrapper=document.createElement('div');wrapper.innerHTML=template.innerHTML.replaceAll('__SERVICE__',String(index)).replaceAll('__SERVICE_ID__',unique('service_'));const row=wrapper.firstElementChild;list.append(row);initRow(row);row.querySelector('input:not([type="hidden"])').focus();});
update();
}
const list=document.getElementById('hgcf-workflow-list');list.querySelectorAll('.hgcf-workflow').forEach(initCard);
document.getElementById('hgcf-add-workflow').addEventListener('click',()=>{if(list.children.length>=20){alert('Maximaal 20 workflows.');return;}const index=Number(list.dataset.nextIndex);list.dataset.nextIndex=index+1;const wrapper=document.createElement('div');wrapper.innerHTML=document.getElementById('hgcf-workflow-template').innerHTML.replaceAll('__INDEX__',String(index)).replaceAll('__WORKFLOW_ID__',unique('workflow_'));const card=wrapper.firstElementChild;list.append(card);initCard(card);card.querySelector('input[name*="[label]"]').focus();});
})();
+4
View File
@@ -2,3 +2,7 @@
.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} .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}} @media(max-width:540px){.hgcf-contact .form-fields{grid-template-columns:1fr;gap:0}.hgcf-contact{padding:20px}}
.hgcf-antispam{margin:18px 0 22px;max-width:100%}.hgcf-antispam altcha-widget{display:block;--altcha-color-primary:var(--rose);--altcha-border-color:var(--line);--altcha-color-base-content:var(--ink);--altcha-border-radius:6px;--altcha-max-width:100%}
.hgcf-contact .form-fields.hgcf-single-field{grid-template-columns:1fr}
+19 -10
View File
@@ -1,18 +1,27 @@
(() => { (() => {
const labels=window.hgcfLabels||{}; document.querySelectorAll('.mlhc-form[data-hgcf-workflows]').forEach(form=>{
document.querySelectorAll('.mlhc-form').forEach(form=>{ const workflows=JSON.parse(form.dataset.hgcfWorkflows);
const requestFields=form.querySelector('.request-fields');
const message=form.querySelector('[name="mlhc_message"]'); const message=form.querySelector('[name="mlhc_message"]');
form.querySelectorAll('[data-hgcf-label]').forEach(label=>label.dataset.base=label.textContent);
function update(){ function update(){
const request=form.querySelector('[name="mlhc_mode"]:checked').value==='request'; const mode=form.querySelector('[name="mlhc_mode"]:checked')||form.querySelector('[name="mlhc_mode"]');const flow=workflows[mode.value];if(!flow)return;
if(requestFields)requestFields.hidden=!request; const service=form.querySelector('select[name="mlhc_massage"]');if(service){const value=service.value;service.replaceChildren(...flow.services.map(item=>{const option=document.createElement('option');option.value=item.value;option.textContent=item.label;return option;}));service.value=flow.services.some(item=>item.value===value)?value:'unsure';}
if(requestFields)requestFields.disabled=!request; form.querySelectorAll('[data-hgcf-field]').forEach(wrapper=>{
message.required=!request; const field=wrapper.dataset.hgcfField;const state=flow.fields[field];wrapper.hidden=state==='hidden';
if(request) message.removeAttribute('minlength'); else message.minLength=5; const label=wrapper.querySelector('[data-hgcf-label]');label.textContent=(field==='service'?flow.serviceLabel:field==='time'?flow.timeLabel:label.dataset.base)+(state==='required'?' *':'');
form.querySelector('.message-label').textContent=request?labels.request:labels.question; if(field==='time'){
const select=wrapper.querySelector('select');const value=select.value;const choices=[{value:'',label:flow.noTimePreference},...Object.entries(flow.dayparts).map(([value,label])=>({value,label}))];
select.replaceChildren(...choices.map(item=>{const option=document.createElement('option');option.value=item.value;option.textContent=item.label;return option;}));select.value=choices.some(item=>item.value===value)?value:'';
wrapper.querySelectorAll('[data-hgcf-time-mode]').forEach(control=>{const active=control.dataset.hgcfTimeMode===flow.timeMode;control.hidden=!active;control.disabled=state==='hidden'||!active;control.required=state==='required'&&active;if(control.type==='time'){control.min=flow.start;control.max=flow.end;}if(active)wrapper.htmlFor=control.id;});
}else if(field==='service'){wrapper.querySelectorAll('[data-hgcf-service-mode]').forEach(control=>{const active=control.dataset.hgcfServiceMode===flow.serviceMode;control.hidden=!active;control.disabled=state==='hidden'||!active;control.required=state==='required'&&active;if(active)wrapper.htmlFor=control.id;});}else{const control=wrapper.querySelector('input,select');control.disabled=state==='hidden';control.required=state==='required';}
});
const dateGrid=form.querySelector('[data-hgcf-datetime-grid]');if(dateGrid)dateGrid.classList.toggle('hgcf-single-field',['date','time'].filter(field=>flow.fields[field]!=='hidden').length<2);
const fieldset=form.querySelector('.request-fields');if(fieldset)fieldset.hidden=['service','date','time'].every(field=>flow.fields[field]==='hidden');
message.required=flow.messageRequired;if(flow.messageRequired)message.minLength=5;else message.removeAttribute('minlength');form.querySelector('.message-label').textContent=flow.messageLabel+(flow.messageRequired?' *':'');
const hint=form.querySelector('.workflow-hint');hint.textContent=flow.hint;hint.hidden=!flow.hint;
} }
form.querySelectorAll('[name="mlhc_mode"]').forEach(input=>input.addEventListener('change',update));update(); 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;}); form.addEventListener('submit',event=>{const widget=form.querySelector('altcha-widget');if(widget&&!form.querySelector('input[name="mlhc_altcha"]')?.value){event.preventDefault();widget.focus();return;}if(event.defaultPrevented)return;const button=form.querySelector('[type="submit"]');button.disabled=true;button.textContent=form.dataset.hgcfSending;});
}); });
const errors=document.querySelector('.form-errors');if(errors)errors.focus(); const errors=document.querySelector('.form-errors');if(errors)errors.focus();
})(); })();
+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}}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023-2026 Daniel Regeci, BAU Software s.r.o.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+1
View File
@@ -0,0 +1 @@
const e=!1;var t=Array.isArray,n=Array.prototype.indexOf,a=Array.prototype.includes,r=Array.from,i=Object.keys,o=Object.defineProperty,l=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyDescriptors,c=Object.prototype,d=Array.prototype,u=Object.getPrototypeOf,f=Object.isExtensible;const h=()=>{};function g(){var e,t;return{promise:new Promise((n,a)=>{e=n,t=a}),resolve:e,reject:t}}const v=1<<24,p=16,b=32,m=64,y=512,k=1024,w=2048,A=4096,x=8192,C=16384,_=32768,$=1<<25,L=65536,S=1<<17,T=1<<19,j=65536,E=1<<21,P=1<<23,z=Symbol("$state"),I=Symbol("component"),V=Symbol("legacy props"),R=Symbol(""),H=Symbol("attributes"),O=Symbol("class"),F=Symbol("style"),M=Symbol("text"),N=Symbol("form reset"),q=new class extends Error{name="StaleReactionError";message="The reaction that called `getAbortSignal()` was re-run or destroyed"},U=!!globalThis.document?.contentType&&globalThis.document.contentType.includes("xml");function D(e){return e===this.v}function B(e,t){return e!=e?t==t:e!==t||null!==e&&"object"==typeof e||"function"==typeof e}function K(e){return!B(e,this.v)}const G={},W=Symbol("uninitialized"),Y="http://www.w3.org/1999/xhtml";let Z=null;function J(e){Z=e}function X(e,t=!1,n){Z={p:Z,i:!1,c:null,e:null,s:e,x:null,r:qt,l:null}}function Q(e){var t=Z,n=t.e;if(null!==n)for(var a of(t.e=null,n))mn(a);return void 0!==e&&(t.x=e),t.i=!0,Z=t.p,ee(e)}function ee(e={}){return o(e,I,{value:!0}),e}let te=[];function ne(){var e=te;te=[],function(e){for(var t=0;t<e.length;t++)e[t]()}(e)}function ae(e){if(0===te.length&&!ut){var t=te;queueMicrotask(()=>{t===te&&ne()})}te.push(e)}function re(){for(;te.length>0;)ne()}function ie(e){console.warn("https://svelte.dev/e/hydration_mismatch")}let oe,le=!1;function se(e){le=e}function ce(e){if(null===e)throw ie(),G;return oe=e}function de(){return ce($e(oe))}function ue(e){if(le){if(null!==$e(oe))throw ie(),G;oe=e}}function fe(e=1){if(le){for(var t=e,n=oe;t--;)n=$e(n);oe=n}}function he(e=!0){for(var t=0,n=oe;;){if(8===n.nodeType){var a=n.data;if("]"===a){if(0===t)return n;t-=1}else("["===a||"[!"===a||"["===a[0]&&!isNaN(Number(a.slice(1))))&&(t+=1)}var r=$e(n);e&&n.remove(),n=r}}function ge(e){if(!e||8!==e.nodeType)throw ie(),G;return e.data}function ve(e){if("object"!=typeof e||null===e||z in e||I in e)return e;const n=u(e);if(n!==c&&n!==d)return e;var a=new Map,r=t(e),i=jt(0),o=Jt,s=e=>{if(Jt===o)return e();var t=Ft,n=Jt;Nt(null),Xt(o);var a=e();return Nt(t),Xt(n),a};return r&&a.set("length",jt(e.length)),new Proxy(e,{defineProperty(e,t,n){"value"in n&&!1!==n.configurable&&!1!==n.enumerable&&!1!==n.writable||function(){throw new Error("https://svelte.dev/e/state_descriptors_fixed")}();var r=a.get(t);return void 0===r?s(()=>{var e=jt(n.value);return a.set(t,e),e}):Pt(r,n.value,!0),!0},deleteProperty(e,t){var n=a.get(t);if(void 0===n){if(t in e){const e=s(()=>jt(W));a.set(t,e),It(i)}}else Pt(n,W),It(i);return!0},get(t,n,r){if(n===z)return e;var i=a.get(n),o=n in t;if(void 0!==i||o&&!l(t,n)?.writable||(i=s(()=>jt(ve(o?t[n]:W))),a.set(n,i)),void 0!==i){var c=cn(i);return c===W?void 0:c}return Reflect.get(t,n,r)},getOwnPropertyDescriptor(e,t){var n=Reflect.getOwnPropertyDescriptor(e,t);if(n&&"value"in n){var r=a.get(t);r&&(n.value=cn(r))}else if(void 0===n){var i=a.get(t),o=i?.v;if(void 0!==i&&o!==W)return{enumerable:!0,configurable:!0,value:o,writable:!0}}return n},has(e,t){if(t===z)return!0;var n=a.get(t),r=void 0!==n&&n.v!==W||Reflect.has(e,t);if((void 0!==n||null!==qt&&(!r||l(e,t)?.writable))&&(void 0===n&&(n=s(()=>jt(r?ve(e[t]):W)),a.set(t,n)),cn(n)===W))return!1;return r},set(e,t,n,o){var c=a.get(t),d=t in e;if(r&&"length"===t)for(var u=n;u<c.v;u+=1){var f=a.get(u+"");void 0!==f?Pt(f,W):u in e&&(f=s(()=>jt(W)),a.set(u+"",f))}void 0===c?d&&!l(e,t)?.writable||(Pt(c=s(()=>jt(void 0)),ve(n)),a.set(t,c)):(d=c.v!==W,Pt(c,s(()=>ve(n))));var h=Reflect.getOwnPropertyDescriptor(e,t);if(h?.set&&h.set.call(o,n),!d){if(r&&"string"==typeof t){var g=a.get("length"),v=Number(t);Number.isInteger(v)&&v>=g.v&&Pt(g,v+1)}It(i)}return!0},ownKeys(e){cn(i);var t=Reflect.ownKeys(e).filter(e=>{var t=a.get(e);return void 0===t||t.v!==W});for(var[n,r]of a)r.v===W||n in e||t.push(n);return t},setPrototypeOf(){!function(){throw new Error("https://svelte.dev/e/state_prototype_fixed")}()}})}function pe(e){try{if(null!==e&&"object"==typeof e&&z in e)return e[z]}catch{}return e}function be(e,t){return Object.is(pe(e),pe(t))}var me,ye,ke,we,Ae;function xe(){if(void 0===me){me=window,ye=document,ke=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,n=Text.prototype;we=l(t,"firstChild").get,Ae=l(t,"nextSibling").get,f(e)&&(e[O]=void 0,e[H]=null,e[F]=void 0,e.__e=void 0),f(n)&&(n[M]=void 0)}}function Ce(e=""){return document.createTextNode(e)}function _e(e){return we.call(e)}function $e(e){return Ae.call(e)}function Le(e,t){if(!le)return _e(e);var n=_e(oe);if(null===n)n=oe.appendChild(Ce());else if(t&&3!==n.nodeType){var a=Ce();return n?.before(a),ce(a),a}return t&&Pe(n),ce(n),n}function Se(eLine truncated
+14 -80
View File
@@ -1,59 +1,23 @@
<?php <?php
/** /**
* Plugin Name: HG Contactformulier * Plugin Name: HG Contactformulier
* Description: Tweetalig contactformulier voor vragen en massageaanvragen, zonder inzendingen in WordPress op te slaan. * Description: Configureerbaar contactformulier met workflows en talen vanuit de website, zonder inzendingen op te slaan.
* Version: 1.1.0 * Version: 1.5.0
* Update URI: https://code.hosting.hippogrief.nl/hippogrief/wp-plugins/src/branch/main/hg_contactform
* Requires at least: 6.5 * Requires at least: 6.5
* Requires PHP: 8.0 * Requires PHP: 8.1
* Text Domain: hg-contactform * Text Domain: hg-contactform
*/ */
if (!defined('ABSPATH')) { exit; } if (!defined('ABSPATH')) { exit; }
require_once __DIR__ . '/includes/hg-plugin-updates.php';
define('HGCF_VERSION','1.5.0');
define('HGCF_FILE',__FILE__);
require_once __DIR__.'/includes/hg-admin-menu.php';
require_once __DIR__.'/includes/settings.php'; require_once __DIR__.'/includes/settings.php';
require_once __DIR__.'/includes/language.php'; require_once __DIR__.'/includes/language.php';
function hgcf_text($nl,$en,$lang) { return $lang==='en'?$en:$nl; } require_once __DIR__.'/includes/form.php';
function hgcf_types() { return hgcf_setting('services')+['unsure'=>['Ik weet het nog niet','Not sure yet']]; } require_once __DIR__.'/includes/antispam.php';
function hgcf_validate(array $source, $lang='nl') { function hgcf_handle_submission() {
$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'];
$headers=['Content-Type: text/plain; charset=UTF-8','Reply-To: '.$data['email']];
$sender_email=hgcf_setting('sender_email');$sender_name=hgcf_setting('sender_name');
if($sender_email!=='') {
if(!is_string($sender_email)||!is_email($sender_email)||preg_match('/[\r\n]/',$sender_email)||!is_string($sender_name)||strlen($sender_name)>150||preg_match('/[\r\n]/',$sender_name)) return false;
$name=sanitize_text_field($sender_name?:hgcf_setting('site_name'));
$quoted='"'.str_replace(['\\','"'],['\\\\','\\"'],$name).'"';
$headers[]='From: '.$quoted.' <'.$sender_email.'>';
}
return wp_mail(hgcf_setting('recipient'),sanitize_text_field(hgcf_setting('site_name')).': '.($request?'afspraakaanvraag':'vraag'),$body,$headers);
}
add_action('template_redirect', function () {
if(($_SERVER['REQUEST_METHOD']??'')!=='POST' || ($_POST['mlhc_action']??'')!=='send') return; if(($_SERVER['REQUEST_METHOD']??'')!=='POST' || ($_POST['mlhc_action']??'')!=='send') return;
$id=get_queried_object_id(); $post=get_post($id); $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]); 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]);
@@ -70,45 +34,15 @@ add_action('template_redirect', function () {
$rate_key='mlhc_rate_'.hash_hmac('sha256',$ip,wp_salt('auth')); $rate_key='mlhc_rate_'.hash_hmac('sha256',$ip,wp_salt('auth'));
$rate=get_transient($rate_key); $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; } 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; }
if(hgcf_altcha_enabled()&&!hgcf_verify_altcha(wp_unslash($_POST['mlhc_altcha']??''),$id)) { $GLOBALS['mlhc_errors']=new WP_Error('altcha',hgcf_text('De antispamcontrole is niet gelukt of verlopen. Probeer de controle opnieuw.','The spam protection check failed or expired. Please verify again.',$lang)); return; }
$rate=$rate?:['count'=>0,'last'=>0]; $rate['count']++;$rate['last']=time();set_transient($rate_key,$rate,15*MINUTE_IN_SECONDS); $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; } 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)); $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; 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.1.0');
wp_enqueue_script('hgcf',plugins_url('assets/contact.js',__FILE__),[], '1.1.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_action('template_redirect','hgcf_handle_submission');
add_shortcode('hg_contactform','hgcf_render'); add_shortcode('hg_contactform','hgcf_render');
add_shortcode('mlh_contact','hgcf_render'); add_shortcode('mlh_contact','hgcf_render');
add_action('wp_enqueue_scripts',function(){ 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.1.0'); $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__),[],HGCF_VERSION);
}); });
+75
View File
@@ -0,0 +1,75 @@
<?php
if(!defined('ABSPATH'))exit;
function hgcf_admin_input($label,$name,$value,$type='text',$help='') {
$id='hgcf-'.sanitize_key($name);?>
<label class="hgcf-admin-field" for="<?php echo esc_attr($id); ?>"><span><?php echo esc_html($label); ?></span><input id="<?php echo esc_attr($id); ?>" type="<?php echo esc_attr($type); ?>" name="<?php echo esc_attr($name); ?>" value="<?php echo esc_attr($value); ?>"><?php if($help): ?><small><?php echo esc_html($help); ?></small><?php endif; ?></label>
<?php
}
function hgcf_service_row($prefix,$index,$id,$names,$languages) { ?>
<div class="hgcf-service-row"><input type="hidden" name="<?php echo esc_attr($prefix.'[services]['.$index.'][id]'); ?>" value="<?php echo esc_attr($id); ?>">
<?php foreach($languages as $lang=>$name)hgcf_admin_input($name,$prefix.'[services]['.$index.'][labels]['.$lang.']',$names[$lang]??$names['en']??$names['nl']??''); ?>
<button type="button" class="button-link-delete hgcf-remove-service">Verwijderen</button></div>
<?php
}
function hgcf_workflow_card($flow,$index,$languages,$template=false) {
$prefix='hgcf_settings[workflows]['.$index.']';$default=hgcf_default_language(); ?>
<details class="hgcf-workflow" <?php if($template)echo 'open'; ?> data-next-service="<?php echo count($flow['services']); ?>">
<summary><span class="hgcf-workflow-name"><?php echo esc_html($flow['label'][$default]??$flow['label']['nl']??'Workflow'); ?></span><span class="hgcf-workflow-badge"><?php echo $flow['enabled']?'Actief':'Uitgeschakeld'; ?></span></summary>
<div class="hgcf-workflow-body"><input type="hidden" name="<?php echo esc_attr($prefix.'[id]'); ?>" value="<?php echo esc_attr($flow['id']); ?>">
<div class="hgcf-workflow-toolbar"><label><input type="checkbox" class="hgcf-workflow-enabled" name="<?php echo esc_attr($prefix.'[enabled]'); ?>" value="1" <?php checked($flow['enabled']); ?>> Deze workflow inschakelen</label><button type="button" class="button-link-delete hgcf-remove-workflow">Workflow verwijderen</button></div>
<div class="hgcf-admin-grid"><?php foreach($languages as $lang=>$name)hgcf_admin_input('Naam voor bezoekers · '.$name,$prefix.'[label]['.$lang.']',$flow['label'][$lang]??hgcf_translated($flow['label'],$lang)); ?></div>
<h3>Velden in dit formulier</h3><p>Naam en e-mailadres zijn altijd verplicht. Stel hieronder de aanvullende velden in.</p>
<div class="hgcf-field-matrix"><?php foreach(['phone'=>'Telefoonnummer','service'=>'Dienstenkeuze','date'=>'Voorkeursdatum','time'=>'Voorkeurstijd'] as $key=>$label): ?>
<label><span><?php echo esc_html($label); ?></span><select data-hgcf-state="<?php echo esc_attr($key); ?>" name="<?php echo esc_attr($prefix.'['.$key.']'); ?>"><?php foreach(['hidden'=>'Niet tonen','optional'=>'Optioneel','required'=>'Verplicht'] as $value=>$name): ?><option value="<?php echo esc_attr($value); ?>" <?php selected($flow[$key],$value); ?>><?php echo esc_html($name); ?></option><?php endforeach; ?></select></label>
<?php endforeach; ?></div><label class="hgcf-checkbox"><input type="checkbox" name="<?php echo esc_attr($prefix.'[message_required]'); ?>" value="1" <?php checked($flow['message_required']); ?>> Bericht verplicht maken</label>
<div class="hgcf-flow-times"><h3>Tijdvoorkeur</h3><label class="hgcf-admin-field"><span>Tijdkeuze</span><select data-hgcf-time-kind name="<?php echo esc_attr($prefix.'[time_mode]'); ?>"><option value="exact" <?php selected(hgcf_time_mode($flow),'exact'); ?>>Exact tijdstip</option><option value="daypart" <?php selected(hgcf_time_mode($flow),'daypart'); ?>>Dagdeel (ochtend, middag of avond)</option><option value="text" <?php selected(hgcf_time_mode($flow),'text'); ?>>Vrije tekst (meerdere voorkeursmomenten)</option></select></label><div class="hgcf-flow-time-range"><div class="hgcf-admin-grid"><?php hgcf_admin_input('Vanaf',$prefix.'[opening_time]',$flow['opening_time'],'time');hgcf_admin_input('Tot',$prefix.'[closing_time]',$flow['closing_time'],'time'); ?></div><p class="description">Deze tijden begrenzen de tijdkeuze en bepalen welke dagdelen beschikbaar zijn. Dit is geen agenda of beschikbaarheidscontrole.</p></div></div>
<div class="hgcf-flow-services"><h3>Diensten / keuzemogelijkheden</h3><label class="hgcf-admin-field"><span>Invoer voor dit veld</span><select data-hgcf-service-kind name="<?php echo esc_attr($prefix.'[service_mode]'); ?>"><option value="choices" <?php selected(hgcf_service_mode($flow),'choices'); ?>>Keuzelijst</option><option value="amount" <?php selected(hgcf_service_mode($flow),'amount'); ?>>Vrij bedrag in euro</option></select></label><div class="hgcf-service-choices"><p>Vul iedere keuze in. De technische code wordt automatisch bewaard.</p><div class="hgcf-service-list"><?php $i=0;foreach($flow['services'] as $id=>$names)hgcf_service_row($prefix,$i++,$id,$names,$languages); ?></div><button type="button" class="button hgcf-add-service">Keuze toevoegen</button>
<template class="hgcf-service-template"><?php hgcf_service_row($prefix,'__SERVICE__','__SERVICE_ID__',[],$languages); ?></template></div></div>
<details class="hgcf-workflow-texts"><summary>Labels en toelichting aanpassen</summary><div class="hgcf-admin-grid"><?php foreach(['subject'=>'Label in e-mailonderwerp','message_label'=>'Label berichtveld','service_label'=>'Label dienstenkeuze'] as $key=>$label)foreach($languages as $lang=>$name)hgcf_admin_input($label.' · '.$name,$prefix.'['.$key.']['.$lang.']',$flow[$key][$lang]??hgcf_translated($flow[$key],$lang)); ?></div>
<?php foreach($languages as $lang=>$name): ?><label class="hgcf-admin-field"><span>Toelichting bij deze workflow · <?php echo esc_html($name); ?></span><textarea rows="3" name="<?php echo esc_attr($prefix.'[hint]['.$lang.']'); ?>"><?php echo esc_textarea($flow['hint'][$lang]??hgcf_translated($flow['hint'],$lang)); ?></textarea></label><?php endforeach; ?></details>
<h3>Aflevering</h3><?php hgcf_admin_input('Ontvangstadres voor deze workflow (optioneel)',$prefix.'[recipient]',$flow['recipient'],'email','Laat leeg om het algemene ontvangstadres te gebruiken.'); ?>
</div></details>
<?php
}
add_action('admin_enqueue_scripts',function($hook){if($hook!==HG_Plugin_Admin::hook('hg-contactform'))return;wp_enqueue_style('hgcf-admin',plugins_url('assets/admin.css',HGCF_FILE),[],HGCF_VERSION);wp_enqueue_script('hgcf-admin',plugins_url('assets/admin.js',HGCF_FILE),[],HGCF_VERSION,true);});
function hgcf_admin_info() {
$manifest=json_decode(file_get_contents(__DIR__.'/vendor/altcha/versions.json'),true);
$version=fn($key)=>is_string($manifest[$key]['version']??null)?$manifest[$key]['version']:'Niet beschikbaar';
$polylang=function_exists('pll_languages_list')?(defined('POLYLANG_VERSION')?POLYLANG_VERSION:'Actief; versie niet beschikbaar'):'Niet actief';
$rows=[
['HG Contactformulier',HGCF_VERSION,'Formulier, workflows en beheer'],
['WordPress',get_bloginfo('version'),'Website en verzending via wp_mail'],
['PHP',PHP_VERSION,'Uitvoering op de server'],
['Polylang',$polylang,'Taalkeuze en vertalingen'],
['ALTCHA-widget',$version('widget'),'Antispamcontrole in de browser'],
['ALTCHA PHP-library',$version('php'),'Controle van het antwoord op de server'],
]; ?>
<section id="hgcf-info" class="hgcf-admin-panel"><div class="hgcf-admin-card"><h2>Over deze plugin</h2><p>Gebruikte onderdelen en hun versies op deze website.</p><div class="hgcf-tech-table"><table class="widefat striped"><thead><tr><th scope="col">Onderdeel</th><th scope="col">Versie</th><th scope="col">Functie</th></tr></thead><tbody><?php foreach($rows as $row): ?><tr><?php foreach($row as $value): ?><td><?php echo esc_html($value); ?></td><?php endforeach; ?></tr><?php endforeach; ?></tbody></table></div></div>
<div class="hgcf-admin-card"><h2>Antispam en verzending</h2><p>ALTCHA is lokaal gebundeld. De browser haalt een uitdaging op bij deze website; de server controleert het antwoord voordat er mail wordt verstuurd. Hiervoor worden geen externe verificatiediensten gebruikt.</p><p>De basisbescherming bestaat uit een verborgen botveld, een ondertekende tijdcontrole, formuliertokens en een verzendlimiet. Met ALTCHA worden ook verlopen en eerder gebruikte antwoorden geweigerd.</p><p>Berichten worden verstuurd via de bestaande mailvoorziening van WordPress en niet als inzendingen opgeslagen. Voor antispam worden tijdelijk technische limiet- en verificatiegegevens bewaard.</p></div>
<div class="hgcf-admin-card"><h2>Onderhoud</h2><p>ALTCHA wordt bijgewerkt als onderdeel van een nieuwe versie van HG Contactformulier. Er worden geen nieuwe versies automatisch van een CDN geladen.</p><p class="description">Voor ontwikkelaars: de repository bevat <code>scripts/update_altcha.py</code> voor versiecontrole en het bijwerken van de gebundelde onderdelen. Test een update voordat je de nieuwe pluginversie uitrolt.</p></div></section>
<?php
}
function hgcf_admin_page() {
if(!current_user_can('manage_options'))wp_die('Geen toegang.', '', ['response'=>403]);
$s=hgcf_settings();$languages=hgcf_languages();$flows=$s['workflows'];?>
<div class="wrap hgcf-admin"><header class="hgcf-admin-header"><div><h1>HG Contactformulier</h1><p>Beheer je mailinstellingen, bezoekersroutes en formulierteksten.</p></div><span class="hgcf-language-status"><?php echo count($languages)>1?'Meertalig via Polylang':'Eén website-taal'; ?> · <?php echo esc_html(implode(' / ',$languages)); ?></span></header>
<?php settings_errors('hgcf_settings'); ?>
<form action="options.php" method="post"><?php settings_fields('hgcf'); ?>
<nav class="hgcf-admin-tabs" aria-label="Instellingengroepen"><a class="is-active" href="#hgcf-general">Algemeen</a><a href="#hgcf-workflows">Workflows <span><?php echo count($flows); ?></span></a><a href="#hgcf-texts">Teksten<?php if(count($languages)>1)echo ' & talen'; ?></a><a href="#hgcf-info">Over deze plugin</a></nav>
<section id="hgcf-general" class="hgcf-admin-panel"><div class="hgcf-admin-card"><h2>E-mail</h2><p>Dit zijn de standaardinstellingen voor alle workflows.</p><div class="hgcf-admin-grid">
<?php foreach(['recipient'=>['Ontvangstadres','email','Hier komen de formulierberichten binnen.'],'sender_email'=>['Afzenderadres','email','Gebruik een adres op een domein waarvoor je mailserver mag versturen. Leeg behoudt de standaard.'],'sender_name'=>['Afzendernaam','text','De naam die de ontvanger bij je mail ziet.'],'site_name'=>['Naam in e-mailonderwerp','text','Wordt vóór het onderwerp van de gekozen workflow geplaatst.'],'contact_name'=>['Contactnaam','text','Beschikbaar als {contact_name} in formulierteksten.']] as $key=>$field)hgcf_admin_input($field[0],'hgcf_settings['.$key.']',$s[$key],$field[1],$field[2]); ?>
</div><p class="hgcf-admin-note">Reply-To blijft het bezoekersadres. Het technische retouradres en de uiteindelijke aflevering worden door de mailvoorziening bepaald.</p></div>
<div class="hgcf-admin-card"><h2>Antispam</h2><input type="hidden" name="hgcf_settings[altcha_enabled]" value="0"><label class="hgcf-checkbox"><input type="checkbox" name="hgcf_settings[altcha_enabled]" value="1" <?php checked($s['altcha_enabled']); ?>> Antispamcontrole inschakelen</label><p>Helpt ongewenste berichten tegen te houden. Bezoekers doorlopen een korte controle voordat ze het formulier kunnen versturen.</p></div>
<div class="hgcf-admin-card"><h2>Formulierweergave</h2><?php foreach(['show_consent'=>'Toestemmingsvinkje tonen en verplicht stellen','show_note'=>'Toelichting onder het formulier tonen'] as $key=>$label): ?><input type="hidden" name="<?php echo esc_attr('hgcf_settings['.$key.']'); ?>" value="0"><label class="hgcf-checkbox"><input type="checkbox" name="<?php echo esc_attr('hgcf_settings['.$key.']'); ?>" value="1" <?php checked($s[$key]); ?>> <?php echo esc_html($label); ?></label><?php endforeach; ?></div>
<div class="hgcf-admin-card"><h2>Op een pagina plaatsen</h2><p>Plaats <code>[hg_contactform]</code> in een shortcodeblok. De taal volgt de website<?php if(count($languages)>1)echo ' en Polylang'; ?>.</p><p>Naam, e-mailadres en bericht vormen de basis. Het toestemmingsvinkje en de toelichting kun je hierboven aan- of uitzetten. Via Workflows geef je bezoekers aanvullende routes, zoals een vraag of een afspraakaanvraag.</p></div></section>
<section id="hgcf-workflows" class="hgcf-admin-panel"><div class="hgcf-panel-heading"><div><h2>Workflows</h2><p>Eén workflow is één keuze voor de bezoeker. Klap een kaart open om de velden aan te passen.</p></div><button type="button" class="button button-secondary" id="hgcf-add-workflow">Workflow toevoegen</button></div>
<div id="hgcf-workflow-list" data-next-index="<?php echo count($flows); ?>"><?php $i=0;foreach($flows as $flow)hgcf_workflow_card($flow,$i++,$languages); ?></div>
<template id="hgcf-workflow-template"><?php $new=hgcf_workflow_defaults('__WORKFLOW_ID__');foreach($languages as $lang=>$name){$new['label'][$lang]=$lang==='nl'?'Nieuwe workflow':'New workflow';$new['message_label'][$lang]=$lang==='nl'?'Bericht':'Message';$new['subject'][$lang]=$lang==='nl'?'bericht':'message';$new['service_label'][$lang]=$lang==='nl'?'Welke dienst?':'Which service?';$new['hint'][$lang]='';}hgcf_workflow_card($new,'__INDEX__',$languages,true); ?></template>
<p class="description">Er moet minimaal één actieve workflow zijn. Een aanvraag wordt niet automatisch een bevestigde afspraak.</p></section>
<section id="hgcf-texts" class="hgcf-admin-panel"><div class="hgcf-panel-heading"><div><h2>Formulierteksten</h2><p><?php echo count($languages)>1?'De talen volgen de actieve Polylang-configuratie.':'Alleen de ingestelde WordPress-taal wordt getoond. Een taalplugin is niet nodig.'; ?> Niet-actieve vertalingen blijven bewaard.</p></div></div>
<?php foreach($languages as $lang=>$name): ?><div class="hgcf-admin-card"><h3><?php echo esc_html($name); ?></h3><?php foreach(['title'=>'Formuliertitel','consent'=>'Toestemmingstekst','note'=>'Toelichting onder het formulier','success'=>'Bevestiging na verzending'] as $key=>$label): ?><label class="hgcf-admin-field"><span><?php echo esc_html($label); ?></span><textarea rows="<?php echo $key==='title'?1:3; ?>" maxlength="1500" name="<?php echo esc_attr('hgcf_settings['.$key.'_'.$lang.']'); ?>"><?php echo esc_textarea(hgcf_raw_local_setting($key,$lang)); ?></textarea></label><?php endforeach; ?><p class="description">Je kunt <code>{contact_name}</code> gebruiken. Labels voor afzonderlijke workflows vind je op hun eigen kaart.</p></div><?php endforeach; ?></section>
<?php hgcf_admin_info(); ?>
<input type="hidden" name="hgcf_settings[_complete]" value="1"><div class="hgcf-save-bar"><?php submit_button('Wijzigingen opslaan','primary','submit',false); ?><span>Wijzigingen worden pas actief na opslaan.</span></div>
</form></div>
<?php
}
+88
View File
@@ -0,0 +1,88 @@
<?php
if (!defined('ABSPATH')) exit;
spl_autoload_register(function ($class) {
$prefix = 'HGCFVendor\\AltchaOrg\\Altcha\\';
if (!str_starts_with($class, $prefix)) return;
$relative = substr($class, strlen($prefix));
if (!preg_match('/^[A-Za-z0-9_\\\\]+$/D', $relative)) return;
$file = __DIR__.'/vendor/altcha/src/'.str_replace('\\', '/', $relative).'.php';
if (is_file($file)) require_once $file;
});
function hgcf_altcha_enabled() { return hgcf_setting('altcha_enabled') === true; }
function hgcf_altcha_engine() {
return new HGCFVendor\AltchaOrg\Altcha\Altcha(hash_hmac('sha256', 'hgcf-altcha-v1|'.home_url('/'), wp_salt('auth')));
}
function hgcf_create_altcha_challenge($page) {
return hgcf_altcha_engine()->createChallenge(new HGCFVendor\AltchaOrg\Altcha\CreateChallengeOptions(
algorithm: new HGCFVendor\AltchaOrg\Altcha\Algorithm\Pbkdf2(),
cost: 1000, keyPrefix: '00', expiresAt: time()+20*MINUTE_IN_SECONDS,
data: ['page'=>(int)$page]
))->toArray();
}
/** Validate before derivation, then atomically claim a single-use answer. */
function hgcf_verify_altcha($raw, $page) {
if (!is_string($raw) || $raw === '' || strlen($raw)>8192) return false;
$decoded = base64_decode($raw, true);
if ($decoded === false) return false;
$payload = json_decode($decoded, true, 12);
if (!is_array($payload) || !is_array($payload['challenge']??null) || !is_array($payload['solution']??null)) return false;
$challenge=$payload['challenge']; $p=$challenge['parameters']??null; $s=$payload['solution'];
if (!is_array($p) || ($p['algorithm']??'')!=='PBKDF2/SHA-256' || ($p['cost']??null)!==1000 || ($p['keyLength']??null)!==32 || ($p['keyPrefix']??'')!=='00') return false;
if (isset($p['keySignature']) || isset($p['memoryCost']) || isset($p['parallelism'])) return false;
if (!is_array($p['data']??null) || ($p['data']['page']??null)!==(int)$page) return false;
$expires=$p['expiresAt']??null;
if (!is_int($expires) || $expires<=time() || $expires>time()+20*MINUTE_IN_SECONDS) return false;
foreach (['nonce','salt'] as $key) if (!is_string($p[$key]??null) || !preg_match('/^[a-f0-9]{32}$/D',$p[$key])) return false;
if (!is_string($challenge['signature']??null) || !preg_match('/^[a-f0-9]{64}$/D',$challenge['signature'])) return false;
if (!is_int($s['counter']??null) || $s['counter']<0 || $s['counter']>1000000 || !is_string($s['derivedKey']??null) || !preg_match('/^[a-f0-9]{64}$/D',$s['derivedKey'])) return false;
try {
$result=hgcf_altcha_engine()->verifySolution(new HGCFVendor\AltchaOrg\Altcha\VerifySolutionOptions(
payload: $payload, algorithm: new HGCFVendor\AltchaOrg\Altcha\Algorithm\Pbkdf2()
));
if (!$result->verified) return false;
} catch (Throwable $error) { return false; }
// Unique option_name index prevents simultaneous replays. No form data is stored.
return add_option('hgcf_pow_used_'.hash('sha256',$challenge['signature']), $expires, '', false);
}
function hgcf_altcha_cleanup() {
global $wpdb;
$keys=$wpdb->get_col($wpdb->prepare("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s AND CAST(option_value AS UNSIGNED) < %d LIMIT 1000", $wpdb->esc_like('hgcf_pow_used_').'%', time()));
foreach($keys as $key)delete_option($key);
if(!hgcf_altcha_enabled()&&!$keys)wp_clear_scheduled_hook('hgcf_altcha_cleanup');
}
add_action('hgcf_altcha_cleanup','hgcf_altcha_cleanup');
function hgcf_altcha_schedule() {
if (hgcf_altcha_enabled()) {
if (!wp_next_scheduled('hgcf_altcha_cleanup')) wp_schedule_event(time()+HOUR_IN_SECONDS,'hourly','hgcf_altcha_cleanup');
}
}
add_action('init','hgcf_altcha_schedule');
register_deactivation_hook(HGCF_FILE, function(){wp_clear_scheduled_hook('hgcf_altcha_cleanup');hgcf_altcha_cleanup();});
function hgcf_altcha_endpoint($request) {
if (!hgcf_altcha_enabled()) return new WP_Error('hgcf_disabled','Not found.',['status'=>404]);
$page=(int)$request->get_param('page'); $post=get_post($page);
if (!$post || !is_post_publicly_viewable($post) || (!has_shortcode($post->post_content,'hg_contactform') && !has_shortcode($post->post_content,'mlh_contact'))) return new WP_Error('hgcf_page','Invalid form page.',['status'=>404]);
$key='hgcf_pow_rate_'.hash_hmac('sha256',$_SERVER['REMOTE_ADDR']??'unknown',wp_salt('auth'));
$rate=get_transient($key);
if ($rate && $rate['count']>=30) return new WP_Error('hgcf_rate','Please try again in a few minutes.',['status'=>429]);
$rate=$rate?:['count'=>0,'until'=>time()+5*MINUTE_IN_SECONDS]; $rate['count']++;
set_transient($key,$rate,max(1,$rate['until']-time()));
try { return new WP_REST_Response(hgcf_create_altcha_challenge($page),200,['Cache-Control'=>'no-store, private, max-age=0']); }
catch (Throwable $error) { return new WP_Error('hgcf_unavailable','Verification temporarily unavailable.',['status'=>503]); }
}
add_action('rest_api_init',function(){
register_rest_route('hg-contactform/v1','/challenge',[
'methods'=>'GET','callback'=>'hgcf_altcha_endpoint','permission_callback'=>'__return_true',
'args'=>['page'=>['required'=>true,'type'=>'integer','minimum'=>1]]
]);
});
add_filter('rest_post_dispatch',function($response,$server,$request){
if ($request->get_route()==='/hg-contactform/v1/challenge' && $response instanceof WP_REST_Response) $response->header('Cache-Control','no-store, private, max-age=0');
return $response;
},10,3);
add_filter('script_loader_tag',function($tag,$handle){
if ($handle!=='hgcf-altcha') return $tag;
$tag=preg_replace('/\s+type=([\'"])text\/javascript\1/','',$tag);
return str_replace('<script ', '<script type="module" ', $tag);
},10,2);
+106
View File
@@ -0,0 +1,106 @@
<?php
if(!defined('ABSPATH'))exit;
function hgcf_text($nl,$en,$lang){return str_starts_with($lang,'nl')?$nl:$en;}
function hgcf_time_mode($flow){$mode=$flow['time_mode']??'exact';return in_array($mode,['exact','daypart','text'],true)?$mode:'exact';}
function hgcf_service_mode($flow){return ($flow['service_mode']??'choices')==='amount'?'amount':'choices';}
function hgcf_parse_amount($value){
if(!is_string($value)||!preg_match('/^[0-9]{1,9}(?:[.,][0-9]{1,2})?$/D',$value))return null;
$parts=explode('.',str_replace(',','.',$value));$whole=ltrim($parts[0],'0');$whole=$whole===''?'0':$whole;$fraction=str_pad($parts[1]??'',2,'0');
return $whole==='0'&&$fraction==='00'?null:$whole.'.'.$fraction;
}
function hgcf_time_label($flow,$lang){return match(hgcf_time_mode($flow)){'text'=>hgcf_text('Voorkeursmomenten','Preferred times',$lang),'daypart'=>hgcf_text('Voorkeursdagdeel','Preferred time of day',$lang),default=>hgcf_text('Voorkeurstijd','Preferred time',$lang)};}
function hgcf_dayparts($flow,$lang='nl') {
$result=[];foreach(['morning'=>['06:00','12:00','Ochtend','Morning'],'afternoon'=>['12:00','18:00','Middag','Afternoon'],'evening'=>['18:00','24:00','Avond','Evening']] as $id=>$part){
if($flow['opening_time']<$part[1]&&$flow['closing_time']>$part[0])$result[$id]=hgcf_text($part[2],$part[3],$lang);
}return $result;
}
function hgcf_types($id='request') {
$flow=hgcf_workflow($id);$types=[];foreach($flow['services']??[] as $key=>$names)$types[$key]=[$names['nl']??$names['en']??'', $names['en']??$names['nl']??''];
return $types+['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]))return new WP_Error('invalid',hgcf_text('Controleer de ingevulde velden.','Please check the form fields.',$lang));$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(!hgcf_valid_email($data['email'])||strlen($data['email'])>254)$errors->add('email',hgcf_text('Vul een geldig e-mailadres in.','Enter a valid email address.',$lang));
$flow=hgcf_workflow($data['mode']);if(!$flow){$errors->add('mode',hgcf_text('Kies een beschikbare optie.','Choose an available option.',$lang));return $errors;}
if(strlen($data['message'])>5000||($flow['message_required']&&strlen($data['message'])<5))$errors->add('message',hgcf_text('Schrijf je bericht (5 tot 5000 tekens).','Write your message (5 to 5000 characters).',$lang));
foreach(['phone'=>'phone','service'=>'massage','date'=>'preferred_date','time'=>'preferred_time'] as $field=>$key){
if($flow[$field]==='hidden'){$data[$key]='';continue;}
if($flow[$field]==='required'&&($data[$key]===''||($field==='service'&&$data[$key]==='unsure')))$errors->add($key,hgcf_text('Vul alle verplichte velden in.','Complete all required fields.',$lang));
if($field==='phone'&&$data[$key]!==''&&(strlen($data[$key])>40||!preg_match('/^[0-9+() .-]{5,40}$/',$data[$key])))$errors->add('phone',hgcf_text('Controleer je telefoonnummer.','Please check your phone number.',$lang));
if($field==='service'&&$data[$key]!==''){
if(hgcf_service_mode($flow)==='amount'){
$amount=hgcf_parse_amount($data[$key]);if($amount===null)$errors->add('massage',hgcf_text('Vul een geldig bedrag groter dan 0 in, bijvoorbeeld 50 of 37,50.','Enter a valid amount greater than 0, for example 50 or 37.50.',$lang));else $data[$key]=$amount;
}elseif($data[$key]!=='unsure'&&!isset($flow['services'][$data[$key]]))$errors->add('massage',hgcf_text('Kies een beschikbare dienst.','Choose an available service.',$lang));
}
if($field==='date'&&$data[$key]!==''){$date=DateTimeImmutable::createFromFormat('!Y-m-d',$data[$key],wp_timezone());if(!$date||$date->format('Y-m-d')!==$data[$key]||$data[$key]<wp_date('Y-m-d'))$errors->add($key,hgcf_text('Kies vandaag of een datum in de toekomst.','Choose today or a future date.',$lang));}
if($field==='time'&&$data[$key]!==''){
if(hgcf_time_mode($flow)==='text'){
if(strlen($data[$key])>1000)$errors->add($key,hgcf_text('Gebruik maximaal 1000 tekens voor je voorkeursmomenten.','Use no more than 1000 characters for your preferred times.',$lang));
}elseif(hgcf_time_mode($flow)==='daypart'){
if(!isset(hgcf_dayparts($flow,$lang)[$data[$key]]))$errors->add($key,hgcf_text('Kies een beschikbaar dagdeel.','Choose an available time of day.',$lang));
}elseif(!preg_match('/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/',$data[$key])||$data[$key]<$flow['opening_time']||$data[$key]>$flow['closing_time'])$errors->add($key,sprintf(hgcf_text('Kies een tijd tussen %s en %s.','Choose a time between %s and %s.',$lang),$flow['opening_time'],$flow['closing_time']));
}
}
if(hgcf_setting('show_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'||($key==='preferred_time'&&hgcf_time_mode($flow)==='text'))?sanitize_textarea_field($value):sanitize_text_field($value);return $data;
}
function hgcf_send(array $data,$lang) {
$flow=hgcf_workflow($data['mode']);if(!$flow)return false;
$recipient=$flow['recipient']?:hgcf_setting('recipient');if(!hgcf_valid_email($recipient)||!hgcf_valid_email($data['email']))return false;
$label=hgcf_translated($flow['label'],$lang);$subject=hgcf_translated($flow['subject'],$lang);
$body='Contactformulier '.sanitize_text_field(hgcf_setting('site_name'))."\nTaal: ".$lang."\nType: ".$label."\nNaam: ".$data['name']."\nE-mail: ".$data['email']."\n";
if($flow['phone']!=='hidden')$body.='Telefoon: '.($data['phone']?:'Niet opgegeven')."\n";
if($flow['service']!=='hidden'){
if(hgcf_service_mode($flow)==='amount'){$amount=$data['massage']!==''?hgcf_parse_amount($data['massage']):null;if($data['massage']!==''&&$amount===null)return false;$service=$amount===null?hgcf_text('Niet opgegeven','Not specified',$lang):'€'.(str_starts_with($lang,'nl')?str_replace('.',',',$amount):$amount);}
else $service=isset($flow['services'][$data['massage']])?hgcf_translated($flow['services'][$data['massage']],$lang):hgcf_text('Ik weet het nog niet','Not sure yet',$lang);
$body.=rtrim(hgcf_translated($flow['service_label'],$lang)," ?*:\t\n\r").': '.$service."\n";
}
if($flow['date']!=='hidden')$body.='Voorkeursdatum: '.($data['preferred_date']?:'Geen voorkeur')."\n";
if($flow['time']!=='hidden'){
$time=match(hgcf_time_mode($flow)){'daypart'=>hgcf_dayparts($flow,$lang)[$data['preferred_time']]??hgcf_text('Geen voorkeur','No preference',$lang),default=>$data['preferred_time']?:hgcf_text('Geen voorkeur','No preference',$lang)};
$body.=hgcf_time_label($flow,$lang).': '.(hgcf_time_mode($flow)==='text'?"\n":'').$time."\n";
}
if($flow['date']!=='hidden'||$flow['time']!=='hidden')$body.="Dit is een aanvraag, geen bevestigde afspraak.\n";
$body.="\nBericht:\n".$data['message'];$headers=['Content-Type: text/plain; charset=UTF-8','Reply-To: '.$data['email']];
$email=hgcf_setting('sender_email');$name=hgcf_setting('sender_name');
if($email!=='') {if(!hgcf_valid_email($email)||!is_string($name)||strlen($name)>150||preg_match('/[\r\n]/',$name))return false;$name=sanitize_text_field($name?:hgcf_setting('site_name'));$quoted='"'.str_replace(['\\','"'],['\\\\','\\"'],$name).'"';$headers[]='From: '.$quoted.' <'.$email.'>';}
return wp_mail($recipient,sanitize_text_field(hgcf_setting('site_name')).': '.sanitize_text_field($subject),$body,$headers);
}
function hgcf_render($atts=[]) {
$atts=shortcode_atts(['lang'=>'auto'],$atts);$languages=hgcf_languages();$lang=isset($languages[$atts['lang']])?$atts['lang']:hgcf_language();$t=fn($nl,$en)=>hgcf_text($nl,$en,$lang);
$flows=hgcf_workflows();if(!$flows)return '';$errors=$GLOBALS['mlhc_errors']??null;
$value=fn($key)=>$errors&&isset($_POST['mlhc_'.$key])&&is_string($_POST['mlhc_'.$key])?wp_unslash($_POST['mlhc_'.$key]):'';
$requested=$_GET['hgcf_workflow']??'';$initial=is_string($requested)&&isset($flows[$requested])?$requested:array_key_first($flows);
$mode=isset($flows[$value('mode')])?$value('mode'):$initial;$flow=$flows[$mode];$started=(string)time();
$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)).'</p><a href="'.esc_url(get_permalink()).'">'.esc_html($t('Nog een bericht sturen','Send another message')).'</a></section>';
$config=[];foreach($flows as $id=>$item){$services=[];foreach($item['services'] as $key=>$names)$services[]=['value'=>$key,'label'=>hgcf_translated($names,$lang)];$services[]=['value'=>'unsure','label'=>$t('Ik weet het nog niet','Not sure yet')];$config[$id]=['fields'=>array_intersect_key($item,array_flip(['phone','service','date','time'])),'messageRequired'=>$item['message_required'],'messageLabel'=>hgcf_translated($item['message_label'],$lang),'serviceLabel'=>hgcf_translated($item['service_label'],$lang),'serviceMode'=>hgcf_service_mode($item),'hint'=>hgcf_translated($item['hint'],$lang),'start'=>$item['opening_time'],'end'=>$item['closing_time'],'timeMode'=>hgcf_time_mode($item),'timeLabel'=>hgcf_time_label($item,$lang),'dayparts'=>hgcf_dayparts($item,$lang),'noTimePreference'=>$t('Geen voorkeur','No preference'),'services'=>$services];}
$has=fn($field)=>(bool)array_filter($flows,fn($item)=>$item[$field]!=='hidden');
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 $error): ?><li><?php echo esc_html($error); ?></li><?php endforeach; ?></ul></div><?php endif; ?>
<form class="mlhc-form" action="<?php echo esc_url(get_permalink()); ?>#contact-form" method="post" data-hgcf-workflows="<?php echo esc_attr(wp_json_encode($config)); ?>" data-hgcf-sending="<?php echo esc_attr($t('Wordt verstuurd…','Sending…')); ?>">
<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 id="mlhc-website" type="text" name="mlhc_website" tabindex="-1" autocomplete="off"></div>
<?php if(count($flows)>1): ?><fieldset class="form-mode"><legend><?php echo esc_html($t('Ik wil…','I would like to…')); ?></legend><?php foreach($flows as $id=>$item): ?><label><input type="radio" name="mlhc_mode" value="<?php echo esc_attr($id); ?>" <?php checked($mode,$id); ?>><?php echo esc_html(hgcf_translated($item['label'],$lang)); ?></label><?php endforeach; ?></fieldset><?php else: ?><input type="hidden" name="mlhc_mode" value="<?php echo esc_attr($mode); ?>"><?php endif; ?>
<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" name="mlhc_email" type="email" autocomplete="email" required maxlength="254" value="<?php echo esc_attr($value('email')); ?>"></label></div>
<?php if($has('phone')): ?><label for="mlhc-phone" data-hgcf-field="phone"><span data-hgcf-label><?php echo esc_html($t('Telefoonnummer','Phone number')); ?></span><input id="mlhc-phone" name="mlhc_phone" type="tel" autocomplete="tel" maxlength="40" value="<?php echo esc_attr($value('phone')); ?>"></label><?php endif; ?>
<?php if($has('service')||$has('date')||$has('time')): ?><fieldset class="request-fields">
<?php if($has('service')): ?><label for="<?php echo hgcf_service_mode($flow)==='amount'?'mlhc-amount':'mlhc-massage'; ?>" data-hgcf-field="service"><span class="service-label" data-hgcf-label><?php echo esc_html(hgcf_translated($flow['service_label'],$lang)); ?></span><select id="mlhc-massage" name="mlhc_massage" data-hgcf-service-mode="choices" <?php if(hgcf_service_mode($flow)==='amount')echo 'hidden disabled'; ?>><?php foreach($flow['services'] as $key=>$names): ?><option value="<?php echo esc_attr($key); ?>" <?php selected($value('massage'),$key); ?>><?php echo esc_html(hgcf_translated($names,$lang)); ?></option><?php endforeach; ?><option value="unsure" <?php selected($value('massage')===''?'unsure':$value('massage'),'unsure'); ?>><?php echo esc_html($t('Ik weet het nog niet','Not sure yet')); ?></option></select><input id="mlhc-amount" name="mlhc_massage" data-hgcf-service-mode="amount" type="text" inputmode="decimal" maxlength="12" placeholder="<?php echo esc_attr($t('Bijvoorbeeld 50 of 37,50','For example 50 or 37.50')); ?>" value="<?php echo esc_attr(hgcf_service_mode($flow)==='amount'?$value('massage'):''); ?>" <?php if(hgcf_service_mode($flow)!=='amount')echo 'hidden disabled'; ?>></label><?php endif; ?>
<div class="form-fields" data-hgcf-datetime-grid><?php if($has('date')): ?><label for="mlhc-date" data-hgcf-field="date"><span data-hgcf-label><?php echo esc_html($t('Voorkeursdatum','Preferred date')); ?></span><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><?php endif; ?><?php if($has('time')): ?><label for="<?php echo match(hgcf_time_mode($flow)){'daypart'=>'mlhc-daypart','text'=>'mlhc-preferences',default=>'mlhc-time'}; ?>" data-hgcf-field="time"><span data-hgcf-label><?php echo esc_html(hgcf_time_label($flow,$lang)); ?></span><input id="mlhc-time" name="mlhc_preferred_time" data-hgcf-time-mode="exact" type="time" min="<?php echo esc_attr($flow['opening_time']); ?>" max="<?php echo esc_attr($flow['closing_time']); ?>" value="<?php echo esc_attr(hgcf_time_mode($flow)==='exact'?$value('preferred_time'):''); ?>" <?php if(hgcf_time_mode($flow)!=='exact')echo 'hidden disabled'; ?>><select id="mlhc-daypart" name="mlhc_preferred_time" data-hgcf-time-mode="daypart" <?php if(hgcf_time_mode($flow)!=='daypart')echo 'hidden disabled'; ?>><option value=""><?php echo esc_html($t('Geen voorkeur','No preference')); ?></option><?php foreach(hgcf_dayparts($flow,$lang) as $key=>$label): ?><option value="<?php echo esc_attr($key); ?>" <?php selected($value('preferred_time'),$key); ?>><?php echo esc_html($label); ?></option><?php endforeach; ?></select><textarea id="mlhc-preferences" name="mlhc_preferred_time" data-hgcf-time-mode="text" rows="3" maxlength="1000" placeholder="<?php echo esc_attr($t('Bijvoorbeeld maandagmiddag, woensdag na 16.00 uur of vrijdag in de ochtend.','For example Monday afternoon, Wednesday after 4 pm or Friday morning.')); ?>" <?php if(hgcf_time_mode($flow)!=='text')echo 'hidden disabled'; ?>><?php echo esc_textarea(hgcf_time_mode($flow)==='text'?$value('preferred_time'):''); ?></textarea></label><?php endif; ?></div>
</fieldset><?php endif; ?><p class="form-note workflow-hint"><?php echo esc_html(hgcf_translated($flow['hint'],$lang)); ?></p>
<label for="mlhc-message"><span class="message-label"><?php echo esc_html(hgcf_translated($flow['message_label'],$lang)); ?></span><textarea id="mlhc-message" name="mlhc_message" rows="5" maxlength="5000"><?php echo esc_textarea($value('message')); ?></textarea></label>
<?php if(hgcf_setting('show_consent')): ?><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><?php endif; ?>
<?php if(hgcf_setting('show_note')): ?><p class="form-note"><?php echo esc_html(hgcf_local_setting('note',$lang)); ?></p><?php endif; ?>
<?php if(hgcf_altcha_enabled()): ?><div class="hgcf-antispam"><altcha-widget name="mlhc_altcha" challenge="<?php echo esc_url(add_query_arg('page',get_queried_object_id(),rest_url('hg-contactform/v1/challenge'))); ?>" language="<?php echo esc_attr(substr($lang,0,2)); ?>" auto="onfocus" workers="2"></altcha-widget><noscript><p class="form-note"><?php echo esc_html($t('Schakel JavaScript in voor de antispamcontrole of gebruik een andere contactmogelijkheid.','Enable JavaScript for the spam protection check or use another contact option.')); ?></p></noscript></div><?php endif; ?>
<button type="submit" class="button"><?php echo esc_html($t('Verstuur bericht','Send message')); ?></button>
</form></section>
<?php
if(hgcf_altcha_enabled())wp_enqueue_script('hgcf-altcha',plugins_url('assets/vendor/altcha/widget.js',HGCF_FILE),[],HGCF_VERSION,true);
wp_enqueue_style('hgcf',plugins_url('assets/contact.css',HGCF_FILE),[],HGCF_VERSION);wp_enqueue_script('hgcf',plugins_url('assets/contact.js',HGCF_FILE),[],HGCF_VERSION,true);
return ob_get_clean();
}
+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);
}
+27 -6
View File
@@ -1,9 +1,30 @@
<?php <?php
if(!defined('ABSPATH'))exit; if (!defined('ABSPATH')) exit;
function hgcf_language($content='') { function hgcf_languages() {
if($content!=='' && preg_match('/'.get_shortcode_regex(['hg_contactform','mlh_contact']).'/s',$content,$match)) { $languages=[];
$attrs=shortcode_parse_atts($match[3]);if(is_array($attrs)&&in_array($attrs['lang']??'',['nl','en'],true))return $attrs['lang']; if(function_exists('pll_languages_list')) {
foreach(pll_languages_list(['hide_empty'=>false,'fields'=>'slug']) as $slug) {
if(is_string($slug)&&preg_match('/^[a-z][a-z0-9_-]{1,19}$/i',$slug)) {
$name=$slug;
if(function_exists('PLL')) { $item=PLL()->model->get_language($slug); if($item)$name=$item->name; }
$languages[$slug]=$name;
}
}
} }
if(function_exists('pll_current_language')){ $language=pll_current_language('slug');if(in_array($language,['nl','en'],true))return $language; } if(!$languages){$locale=get_locale()?:'en_US';$slug=strtolower(explode('_',str_replace('-','_',$locale))[0]);$languages[$slug]=['nl'=>'Nederlands','en'=>'English'][$slug]??$locale;}
return str_starts_with(get_locale(),'en')?'en':'nl'; $languages=apply_filters('hgcf_languages',$languages);
return is_array($languages)&&$languages?$languages:['en'=>'English'];
}
function hgcf_default_language() {
$languages=hgcf_languages();
if(function_exists('pll_default_language')){$lang=pll_default_language('slug');if(isset($languages[$lang]))return $lang;}
return array_key_first($languages);
}
function hgcf_language($content='') {
$languages=hgcf_languages();
if($content!==''&&preg_match('/'.get_shortcode_regex(['hg_contactform','mlh_contact']).'/s',$content,$match)) {
$attrs=shortcode_parse_atts($match[3]);if(is_array($attrs)&&isset($languages[$attrs['lang']??'']))return $attrs['lang'];
}
if(function_exists('pll_current_language')){$lang=pll_current_language('slug');if(isset($languages[$lang]))return $lang;}
return hgcf_default_language();
} }
+99 -54
View File
@@ -1,66 +1,111 @@
<?php <?php
if (!defined('ABSPATH')) exit; if (!defined('ABSPATH')) exit;
function hgcf_defaults() { function hgcf_defaults() {
return ['recipient'=>get_option('admin_email'),'site_name'=>get_bloginfo('name'),'contact_name'=>'','sender_email'=>'','sender_name'=>'','enable_requests'=>false,'show_phone'=>true,'opening_time'=>'09:00','closing_time'=>'21:00','services'=>[], return ['recipient'=>get_option('admin_email'),'site_name'=>get_bloginfo('name'),'contact_name'=>'','sender_email'=>'','sender_name'=>'','altcha_enabled'=>false,'show_consent'=>true,'show_note'=>true,
'title_nl'=>'Waarmee kunnen we je helpen?','title_en'=>'How can we help?', '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.', '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.', '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.']; '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_workflow_defaults($id='question') {
function hgcf_setting($key) { return hgcf_settings()[$key]??''; } return ['id'=>$id,'enabled'=>true,'recipient'=>'','message_required'=>true,'phone'=>'optional','service'=>'hidden','date'=>'hidden','time'=>'hidden','time_mode'=>'exact','service_mode'=>'choices','opening_time'=>'09:00','closing_time'=>'21:00','services'=>[],
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'))); } 'label'=>['nl'=>'Een vraag stellen','en'=>'Ask a question'],'subject'=>['nl'=>'vraag','en'=>'question'],
function hgcf_sanitize_settings($input) { 'message_label'=>['nl'=>'Je vraag','en'=>'Your question'],'service_label'=>['nl'=>'Welke dienst?','en'=>'Which service?'],
$old=hgcf_settings(); if(!is_array($input))return $old; 'hint'=>['nl'=>'','en'=>'']];
$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']);} function hgcf_normalize_settings($saved) {
if(array_key_exists('sender_email',$input)) { $s=array_replace(hgcf_defaults(),is_array($saved)?$saved:[]);
$email=$input['sender_email']; if(!array_key_exists('workflows',$s)) {
if(is_string($email) && ($email==='' || (is_email($email) && !preg_match('/[\r\n]/',$email)))) $out['sender_email']=$email===''?'':sanitize_email($email); $question=hgcf_workflow_defaults();$question['phone']=($s['show_phone']??true)?'optional':'hidden';$flows=['question'=>$question];
else add_settings_error('hgcf_settings','sender_email','Vul een geldig afzenderadres in, of laat het leeg voor de standaardafzender.'); if($s['enable_requests']??false) {
} $request=hgcf_workflow_defaults('request');$request['message_required']=false;$request['phone']=$question['phone'];$request['service']='optional';$request['date']='optional';$request['time']='optional';
if(array_key_exists('sender_name',$input)) { $request['opening_time']=$s['opening_time']??'09:00';$request['closing_time']=$s['closing_time']??'21:00';
$name=$input['sender_name']; foreach(($s['services']??[]) as $id=>$names)$request['services'][$id]=['nl'=>$names[0],'en'=>$names[1]];
if(is_string($name)&&strlen($name)<=150&&!preg_match('/[\r\n]/',$name))$out['sender_name']=sanitize_text_field($name); foreach(['nl','en'] as $lang){$request['label'][$lang]=$s['request_label_'.$lang]??($lang==='nl'?'Een afspraak aanvragen':'Request an appointment');$request['subject'][$lang]=$lang==='nl'?'afspraakaanvraag':'appointment request';$request['service_label'][$lang]=$s['service_label_'.$lang]??($lang==='nl'?'Welke dienst?':'Which service?');}
else add_settings_error('hgcf_settings','sender_name','Vul een afzendernaam van maximaal 150 tekens in, zonder regeleinden.'); $request['message_label']=['nl'=>'Toelichting','en'=>'Message'];$request['hint']=['nl'=>'Dit is een voorkeur, geen reservering. We stemmen de datum en tijd met je af.','en'=>'This is a preference, not a reservation. We will confirm the date and time with you.'];$flows['request']=$request;
}
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.'); $s['workflows']=$flows;
} }
return $s;
}
function hgcf_settings(){return hgcf_normalize_settings(get_option('hgcf_settings',[]));}
function hgcf_setting($key){return hgcf_settings()[$key]??'';}
function hgcf_translated($values,$lang,$fallback='') {
$text=$values[$lang]??$values[hgcf_default_language()]??$values['en']??$values['nl']??$fallback;
return str_replace('{contact_name}',hgcf_setting('contact_name')?:hgcf_setting('site_name'),is_string($text)?$text:$fallback);
}
function hgcf_raw_local_setting($key,$lang) {
$s=hgcf_settings();return $s[$key.'_'.$lang]??$s[$key.'_'.hgcf_default_language()]??$s[$key.'_en']??$s[$key.'_nl']??'';
}
function hgcf_local_setting($key,$lang) {
return str_replace('{contact_name}',hgcf_setting('contact_name')?:hgcf_setting('site_name'),hgcf_raw_local_setting($key,$lang));
}
function hgcf_workflows($active=true) {
$flows=hgcf_setting('workflows');return $active?array_filter($flows,fn($f)=>!empty($f['enabled'])):$flows;
}
function hgcf_workflow($id){$flows=hgcf_workflows();return $flows[$id]??null;}
function hgcf_valid_email($value,$empty=false){return is_string($value)&&(($empty&&$value==='')||(is_email($value)&&!preg_match('/[\r\n]/',$value)));}
function hgcf_valid_times($start,$end){return 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;}
function hgcf_sanitize_workflows($rows,$old,$languages) {
if(!is_array($rows)||count($rows)>20)return new WP_Error('flows','Gebruik één tot twintig workflows.');
$flows=[];
foreach($rows as $row) {
if(!is_array($row))return new WP_Error('flows','Een workflow is ongeldig.');
$id=$row['id']??'';
if(!is_string($id)||!preg_match('/^[a-z][a-z0-9_-]{0,39}$/',$id)||isset($flows[$id]))return new WP_Error('flows','Elke workflow moet een unieke geldige code hebben.');
$flow=array_replace(hgcf_workflow_defaults($id),$old[$id]??[]);
$flow['enabled']=($row['enabled']??'')==='1';$flow['message_required']=($row['message_required']??'')==='1';
$recipient=$row['recipient']??'';if(!hgcf_valid_email($recipient,true))return new WP_Error('flows','Controleer het ontvangstadres van de workflow.');$flow['recipient']=$recipient;
foreach(['phone','service','date','time'] as $field){if(!in_array($row[$field]??'', ['hidden','optional','required'],true))return new WP_Error('flows','Controleer de veldinstellingen.');$flow[$field]=$row[$field];}
if(!hgcf_valid_times($row['opening_time']??'',$row['closing_time']??''))return new WP_Error('flows','Controleer de begintijd en eindtijd van de workflow.');
$flow['opening_time']=$row['opening_time'];$flow['closing_time']=$row['closing_time'];
$service_mode=$row['service_mode']??($flow['service_mode']??'choices');if(!in_array($service_mode,['choices','amount'],true))return new WP_Error('flows','Controleer het type dienstenveld.');$flow['service_mode']=$service_mode;
$time_mode=$row['time_mode']??($flow['time_mode']??'exact');if(!in_array($time_mode,['exact','daypart','text'],true))return new WP_Error('flows','Controleer de tijdkeuze van de workflow.');$flow['time_mode']=$time_mode;
if($flow['time']!=='hidden'&&$time_mode==='daypart'&&!hgcf_dayparts($flow))return new WP_Error('flows','Er valt geen dagdeel binnen de ingestelde tijden.');
foreach(['label','subject','message_label','service_label','hint'] as $field) {if(!isset($row[$field])||!is_array($row[$field]))return new WP_Error('flows','Controleer de teksten van de workflow.');}
foreach(['label','subject','message_label','service_label','hint'] as $field)foreach($languages as $lang=>$name){
$value=$row[$field][$lang]??null;
if(!is_string($value)||strlen($value)>1500||($field!=='hint'&&trim($value)===''))return new WP_Error('flows','Vul de namen en labels van iedere actieve taal in.');
$flow[$field][$lang]=$field==='hint'?sanitize_textarea_field($value):sanitize_text_field($value);
}
$services=[];$service_rows=$row['services']??[];
if(!is_array($service_rows)||count($service_rows)>50)return new WP_Error('flows','Gebruik maximaal vijftig keuzemogelijkheden per workflow.');
foreach($service_rows as $entry){
if(!is_array($entry)||!isset($entry['labels'])||!is_array($entry['labels']))return new WP_Error('flows','Een keuzemogelijkheid is ongeldig.');
$key=$entry['id']??'';if(!is_string($key)||!preg_match('/^[a-z][a-z0-9_-]{0,39}$/',$key)||$key==='unsure'||isset($services[$key]))return new WP_Error('flows','Keuzemogelijkheden moeten unieke geldige codes hebben.');
$names=$flow['services'][$key]??[];
foreach($languages as $lang=>$name){$value=$entry['labels'][$lang]??'';if(!is_string($value)||trim($value)===''||strlen($value)>150)return new WP_Error('flows','Vul de naam van iedere keuzemogelijkheid in.');$names[$lang]=sanitize_text_field($value);}
$services[$key]=$names;
}
$flow['services']=$services;
if($flow['service']==='required'&&$flow['service_mode']==='choices'&&!$services)return new WP_Error('flows','Voeg keuzemogelijkheden toe wanneer de dienstenkeuze verplicht is.');
$flows[$id]=$flow;
}
if(!array_filter($flows,fn($flow)=>$flow['enabled']))return new WP_Error('flows','Houd minimaal één workflow ingeschakeld.');
return $flows;
}
function hgcf_sanitize_settings($input) {
$old=hgcf_settings();if(!is_array($input))return $old;
if(($_POST['option_page']??'')==='hgcf'&&($input['_complete']??'')!=='1'){add_settings_error('hgcf_settings','incomplete','Niet alle velden zijn ontvangen. Je instellingen zijn niet gewijzigd.');return $old;}
$out=$old;
foreach(['show_consent','show_note'] as $key)if(array_key_exists($key,$input)){if(in_array($input[$key],['0','1'],true))$out[$key]=$input[$key]==='1';else add_settings_error('hgcf_settings',$key,'Controleer de weergave-instelling.');}
if(array_key_exists('altcha_enabled',$input)) {
if(in_array($input['altcha_enabled'],['0','1'],true))$out['altcha_enabled']=$input['altcha_enabled']==='1';
else add_settings_error('hgcf_settings','altcha_enabled','Controleer de antispaminstelling.');
}
foreach(['recipient'=>false,'sender_email'=>true] as $key=>$empty){if(array_key_exists($key,$input)){if(hgcf_valid_email($input[$key],$empty))$out[$key]=$input[$key]===''?'':sanitize_email($input[$key]);else add_settings_error('hgcf_settings',$key,'Controleer het e-mailadres.');}}
foreach(['sender_name','site_name','contact_name'] as $key)if(array_key_exists($key,$input)) {
$value=$input[$key];if(is_string($value)&&strlen($value)<=150&&!preg_match('/[\r\n]/',$value)&&($key!=='site_name'||trim($value)!==''))$out[$key]=sanitize_text_field($value);else add_settings_error('hgcf_settings',$key,'Controleer de naam.');
}
foreach(hgcf_languages() as $lang=>$name)foreach(['title','consent','note','success'] as $key){$field=$key.'_'.$lang;if(array_key_exists($field,$input)){if(is_string($input[$field])&&strlen($input[$field])<=1500&&trim($input[$field])!=='')$out[$field]=sanitize_textarea_field($input[$field]);else add_settings_error('hgcf_settings',$field,'Vul de formulierteksten in.');}}
if(array_key_exists('workflows',$input)) {
$flows=hgcf_sanitize_workflows($input['workflows'],$old['workflows'],hgcf_languages());
if(is_wp_error($flows))add_settings_error('hgcf_settings','workflows',$flows->get_error_message());else $out['workflows']=$flows;
}
$out['schema_version']=2;
return $out; return $out;
} }
add_action('admin_menu',function(){add_menu_page('HG Contactformulier','Contactformulier','manage_options','hg-contactform','hgcf_admin_page','dashicons-email-alt',58);}); HG_Plugin_Admin::register(['slug'=>'hg-contactform','title'=>'HG Contactformulier','label'=>'Contactformulier','callback'=>'hgcf_admin_page','version'=>HGCF_VERSION,'description'=>'Contactformulieren, workflows en e-mailinstellingen beheren.']);
add_action('admin_init',function(){register_setting('hgcf','hgcf_settings',['type'=>'array','sanitize_callback'=>'hgcf_sanitize_settings','default'=>hgcf_defaults()]);}); add_action('admin_init',function(){register_setting('hgcf','hgcf_settings',['type'=>'array','sanitize_callback'=>'hgcf_sanitize_settings']);});
function hgcf_admin_page() { require_once __DIR__.'/admin.php';
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'],'sender_email'=>['Afzenderadres (optioneel)','email'],'sender_name'=>['Afzendernaam (optioneel)','text'],'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; ?>
<tr><th scope="row">Afzender en aflevering</th><td><p class="description">Gebruik een afzenderadres op een domein waarvoor jouw mailserver mag versturen. Laat het adres leeg om de bestaande standaardafzender te behouden. Reply-To blijft het adres van de bezoeker. Deze instelling wijzigt alleen formuliermails; het technische retouradres kan door de mailserver worden bepaald.</p></td></tr>
<?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
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2023 Daniel Regeci
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+37
View File
@@ -0,0 +1,37 @@
{
"name": "altcha-org/altcha",
"description": "A lightweight PHP library for creating and verifying ALTCHA challenges.",
"type": "library",
"license": "MIT",
"autoload": {
"psr-4": {
"AltchaOrg\\Altcha\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"AltchaOrg\\Altcha\\Tests\\": "tests/"
}
},
"authors": [
{
"name": "Daniel Regeci",
"email": "536331+ovx@users.noreply.github.com"
}
],
"require": {
"php": ">=8.1"
},
"require-dev": {
"phpunit/phpunit": "^10.5 || ^11.5",
"phpstan/phpstan": "^2.1",
"phpstan/phpstan-phpunit": "^2.0",
"phpstan/extension-installer": "^1.4",
"friendsofphp/php-cs-fixer": "^3.72"
},
"config": {
"allow-plugins": {
"phpstan/extension-installer": true
}
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
class Argon2id implements DeriveKeyInterface
{
public function getAlgorithmName(): string
{
return 'ARGON2ID';
}
public function deriveKey(
ChallengeParameters $parameters,
string $salt,
string $password,
): DeriveKeyResult {
if (!\function_exists('sodium_crypto_pwhash')) {
throw new \RuntimeException('ext-sodium is required for Argon2id.');
}
$cost = max(1, $parameters->cost);
$memoryCost = max(1, $parameters->memoryCost ?? 32768) * 1024;
$keyLength = max(0, $parameters->keyLength);
$derivedKey = sodium_crypto_pwhash(
$keyLength,
$password,
$salt,
$cost,
$memoryCost,
\SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13,
);
return new DeriveKeyResult($derivedKey);
}
}
@@ -0,0 +1,16 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
interface DeriveKeyInterface
{
public function getAlgorithmName(): string;
public function deriveKey(
ChallengeParameters $parameters,
string $salt,
string $password,
): DeriveKeyResult;
}
@@ -0,0 +1,14 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
class DeriveKeyResult
{
public function __construct(
public readonly string $derivedKey,
public readonly ?ChallengeParameters $parameterOverrides = null,
) {
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
use HGCFVendor\AltchaOrg\Altcha\HmacAlgorithm;
class Pbkdf2 implements DeriveKeyInterface
{
public function __construct(
private readonly HmacAlgorithm $hmacAlgorithm = HmacAlgorithm::SHA256,
) {
}
public function getAlgorithmName(): string
{
return 'PBKDF2/' . $this->hmacAlgorithm->value;
}
public function deriveKey(
ChallengeParameters $parameters,
string $salt,
string $password,
): DeriveKeyResult {
$cost = max(1, $parameters->cost);
$keyLength = max(0, $parameters->keyLength);
$derivedKey = hash_pbkdf2(
$this->hmacAlgorithm->hashAlgo(),
$password,
$salt,
$cost,
$keyLength,
true,
);
return new DeriveKeyResult($derivedKey);
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
class Scrypt implements DeriveKeyInterface
{
public function getAlgorithmName(): string
{
return 'SCRYPT';
}
public function deriveKey(
ChallengeParameters $parameters,
string $salt,
string $password,
): DeriveKeyResult {
if (!\function_exists('scrypt')) {
throw new \RuntimeException('ext-scrypt is required for Scrypt (https://github.com/DomBlack/php-scrypt).');
}
$cost = max(1, $parameters->cost);
$memoryCost = max(1, $parameters->memoryCost ?? 8);
$parallelism = max(1, $parameters->parallelism ?? 1);
$keyLength = max(0, $parameters->keyLength);
/** @var string $derivedKey */
$derivedKey = scrypt(
$password,
$salt,
$cost,
$memoryCost,
$parallelism,
$keyLength,
);
return new DeriveKeyResult($derivedKey);
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
use HGCFVendor\AltchaOrg\Altcha\ChallengeParameters;
class Sha implements DeriveKeyInterface
{
public function __construct(
private readonly ShaAlgorithm $algorithm = ShaAlgorithm::SHA256,
) {
}
public function getAlgorithmName(): string
{
return $this->algorithm->value;
}
public function deriveKey(
ChallengeParameters $parameters,
string $salt,
string $password,
): DeriveKeyResult {
$algo = $this->algorithm->hashAlgo();
$derivedKey = hash($algo, $salt . $password, true);
$cost = max(1, $parameters->cost);
for ($i = 1; $i < $cost; $i++) {
$derivedKey = hash($algo, $derivedKey, true);
}
if ($parameters->keyLength > 0 && $parameters->keyLength < \strlen($derivedKey)) {
$derivedKey = substr($derivedKey, 0, $parameters->keyLength);
}
return new DeriveKeyResult($derivedKey);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Algorithm;
enum ShaAlgorithm: string
{
case SHA1 = 'SHA-1';
case SHA256 = 'SHA-256';
case SHA384 = 'SHA-384';
case SHA512 = 'SHA-512';
public function hashAlgo(): string
{
return match ($this) {
self::SHA1 => 'sha1',
self::SHA256 => 'sha256',
self::SHA384 => 'sha384',
self::SHA512 => 'sha512',
};
}
}
+227
View File
@@ -0,0 +1,227 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
use HGCFVendor\AltchaOrg\Altcha\Algorithm\DeriveKeyInterface;
class Altcha
{
public function __construct(
private readonly ?string $hmacSignatureSecret = null,
private readonly ?string $hmacKeySignatureSecret = null,
private readonly HmacAlgorithm $hmacAlgorithm = HmacAlgorithm::SHA256,
) {
}
public function createChallenge(CreateChallengeOptions $options): Challenge
{
$nonce = $options->nonce ?? bin2hex(random_bytes(16));
$salt = $options->salt ?? bin2hex(random_bytes(16));
$params = new ChallengeParameters(
algorithm: $options->algorithm->getAlgorithmName(),
nonce: $nonce,
salt: $salt,
cost: $options->cost,
keyLength: $options->keyLength,
keyPrefix: $options->keyPrefix,
memoryCost: $options->memoryCost,
parallelism: $options->parallelism,
expiresAt: $options->expiresAt,
data: $options->data,
);
$keyPrefix = $params->keyPrefix;
$keySignature = null;
$keyPrefixLength = $options->keyPrefixLength ?? $params->keyLength / 2;
if (null !== $options->counter) {
$result = $this->deriveKeyForCounter($options->algorithm, $params, $options->counter);
$keyPrefix = bin2hex(substr($result, 0, $keyPrefixLength));
if (null !== $this->hmacKeySignatureSecret) {
$keySignature = $this->hmacHex($result, $this->hmacKeySignatureSecret);
}
} elseif (empty($keyPrefix)) {
// Generate a random prefix of the desired hex length
$keyPrefix = bin2hex(random_bytes(max(1, (int) $keyPrefixLength)));
}
$params = new ChallengeParameters(
algorithm: $params->algorithm,
nonce: $params->nonce,
salt: $params->salt,
cost: $params->cost,
keyLength: $params->keyLength,
keyPrefix: $keyPrefix,
keySignature: $keySignature,
memoryCost: $params->memoryCost,
parallelism: $params->parallelism,
expiresAt: $params->expiresAt,
data: $params->data,
);
$secret = $this->signatureSecret();
$signature = null !== $secret ? $this->hmacHex($params->toCanonicalJson(), $secret) : null;
return new Challenge($params, $signature);
}
public function solveChallenge(SolveChallengeOptions $options): ?Solution
{
$params = $options->challenge->parameters;
$nonceBytes = hex2bin($params->nonce) ?: '';
$saltBytes = hex2bin($params->salt) ?: '';
$keyPrefix = $params->keyPrefix;
$keyPrefixBytes = self::hexToBytes($keyPrefix);
$startTime = microtime(true);
$deadline = $startTime + $options->timeout;
$i = 0;
while (microtime(true) < $deadline) {
$counter = $options->start + ($i * $options->step);
$password = $nonceBytes . pack('N', $counter);
$result = $options->algorithm->deriveKey($params, $saltBytes, $password);
$derivedKey = $result->derivedKey;
if (self::hasKeyPrefix($derivedKey, $keyPrefix, $keyPrefixBytes)) {
$time = microtime(true) - $startTime;
return new Solution($counter, bin2hex($derivedKey), $time);
}
$i++;
}
return null;
}
public function verifySolution(VerifySolutionOptions $options): VerifySolutionResult
{
$startTime = microtime(true);
$payload = $options->payload;
$params = $payload->challenge->parameters;
// Check expiration: 0 means no expiry; fractional-second comparison, matching altcha-lib (JS)
if ($params->expiresAt) {
if ($params->expiresAt < microtime(true)) {
return new VerifySolutionResult(
verified: false,
expired: true,
time: microtime(true) - $startTime,
);
}
}
// Verify challenge signature. Like altcha-lib (JS) there is no unsigned mode: a missing
// signature, or a verifier without a signature secret, can never verify.
$secret = $this->signatureSecret();
$signature = $payload->challenge->signature;
try {
$canonicalJson = $params->toCanonicalJson();
} catch (\JsonException) {
$canonicalJson = null; // e.g. invalid UTF-8 in parameters passed as a PHP array
}
if (
null === $secret
|| null === $signature
|| null === $canonicalJson
|| !hash_equals($this->hmacHex($canonicalJson, $secret), $signature)
) {
return new VerifySolutionResult(
verified: false,
invalidSignature: true,
time: microtime(true) - $startTime,
);
}
// Fast path: the challenge carries an HMAC of the raw derived key bytes. A mismatch is final
// (no fallback to re-derivation), matching altcha-lib (JS).
if (null !== $params->keySignature && null !== $this->hmacKeySignatureSecret) {
$derivedKeyBytes = self::hexToBytes($payload->solution->derivedKey);
$verified = null !== $derivedKeyBytes
&& hash_equals($params->keySignature, $this->hmacHex($derivedKeyBytes, $this->hmacKeySignatureSecret));
return new VerifySolutionResult(
verified: $verified,
invalidSolution: $verified ? null : true,
time: microtime(true) - $startTime,
);
}
// Full re-derivation path
$nonceBytes = hex2bin($params->nonce) ?: '';
$saltBytes = hex2bin($params->salt) ?: '';
$password = $nonceBytes . pack('N', $payload->solution->counter);
$result = $options->algorithm->deriveKey($params, $saltBytes, $password);
$derivedKeyHex = bin2hex($result->derivedKey);
if (!hash_equals($derivedKeyHex, $payload->solution->derivedKey)) {
return new VerifySolutionResult(
verified: false,
invalidSolution: true,
time: microtime(true) - $startTime,
);
}
// Verify the derived key starts with the required prefix
$keyPrefix = $params->keyPrefix;
if (!self::hasKeyPrefix($result->derivedKey, $keyPrefix, self::hexToBytes($keyPrefix))) {
return new VerifySolutionResult(
verified: false,
invalidSolution: true,
time: microtime(true) - $startTime,
);
}
return new VerifySolutionResult(
verified: true,
time: microtime(true) - $startTime,
);
}
private function deriveKeyForCounter(DeriveKeyInterface $algorithm, ChallengeParameters $params, int $counter): string
{
$nonceBytes = hex2bin($params->nonce) ?: '';
$saltBytes = hex2bin($params->salt) ?: '';
$password = $nonceBytes . pack('N', $counter);
$result = $algorithm->deriveKey($params, $saltBytes, $password);
return $result->derivedKey;
}
/**
* An empty secret counts as unset, matching altcha-lib (JS).
*/
private function signatureSecret(): ?string
{
return '' === $this->hmacSignatureSecret ? null : $this->hmacSignatureSecret;
}
private function hmacHex(string $data, string $key): string
{
return bin2hex(hash_hmac($this->hmacAlgorithm->hashAlgo(), $data, $key, true));
}
/**
* Decodes an even-length hex string; returns null for anything else (no hex2bin warning).
*/
private static function hexToBytes(string $hex): ?string
{
return 1 === preg_match('/\A(?:[0-9a-fA-F]{2})*\z/', $hex) ? (string) hex2bin($hex) : null;
}
/**
* Even-length prefixes compare bytes; odd-length (half-byte) prefixes compare the lowercase
* hex string, matching altcha-lib (JS).
*/
private static function hasKeyPrefix(string $derivedKey, string $keyPrefix, ?string $keyPrefixBytes): bool
{
return null !== $keyPrefixBytes
? str_starts_with($derivedKey, $keyPrefixBytes)
: str_starts_with(bin2hex($derivedKey), $keyPrefix);
}
}
+48
View File
@@ -0,0 +1,48 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
class Challenge
{
public function __construct(
public readonly ChallengeParameters $parameters,
public readonly ?string $signature = null,
) {
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
$arr = ['parameters' => $this->parameters->toArray()];
if (null !== $this->signature) {
$arr['signature'] = $this->signature;
}
return $arr;
}
public function toJson(): string
{
return json_encode($this->toArray(), \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE) ?: '';
}
/**
* @param array<string, mixed> $arr
*/
public static function fromArray(array $arr): self
{
if (!isset($arr['parameters']) || !\is_array($arr['parameters'])) {
throw new \InvalidArgumentException('Invalid challenge data: expected "parameters" (array).');
}
/** @var array<string, mixed> $parameters */
$parameters = $arr['parameters'];
return new self(
parameters: ChallengeParameters::fromArray($parameters),
signature: isset($arr['signature']) && \is_string($arr['signature']) ? $arr['signature'] : null,
);
}
}
+222
View File
@@ -0,0 +1,222 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
class ChallengeParameters
{
/**
* @param null|array<array-key, mixed> $data JSON object; numeric-string keys become int keys in PHP
*/
public function __construct(
public readonly string $algorithm,
public readonly string $nonce,
public readonly string $salt,
public readonly int $cost,
public readonly int $keyLength = 32,
public readonly string $keyPrefix = '',
public readonly ?string $keySignature = null,
public readonly ?int $memoryCost = null,
public readonly ?int $parallelism = null,
public readonly int|float|null $expiresAt = null,
public readonly ?array $data = null,
) {
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
$arr = [
'algorithm' => $this->algorithm,
'cost' => $this->cost,
'keyLength' => $this->keyLength,
'keyPrefix' => $this->keyPrefix,
'nonce' => $this->nonce,
'salt' => $this->salt,
];
if (null !== $this->keySignature) {
$arr['keySignature'] = $this->keySignature;
}
if (null !== $this->memoryCost) {
$arr['memoryCost'] = $this->memoryCost;
}
if (null !== $this->parallelism) {
$arr['parallelism'] = $this->parallelism;
}
if (null !== $this->expiresAt) {
$arr['expiresAt'] = $this->expiresAt;
}
if (null !== $this->data) {
// `data` is a JSON object (JS: Record<string, …>); PHP can't tell `{}`/`{"0": …}` from a list.
$arr['data'] = array_is_list($this->data) ? (object) $this->data : $this->data;
}
ksort($arr);
return $arr;
}
/**
* Byte-for-byte equal to altcha-lib (JS) `JSON.stringify(sortKeys(parameters))`.
*
* @throws \JsonException if a string is not valid UTF-8
*/
public function toCanonicalJson(): string
{
return self::encodeCanonical($this->toArray());
}
/**
* @param bool $sortKeys false inside lists: JS `sortKeys()` returns arrays (and their contents) untouched
*/
private static function encodeCanonical(mixed $value, bool $sortKeys = true): string
{
if (\is_array($value) && array_is_list($value)) {
return '[' . implode(',', array_map(static fn (mixed $item): string => self::encodeCanonical($item, false), $value)) . ']';
}
if (\is_array($value) || $value instanceof \stdClass) {
$value = (array) $value;
// PHP turns numeric-string keys into ints; JS keys are always strings.
$keys = array_map(strval(...), array_keys($value));
usort($keys, static fn (string $a, string $b): int => self::compareKeys($a, $b, $sortKeys));
$members = array_map(
static fn (string $key): string => self::encodeCanonical($key) . ':' . self::encodeCanonical($value[$key], $sortKeys),
$keys,
);
return '{' . implode(',', $members) . '}';
}
if (\is_float($value) || (\is_int($value) && abs($value) > 2 ** 53)) {
return self::encodeJsNumber((float) $value);
}
return json_encode(
$value,
\JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_UNESCAPED_LINE_TERMINATORS | \JSON_THROW_ON_ERROR,
);
}
/**
* JS property enumeration order: array-index keys ("0"…"4294967294") first in numeric order, then the
* remaining keys sorted (objects rebuilt by `sortKeys()`) or in insertion order (stable `usort`).
*/
private static function compareKeys(string $a, string $b, bool $sortKeys): int
{
$aIndex = self::arrayIndex($a);
$bIndex = self::arrayIndex($b);
if (null !== $aIndex || null !== $bIndex) {
return (null === $aIndex ? 1 : 0) <=> (null === $bIndex ? 1 : 0) ?: $aIndex <=> $bIndex;
}
return $sortKeys ? self::compareUtf16($a, $b) : 0;
}
private static function arrayIndex(string $key): ?int
{
return 1 === preg_match('/\A(?:0|[1-9][0-9]{0,9})\z/', $key) && (int) $key <= 4294967294 ? (int) $key : null;
}
/**
* Compares UTF-8 strings in UTF-16 code unit order (JS `Array.prototype.sort`): identical to byte
* order except that U+E000–U+FFFF (lead bytes EE, EF) sorts after supplementary characters
* (lead bytes F0–F4, surrogate pairs in UTF-16).
*/
private static function compareUtf16(string $a, string $b): int
{
$common = strspn($a ^ $b, "\0");
if ($common === min(\strlen($a), \strlen($b))) {
return \strlen($a) <=> \strlen($b);
}
$x = \ord($a[$common]);
$y = \ord($b[$common]);
if ($x >= 0xEE && $y >= 0xEE) {
$x = $x < 0xF0 ? $x + 0x10 : $x;
$y = $y < 0xF0 ? $y + 0x10 : $y;
}
return $x <=> $y;
}
/**
* Formats a double like JS `Number.prototype.toString()`: shortest round-trip digits, plain notation
* for 1e-6 <= |n| < 1e21, otherwise `d[.ddd]e±x`.
*/
private static function encodeJsNumber(float $value): string
{
if (!is_finite($value)) {
return 'null';
}
if (0.0 === $value) {
return '0';
}
// Shortest digits that round-trip, as coefficient × 10^scale.
$abs = abs($value);
for ($precision = 0; $precision < 17; $precision++) {
[$mantissa, $exponent] = explode('e', \sprintf('%.' . $precision . 'e', $abs));
$scale = (int) $exponent - $precision;
$coefficient = (int) str_replace('.', '', $mantissa);
if ((float) ($coefficient . 'e' . $scale) === $abs) {
break;
}
// At exact powers of two the gap below is half the gap above: the nearest candidate can fail
// while the next one up round-trips, and JS picks that one.
if ((float) (($coefficient + 1) . 'e' . $scale) === $abs) {
$coefficient++;
break;
}
}
$sign = $value < 0 ? '-' : '';
$digits = rtrim((string) $coefficient, '0');
$k = \strlen($digits);
$n = $scale + \strlen((string) $coefficient);
if ($k <= $n && $n <= 21) {
return $sign . $digits . str_repeat('0', $n - $k);
}
if (0 < $n && $n <= 21) {
return $sign . substr($digits, 0, $n) . '.' . substr($digits, $n);
}
if (-6 < $n && $n <= 0) {
return $sign . '0.' . str_repeat('0', -$n) . $digits;
}
return $sign . $digits[0] . ($k > 1 ? '.' . substr($digits, 1) : '') . 'e' . ($n > 0 ? '+' : '-') . abs($n - 1);
}
/**
* @param array<string, mixed> $arr
*/
public static function fromArray(array $arr): self
{
$algorithm = isset($arr['algorithm']) && \is_string($arr['algorithm']) ? $arr['algorithm'] : '';
$nonce = isset($arr['nonce']) && \is_string($arr['nonce']) ? $arr['nonce'] : '';
$salt = isset($arr['salt']) && \is_string($arr['salt']) ? $arr['salt'] : '';
$cost = isset($arr['cost']) && \is_int($arr['cost']) ? $arr['cost'] : 0;
$keyLength = isset($arr['keyLength']) && \is_int($arr['keyLength']) ? $arr['keyLength'] : 32;
$keyPrefix = isset($arr['keyPrefix']) && \is_string($arr['keyPrefix']) ? $arr['keyPrefix'] : '';
$keySignature = isset($arr['keySignature']) && \is_string($arr['keySignature']) ? $arr['keySignature'] : null;
$memoryCost = isset($arr['memoryCost']) && \is_int($arr['memoryCost']) ? $arr['memoryCost'] : null;
$parallelism = isset($arr['parallelism']) && \is_int($arr['parallelism']) ? $arr['parallelism'] : null;
// JS issuers may send a fractional expiresAt (e.g. Date.now() / 1000 + 600); it is signed as-is.
$expiresAt = isset($arr['expiresAt']) && (\is_int($arr['expiresAt']) || \is_float($arr['expiresAt'])) ? $arr['expiresAt'] : null;
/** @var null|array<array-key, mixed> $data */
$data = isset($arr['data']) && (\is_array($arr['data']) || $arr['data'] instanceof \stdClass) ? (array) $arr['data'] : null;
return new self(
algorithm: $algorithm,
nonce: $nonce,
salt: $salt,
cost: $cost,
keyLength: $keyLength,
keyPrefix: $keyPrefix,
keySignature: $keySignature,
memoryCost: $memoryCost,
parallelism: $parallelism,
expiresAt: $expiresAt,
data: $data,
);
}
}
+32
View File
@@ -0,0 +1,32 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
use HGCFVendor\AltchaOrg\Altcha\Algorithm\DeriveKeyInterface;
class CreateChallengeOptions
{
public readonly int|float|null $expiresAt;
/**
* @param null|array<string, mixed> $data
*/
public function __construct(
public readonly DeriveKeyInterface $algorithm,
public readonly int $cost,
public readonly int $keyLength = 32,
public readonly string $keyPrefix = '00',
public readonly ?int $counter = null,
public readonly ?int $memoryCost = null,
public readonly ?int $parallelism = null,
\DateTimeInterface|int|float|null $expiresAt = null,
public readonly ?array $data = null,
public readonly ?string $nonce = null,
public readonly ?string $salt = null,
public readonly ?int $keyPrefixLength = null,
) {
$this->expiresAt = $expiresAt instanceof \DateTimeInterface
? $expiresAt->getTimestamp()
: $expiresAt;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
enum HmacAlgorithm: string
{
case SHA256 = 'SHA-256';
case SHA384 = 'SHA-384';
case SHA512 = 'SHA-512';
/**
* @return non-falsy-string
*/
public function hashAlgo(): string
{
return match ($this) {
self::SHA256 => 'sha256',
self::SHA384 => 'sha384',
self::SHA512 => 'sha512',
};
}
}
+11
View File
@@ -0,0 +1,11 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Http;
interface HttpClientInterface
{
/**
* @param array<string, string> $headers
*/
public function send(string $url, string $method, array $headers, string $body, float $timeout): HttpResponse;
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Http;
class HttpResponse
{
public function __construct(
public readonly int $statusCode,
public readonly string $body,
) {
}
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\Http;
/**
* Default HttpClientInterface implementation using PHP's built-in stream wrappers.
* Requires no additional extension or dependency.
*/
class StreamHttpClient implements HttpClientInterface
{
public function send(string $url, string $method, array $headers, string $body, float $timeout): HttpResponse
{
$headerLines = [];
foreach ($headers as $name => $value) {
$headerLines[] = $name . ': ' . $value;
}
$context = stream_context_create([
'http' => [
'method' => $method,
'header' => implode("\r\n", $headerLines),
'content' => $body,
'timeout' => $timeout,
'ignore_errors' => true,
],
]);
$errorMessage = null;
set_error_handler(static function (int $errno, string $errstr) use (&$errorMessage): bool {
$errorMessage = $errstr;
return true;
});
try {
$handle = fopen($url, 'r', false, $context);
} finally {
restore_error_handler();
}
if (false === $handle) {
throw new \RuntimeException($errorMessage ?? 'Network error while requesting Sentinel API.');
}
$responseBody = stream_get_contents($handle);
$meta = stream_get_meta_data($handle);
fclose($handle);
if (false === $responseBody) {
throw new \RuntimeException('Failed to read response from Sentinel API.');
}
$statusCode = 0;
/** @var list<string> $wrapperData */
$wrapperData = $meta['wrapper_data'] ?? [];
foreach ($wrapperData as $line) {
if (preg_match('#^HTTP/\S+\s+(\d+)#', $line, $matches)) {
$statusCode = (int) $matches[1];
}
}
return new HttpResponse($statusCode, $responseBody);
}
}
+125
View File
@@ -0,0 +1,125 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
use HGCFVendor\AltchaOrg\Altcha\Algorithm\DeriveKeyInterface;
use HGCFVendor\AltchaOrg\Altcha\Algorithm\Pbkdf2;
class Obfuscator
{
private const CIPHER = 'aes-256-gcm';
private const IV_LENGTH = 12;
private const TAG_LENGTH = 16;
private const DEFAULT_COST = 5000;
private const DEFAULT_KEY_PREFIX_LENGTH = 32;
private const DEFAULT_COUNTER_MIN = 20;
private const DEFAULT_COUNTER_MAX = 200;
public function __construct(
private readonly Altcha $altcha,
private readonly DeriveKeyInterface $algorithm = new Pbkdf2(),
) {
}
public function obfuscate(
string $data,
int $cost = self::DEFAULT_COST,
int $counterMin = self::DEFAULT_COUNTER_MIN,
int $counterMax = self::DEFAULT_COUNTER_MAX,
int $keyPrefixLength = self::DEFAULT_KEY_PREFIX_LENGTH,
): string {
$counter = random_int($counterMin, $counterMax);
$challenge = $this->altcha->createChallenge(new CreateChallengeOptions(
algorithm: $this->algorithm,
cost: $cost,
keyLength: 32,
keyPrefixLength: $keyPrefixLength,
counter: $counter,
));
// The full keyPrefix from challenge creation is the AES key (hex-encoded).
// Convert to raw bytes for AES-256-GCM (requires 32 bytes = 64 hex chars).
$fullKeyHex = $challenge->parameters->keyPrefix;
$aesKey = hex2bin($fullKeyHex) ?: throw new \RuntimeException('Invalid key prefix.');
// Encrypt the data with AES-256-GCM
$iv = random_bytes(self::IV_LENGTH);
$tag = '';
$ciphertext = openssl_encrypt($data, self::CIPHER, $aesKey, \OPENSSL_RAW_DATA, $iv, $tag, '', self::TAG_LENGTH);
if (false === $ciphertext) {
throw new \RuntimeException('Encryption failed.');
}
// Truncate the keyPrefix to half (the solver must brute-force the rest)
$truncatedKeyPrefix = substr($fullKeyHex, 0, $challenge->parameters->keyLength);
$params = new ChallengeParameters(
algorithm: $challenge->parameters->algorithm,
nonce: $challenge->parameters->nonce,
salt: $challenge->parameters->salt,
cost: $challenge->parameters->cost,
keyLength: $challenge->parameters->keyLength,
keyPrefix: $truncatedKeyPrefix,
memoryCost: $challenge->parameters->memoryCost,
parallelism: $challenge->parameters->parallelism,
);
$output = [
'parameters' => $params->toArray(),
'cipher' => [
'iv' => bin2hex($iv),
'data' => bin2hex($ciphertext . $tag),
],
];
return base64_encode(json_encode($output, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE) ?: '');
}
public function deobfuscate(
string $obfuscatedData,
float $timeout = 30.0,
): string {
$json = base64_decode($obfuscatedData, true);
if (false === $json) {
throw new \InvalidArgumentException('Unable to parse obfuscated data.');
}
/** @var null|array{parameters: array<string, mixed>, parameters: null|array<string, mixed>, cipher: null|array{iv: string, data: string}} $parsed */
$parsed = json_decode($json, true);
if (!\is_array($parsed) || !isset($parsed['parameters'], $parsed['cipher'])) {
throw new \InvalidArgumentException('Invalid obfuscated data format.');
}
$params = ChallengeParameters::fromArray($parsed['parameters']);
$challenge = new Challenge($params, null);
// Solve the challenge to recover the full derived key
$solution = $this->altcha->solveChallenge(new SolveChallengeOptions(
challenge: $challenge,
algorithm: $this->algorithm,
timeout: $timeout,
));
if (null === $solution) {
throw new \RuntimeException('Unable to find solution.');
}
// The full derived key (hex) is the AES key
$aesKey = hex2bin($solution->derivedKey) ?: throw new \RuntimeException('Invalid derived key.');
$iv = hex2bin($parsed['cipher']['iv']) ?: throw new \RuntimeException('Invalid cipher IV.');
$ciphertextWithTag = hex2bin($parsed['cipher']['data']) ?: throw new \RuntimeException('Invalid cipher data.');
// Separate ciphertext and GCM auth tag
$ciphertext = substr($ciphertextWithTag, 0, -self::TAG_LENGTH);
$tag = substr($ciphertextWithTag, -self::TAG_LENGTH);
$decrypted = openssl_decrypt($ciphertext, self::CIPHER, $aesKey, \OPENSSL_RAW_DATA, $iv, $tag);
if (false === $decrypted) {
throw new \RuntimeException('Decryption failed.');
}
return $decrypted;
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
class Payload
{
public function __construct(
public readonly Challenge $challenge,
public readonly Solution $solution,
) {
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'challenge' => $this->challenge->toArray(),
'solution' => $this->solution->toArray(),
];
}
public function toJson(): string
{
return json_encode($this->toArray(), \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE) ?: '';
}
public function toBase64(): string
{
return base64_encode($this->toJson());
}
/**
* @param array<string, mixed> $arr
*/
public static function fromArray(array $arr): self
{
if (!isset($arr['challenge'], $arr['solution']) || !\is_array($arr['challenge']) || !\is_array($arr['solution'])) {
throw new \InvalidArgumentException('Invalid payload data: expected "challenge" and "solution".');
}
/** @var array<string, mixed> $challenge */
$challenge = $arr['challenge'];
/** @var array<string, mixed> $solution */
$solution = $arr['solution'];
return new self(
challenge: Challenge::fromArray($challenge),
solution: Solution::fromArray($solution),
);
}
public static function fromBase64(string $payload): self
{
$decoded = base64_decode($payload, true);
if (false === $decoded) {
throw new \InvalidArgumentException('Invalid base64-encoded payload.');
}
try {
$data = json_decode($decoded, true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException $e) {
throw new \InvalidArgumentException('Invalid JSON in payload.', previous: $e);
}
if (!\is_array($data)) {
throw new \InvalidArgumentException('Invalid payload: expected a JSON object.');
}
/** @var array<string, mixed> $decodedData */
$decodedData = $data;
return self::fromArray($decodedData);
}
}
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
enum RetryBackoff
{
case Fixed;
case Exponential;
}
+73
View File
@@ -0,0 +1,73 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
use HGCFVendor\AltchaOrg\Altcha\Http\HttpResponse;
use HGCFVendor\AltchaOrg\Altcha\Http\StreamHttpClient;
class Sentinel
{
/**
* Verifies a payload remotely via the ALTCHA Sentinel `/v1/verify/signature` API,
* instead of verifying the HMAC signature locally.
*/
public static function verify(VerifyServerOptions $options): VerifyServerResult
{
$httpClient = $options->httpClient ?? new StreamHttpClient();
$body = ['payload' => $options->payload];
if (null !== $options->secret) {
$body['secret'] = $options->secret;
}
$bodyJson = json_encode($body, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE) ?: '{}';
$headers = ['Content-Type' => 'application/json', ...$options->headers];
for ($attempt = 0; $attempt <= $options->retries; $attempt++) {
try {
$response = $httpClient->send($options->url, 'POST', $headers, $bodyJson, $options->timeout);
return self::handleResponse($response);
} catch (\Throwable $e) {
if ($attempt >= $options->retries) {
return new VerifyServerResult(verified: false, reason: $e->getMessage());
}
$backoffMs = RetryBackoff::Fixed === $options->retryBackoff
? $options->retryDelay
: $options->retryDelay * 2 ** $attempt;
usleep($backoffMs * 1000);
}
}
return new VerifyServerResult(verified: false, reason: 'NETWORK_ERROR');
}
/**
* Interprets an HTTP response. Returns a terminal (non-retryable) VerifyServerResult,
* or throws to trigger the retry path for non-2xx/non-400 statuses and unparseable bodies.
*/
private static function handleResponse(HttpResponse $response): VerifyServerResult
{
if (400 === $response->statusCode) {
$data = json_decode($response->body, true);
$reason = \is_array($data) && isset($data['error']) && \is_string($data['error']) ? $data['error'] : 'HTTP_400';
return new VerifyServerResult(verified: false, reason: $reason);
}
if ($response->statusCode < 200 || $response->statusCode >= 300) {
throw new \RuntimeException('HTTP_' . $response->statusCode);
}
$data = json_decode($response->body, true);
if (!\is_array($data)) {
throw new \RuntimeException('Invalid JSON response from Sentinel API.');
}
/** @var array<string, mixed> $result */
$result = $data;
return VerifyServerResult::fromArray($result);
}
}
+168
View File
@@ -0,0 +1,168 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
class ServerSignature
{
/** @var list<string> */
private const ARRAY_KEYS = ['fields', 'reasons'];
/**
* @param array<array-key, mixed>|string $data
*/
public static function verifyServerSignature(
string|array $data,
string $hmacKey,
): ServerSignatureVerification {
$startTime = hrtime(true);
$payload = self::parsePayload($data);
if (!$payload) {
return new ServerSignatureVerification(
verified: false,
verificationData: null,
);
}
$hashAlgo = $payload['hmacAlgorithm']->hashAlgo();
$hash = hash($hashAlgo, $payload['verificationData'], true);
$expectedSignature = bin2hex(hash_hmac($hashAlgo, $hash, $hmacKey, true));
$verificationData = self::parseVerificationData($payload['verificationData']);
$invalidSignature = !hash_equals($expectedSignature, $payload['signature']);
$invalidSolution = !$payload['verified'] || !($verificationData['verified'] ?? false);
$expire = $verificationData['expire'] ?? null;
$expired = \is_int($expire) && $expire < time();
$verified = !$invalidSignature && !$invalidSolution && !$expired;
$elapsedTime = (hrtime(true) - $startTime) / 1e9;
return new ServerSignatureVerification(
verified: $verified,
verificationData: $verificationData,
expired: $expired,
invalidSignature: $invalidSignature,
invalidSolution: $invalidSolution,
time: $elapsedTime,
);
}
/**
* Parse URL-encoded verification data with auto type detection.
*/
public static function parseVerificationData(string $data): ServerSignatureVerificationData
{
parse_str($data, $params);
/** @var array<string, mixed> $result */
$result = [];
foreach ($params as $key => $value) {
$key = (string) $key;
if (!\is_string($value)) {
$result[$key] = $value;
continue;
}
if (\in_array($key, self::ARRAY_KEYS, true)) {
$result[$key] = '' !== $value ? explode(',', $value) : [];
continue;
}
if ('true' === $value) {
$result[$key] = true;
continue;
}
if ('false' === $value) {
$result[$key] = false;
continue;
}
if (preg_match('/^\d+$/', $value)) {
$result[$key] = (int) $value;
continue;
}
if (preg_match('/^\d+\.\d+$/', $value)) {
$result[$key] = (float) $value;
continue;
}
$result[$key] = $value;
}
return new ServerSignatureVerificationData($result);
}
/**
* @param array<string, mixed> $formData
* @param list<string> $fields
*/
public static function verifyFieldsHash(
array $formData,
array $fields,
string $fieldsHash,
HmacAlgorithm $hmacAlgorithm = HmacAlgorithm::SHA256,
): bool {
$lines = [];
foreach ($fields as $field) {
$value = $formData[$field] ?? null;
$lines[] = \is_scalar($value) ? (string) $value : '';
}
$joinedData = implode("\n", $lines);
$computedHash = hash($hmacAlgorithm->hashAlgo(), $joinedData);
return $computedHash === $fieldsHash;
}
/**
* @param array<array-key, mixed>|string $data
*
* @return null|array{hmacAlgorithm: HmacAlgorithm, verificationData: string, signature: string, verified: bool}
*/
private static function parsePayload(string|array $data): ?array
{
if (\is_string($data)) {
$decoded = base64_decode($data, true);
if (!$decoded) {
return null;
}
try {
$data = json_decode($decoded, true, 2, \JSON_THROW_ON_ERROR);
} catch (\JsonException|\ValueError) {
return null;
}
if (!\is_array($data) || empty($data)) {
return null;
}
}
if (!isset($data['algorithm'], $data['verificationData'], $data['signature'], $data['verified'])
|| !\is_string($data['algorithm'])
|| !\is_string($data['verificationData'])
|| !\is_string($data['signature'])
|| !\is_bool($data['verified'])
) {
return null;
}
$hmacAlgorithm = HmacAlgorithm::tryFrom($data['algorithm']);
if (!$hmacAlgorithm) {
return null;
}
return [
'hmacAlgorithm' => $hmacAlgorithm,
'verificationData' => $data['verificationData'],
'signature' => $data['signature'],
'verified' => $data['verified'],
];
}
}
@@ -0,0 +1,16 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
class ServerSignatureVerification
{
public function __construct(
public readonly bool $verified,
public readonly ?ServerSignatureVerificationData $verificationData,
public readonly bool $expired = false,
public readonly bool $invalidSignature = false,
public readonly bool $invalidSolution = false,
public readonly float $time = 0.0,
) {
}
}
@@ -0,0 +1,79 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
/**
* Generic verification data parsed from server signature payload.
*
* Supports property access ($data->key) and array access ($data['key']).
*
* @implements \ArrayAccess<string, mixed>
*
* @property mixed $verified
* @property mixed $expire
* @property mixed $score
* @property mixed $fields
* @property mixed $fieldsHash
* @property mixed $reasons
* @property mixed $classification
* @property mixed $country
* @property mixed $detectedLanguage
* @property mixed $email
* @property mixed $time
*/
class ServerSignatureVerificationData implements \ArrayAccess, \JsonSerializable
{
/**
* @param array<string, mixed> $data
*/
public function __construct(
private readonly array $data = [],
) {
}
public function __get(string $name): mixed
{
return $this->data[$name] ?? null;
}
public function __isset(string $name): bool
{
return isset($this->data[$name]);
}
public function offsetExists(mixed $offset): bool
{
return isset($this->data[$offset]);
}
public function offsetGet(mixed $offset): mixed
{
return $this->data[$offset] ?? null;
}
public function offsetSet(mixed $offset, mixed $value): void
{
throw new \LogicException('ServerSignatureVerificationData is read-only.');
}
public function offsetUnset(mixed $offset): void
{
throw new \LogicException('ServerSignatureVerificationData is read-only.');
}
/**
* @return array<string, mixed>
*/
public function jsonSerialize(): array
{
return $this->data;
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return $this->data;
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
class Solution
{
public function __construct(
public readonly int $counter,
public readonly string $derivedKey,
public readonly ?float $time = null,
) {
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
$arr = [
'counter' => $this->counter,
'derivedKey' => $this->derivedKey,
];
if (null !== $this->time) {
$arr['time'] = $this->time;
}
return $arr;
}
/**
* @param array<string, mixed> $arr
*/
public static function fromArray(array $arr): self
{
if (!isset($arr['counter'], $arr['derivedKey']) || !\is_int($arr['counter']) || !\is_string($arr['derivedKey'])) {
throw new \InvalidArgumentException('Invalid solution data: expected "counter" (int) and "derivedKey" (string).');
}
return new self(
counter: $arr['counter'],
derivedKey: $arr['derivedKey'],
time: isset($arr['time']) && is_numeric($arr['time']) ? (float) $arr['time'] : null,
);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
use HGCFVendor\AltchaOrg\Altcha\Algorithm\DeriveKeyInterface;
class SolveChallengeOptions
{
public function __construct(
public readonly Challenge $challenge,
public readonly DeriveKeyInterface $algorithm,
public readonly int $start = 0,
public readonly int $step = 1,
public readonly float $timeout = 30.0,
) {
}
}
+250
View File
@@ -0,0 +1,250 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Hasher;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\HasherInterface;
class Altcha
{
/**
* @param string $hmacKey Required HMAC key for challenge calculation and solution verification.
*/
public function __construct(
private readonly string $hmacKey,
private readonly HasherInterface $hasher = new Hasher(),
) {
}
/**
* @return null|array<array-key, mixed>
*/
private function decodePayload(string $payload): ?array
{
$decoded = base64_decode($payload, true);
if (!$decoded) {
return null;
}
try {
$data = json_decode($decoded, true, 2, \JSON_THROW_ON_ERROR);
} catch (\JsonException|\ValueError) {
return null;
}
if (!\is_array($data) || empty($data)) {
return null;
}
return $data;
}
/**
* @param array<array-key, mixed>|string $data
*/
private function verifyAndBuildSolutionPayload(string|array $data): ?Payload
{
if (\is_string($data)) {
$data = $this->decodePayload($data);
}
if (null === $data
|| !isset($data['algorithm'], $data['challenge'], $data['number'], $data['salt'], $data['signature'])
|| !\is_string($data['algorithm'])
|| !\is_string($data['challenge'])
|| !\is_int($data['number'])
|| !\is_string($data['salt'])
|| !\is_string($data['signature'])
) {
return null;
}
$algorithm = Algorithm::tryFrom($data['algorithm']);
if (!$algorithm) {
return null;
}
return new Payload($algorithm, $data['challenge'], $data['number'], $data['salt'], $data['signature']);
}
/**
* @param array<array-key, mixed>|string $data
*/
private function verifyAndBuildServerSignaturePayload(string|array $data): ?ServerSignaturePayload
{
if (\is_string($data)) {
$data = $this->decodePayload($data);
}
if (null === $data
|| !isset($data['algorithm'], $data['verificationData'], $data['signature'], $data['verified'])
|| !\is_string($data['algorithm'])
|| !\is_string($data['verificationData'])
|| !\is_string($data['signature'])
|| !\is_bool($data['verified'])
) {
return null;
}
$algorithm = Algorithm::tryFrom($data['algorithm']);
if (!$algorithm) {
return null;
}
return new ServerSignaturePayload($algorithm, $data['verificationData'], $data['signature'], $data['verified']);
}
/**
* Creates a new challenge for ALTCHA.
*
* @return Challenge The challenge data to be passed to ALTCHA.
*/
public function createChallenge(BaseChallengeOptions $options = new ChallengeOptions()): Challenge
{
$challenge = $this->hasher->hashHex($options->algorithm, $options->salt . $options->number);
$signature = $this->hasher->hashHmacHex($options->algorithm, $challenge, $this->hmacKey);
return new Challenge($options->algorithm->value, $challenge, $options->maxNumber, $options->salt, $signature);
}
/**
* Verifies an ALTCHA solution.
*
* @param array<array-key, mixed>|string $data The solution payload to verify.
* @param bool $checkExpires Whether to check if the challenge has expired.
*
* @return bool True if the solution is valid.
*/
public function verifySolution(string|array $data, bool $checkExpires = true): bool
{
$payload = $this->verifyAndBuildSolutionPayload($data);
if (!$payload) {
return false;
}
$params = $this->extractParams($payload);
if ($checkExpires && isset($params['expires']) && is_numeric($params['expires'])) {
$expireTime = (int) $params['expires'];
if (time() > $expireTime) {
return false;
}
}
$challengeOptions = new CheckChallengeOptions(
$payload->algorithm,
$payload->salt,
$payload->number
);
$expectedChallenge = $this->createChallenge($challengeOptions);
return $expectedChallenge->challenge === $payload->challenge
&& $expectedChallenge->signature === $payload->signature;
}
/**
* @return array<array-key, array<array-key, mixed>|string>
*/
private function extractParams(Payload $payload): array
{
$saltParts = explode('?', $payload->salt);
if (\count($saltParts) > 1) {
parse_str($saltParts[1], $params);
return $params;
}
return [];
}
/**
* Verifies the hash of form fields.
*
* @param array<string, mixed> $formData The form data to hash.
* @param list<string> $fields The fields to include in the hash.
* @param string $fieldsHash The expected hash value.
* @param Algorithm $algorithm Hashing algorithm (`SHA-1`, `SHA-256`, `SHA-512`).
*/
public function verifyFieldsHash(array $formData, array $fields, string $fieldsHash, Algorithm $algorithm): bool
{
$lines = [];
foreach ($fields as $field) {
$value = $formData[$field] ?? null;
$lines[] = \is_scalar($value) ? (string) $value : '';
}
$joinedData = implode("\n", $lines);
$computedHash = $this->hasher->hashHex($algorithm, $joinedData);
return $computedHash === $fieldsHash;
}
/**
* Verifies the server signature.
*
* @param array<array-key, mixed>|string $data The payload to verify (string or `ServerSignaturePayload` array).
*/
public function verifyServerSignature(string|array $data): ServerSignatureVerification
{
$payload = $this->verifyAndBuildServerSignaturePayload($data);
if (!$payload) {
return new ServerSignatureVerification(false, null);
}
$hash = $this->hasher->hash($payload->algorithm, $payload->verificationData);
$expectedSignature = $this->hasher->hashHmacHex($payload->algorithm, $hash, $this->hmacKey);
parse_str($payload->verificationData, $params);
$verificationData = new ServerSignatureVerificationData(
classification: isset($params['classification']) && \is_string($params['classification']) ? $params['classification'] : '',
country: isset($params['country']) && \is_string($params['country']) ? $params['country'] : '',
detectedLanguage: isset($params['detectedLanguage']) && \is_string($params['detectedLanguage']) ? $params['detectedLanguage'] : '',
email: isset($params['email']) && \is_string($params['email']) ? $params['email'] : '',
expire: isset($params['expire']) && is_numeric($params['expire']) ? (int) $params['expire'] : 0,
fields: isset($params['fields']) && \is_array($params['fields']) ? $params['fields'] : [],
fieldsHash: isset($params['fieldsHash']) && \is_string($params['fieldsHash']) ? $params['fieldsHash'] : '',
reasons: isset($params['reasons']) && \is_array($params['reasons']) ? $params['reasons'] : [],
score: isset($params['score']) && is_numeric($params['score']) ? (float) $params['score'] : 0.0,
time: isset($params['time']) && is_numeric($params['time']) ? (int) $params['time'] : 0,
verified: isset($params['verified']) && $params['verified'],
);
$now = time();
$isVerified = $payload->verified && $verificationData->verified
&& $verificationData->expire > $now
&& $payload->signature === $expectedSignature;
return new ServerSignatureVerification($isVerified, $verificationData);
}
/**
* Finds a solution to the given challenge.
*
* @param string $challenge The challenge hash.
* @param string $salt The challenge salt.
* @param Algorithm $algorithm Hashing algorithm.
* @param int $max Maximum number to iterate to.
* @param int $start Starting number.
*/
public function solveChallenge(string $challenge, string $salt, Algorithm $algorithm, int $max, int $start = 0): ?Solution
{
$startTime = microtime(true);
for ($n = $start; $n <= $max; $n++) {
$hash = $this->hasher->hashHex($algorithm, $salt . $n);
if ($hash === $challenge) {
$took = microtime(true) - $startTime;
return new Solution($n, $took);
}
}
return null;
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
/**
* @phpstan-type ChallengeParams array<string, null|scalar>
*/
class BaseChallengeOptions
{
public const DEFAULT_MAX_NUMBER = 1000000;
public readonly string $salt;
/**
* Options for creation of a new challenge.
*
* @see ChallengeOptions for options with sane defaults.
*
* @param ChallengeParams $params
*/
public function __construct(
public readonly Algorithm $algorithm,
public readonly int $maxNumber,
public readonly ?\DateTimeInterface $expires,
string $salt,
public readonly int $number,
public readonly array $params,
) {
if ($expires) {
$params['expires'] = $expires->getTimestamp();
}
if (!empty($params)) {
$salt .= '?' . http_build_query($params);
}
// Add a delimiter to prevent parameter splicing
if (!str_ends_with($salt, '&')) {
$salt .= '&';
}
$this->salt = $salt;
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
class Challenge
{
public function __construct(
public readonly string $algorithm,
public readonly string $challenge,
public readonly int $maxNumber,
public readonly string $salt,
public readonly string $signature,
) {
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
/**
* @phpstan-import-type ChallengeParams from BaseChallengeOptions
*/
class ChallengeOptions extends BaseChallengeOptions
{
private const DEFAULT_SALT_LENGTH = 12;
/**
* Options for creation of a new challenge with sane defaults.
*
* @param int $maxNumber Maximum number for the random number generator (default: 1,000,000)
* @param Algorithm $algorithm Hashing algorithm to use (`SHA-1`, `SHA-256`, `SHA-512`, default:
* `SHA-256`).
* @param null|\DateTimeInterface $expires Optional expiration time for the challenge.
* @param ChallengeParams $params Optional URL-encoded query parameters.
* @param int<1, max> $saltLength Length of the random salt (default: 12 bytes).
*/
public function __construct(
Algorithm $algorithm = Algorithm::SHA256,
int $maxNumber = self::DEFAULT_MAX_NUMBER,
?\DateTimeInterface $expires = null,
array $params = [],
int $saltLength = self::DEFAULT_SALT_LENGTH,
) {
parent::__construct(
$algorithm,
$maxNumber,
$expires,
bin2hex(self::randomBytes($saltLength)),
self::randomInt($maxNumber),
$params
);
}
private static function randomInt(int $max): int
{
return random_int(0, $max);
}
/**
* @param int<1, max> $length
*/
private static function randomBytes(int $length): string
{
return random_bytes($length);
}
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
class CheckChallengeOptions extends BaseChallengeOptions
{
public function __construct(
Algorithm $algorithm,
string $salt,
int $number,
) {
parent::__construct($algorithm, self::DEFAULT_MAX_NUMBER, null, $salt, $number, []);
}
}
+10
View File
@@ -0,0 +1,10 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1\Hasher;
enum Algorithm: string
{
case SHA1 = 'SHA-1';
case SHA256 = 'SHA-256';
case SHA512 = 'SHA-512';
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1\Hasher;
class Hasher implements HasherInterface
{
public function hash(Algorithm $algorithm, string $data): string
{
return match ($algorithm) {
Algorithm::SHA1 => sha1($data, true),
Algorithm::SHA256 => hash('sha256', $data, true),
Algorithm::SHA512 => hash('sha512', $data, true),
};
}
public function hashHex(Algorithm $algorithm, string $data): string
{
return bin2hex($this->hash($algorithm, $data));
}
public function hashHmac(Algorithm $algorithm, string $data, string $hmacKey): string
{
return match ($algorithm) {
Algorithm::SHA1 => hash_hmac('sha1', $data, $hmacKey, true),
Algorithm::SHA256 => hash_hmac('sha256', $data, $hmacKey, true),
Algorithm::SHA512 => hash_hmac('sha512', $data, $hmacKey, true),
};
}
public function hashHmacHex(Algorithm $algorithm, string $data, string $hmacKey): string
{
return bin2hex($this->hashHmac($algorithm, $data, $hmacKey));
}
}
@@ -0,0 +1,14 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1\Hasher;
interface HasherInterface
{
public function hash(Algorithm $algorithm, string $data): string;
public function hashHex(Algorithm $algorithm, string $data): string;
public function hashHmac(Algorithm $algorithm, string $data, string $hmacKey): string;
public function hashHmacHex(Algorithm $algorithm, string $data, string $hmacKey): string;
}
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Hasher;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\HasherInterface;
class Obfuscator
{
public const DEFAULT_MAX_NUMBER = 10_000;
/**
* @param int $maxNumber Maximum number for the random number generator (default: 10,000)
*/
public function __construct(
private readonly int $maxNumber = self::DEFAULT_MAX_NUMBER,
private readonly HasherInterface $hasher = new Hasher(),
) {
}
/**
* Encrypts a payload for PoW-based reveal using AES-GCM.
*
* @param string $raw Plaintext payload to encrypt.
* @param string $key Symmetric key used to encrypt/decrypt the payload. Defaults to empty string, ie. no key.
* @param null|int $counter Optional fixed PoW counter used to derive the IV. If null, a random integer in [0, $this->maxNumber] inclusive is chosen.
*
* @return string Base64-encoded bytes of ciphertext followed by the 16‑byte GCM authentication tag ($ciphertext . $tag).
*/
public function obfuscateData(string $raw, string $key = '', ?int $counter = null): string
{
$cipher = 'AES-256-GCM';
$keyHash = $this->hasher->hash(Algorithm::SHA256, $key);
$ivLength = openssl_cipher_iv_length($cipher);
if (false === $ivLength) {
throw new \RuntimeException('Getting cipher iv length failed.');
}
$iv = ''; // AES‑GCM initialization vector (IV), typically 12 bytes for AES-256-GCM
$num = $counter ?? $this->randomInt();
// Fill IV from the counter, one byte at a time (little‑endian)
for ($i = 0; $i < $ivLength; $i++) {
$iv .= \chr(abs($num % 256));
$num = intdiv($num, 256);
}
$encryptedData = openssl_encrypt($raw, $cipher, $keyHash, \OPENSSL_RAW_DATA, $iv, $tag);
if (!$encryptedData) {
throw new \RuntimeException('Data encryption failed.');
}
return base64_encode($encryptedData . $tag);
}
private function randomInt(): int
{
return random_int(0, $this->maxNumber);
}
}
+17
View File
@@ -0,0 +1,17 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
class Payload
{
public function __construct(
public readonly Algorithm $algorithm,
public readonly string $challenge,
public readonly int $number,
public readonly string $salt,
public readonly string $signature,
) {
}
}
@@ -0,0 +1,16 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
use HGCFVendor\AltchaOrg\Altcha\V1\Hasher\Algorithm;
class ServerSignaturePayload
{
public function __construct(
public readonly Algorithm $algorithm,
public readonly string $verificationData,
public readonly string $signature,
public readonly bool $verified,
) {
}
}
@@ -0,0 +1,12 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
class ServerSignatureVerification
{
public function __construct(
public readonly bool $verified,
public readonly ?ServerSignatureVerificationData $data,
) {
}
}
@@ -0,0 +1,25 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
class ServerSignatureVerificationData
{
/**
* @param array<array-key, mixed> $fields
* @param array<array-key, mixed> $reasons
*/
public function __construct(
public readonly string $classification,
public readonly string $country,
public readonly string $detectedLanguage,
public readonly string $email,
public readonly int $expire,
public readonly array $fields,
public readonly string $fieldsHash,
public readonly array $reasons,
public readonly float $score,
public readonly int $time,
public readonly bool $verified,
) {
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha\V1;
class Solution
{
public function __construct(
public readonly int $number,
public readonly float $took,
) {
}
}
+33
View File
@@ -0,0 +1,33 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
use HGCFVendor\AltchaOrg\Altcha\Http\HttpClientInterface;
class VerifyServerOptions
{
/**
* @param array<string, mixed>|string $payload The payload to verify, as received from the client
* (either the raw base64 string or a decoded array).
* @param string $url Full URL of the Sentinel `/v1/verify/signature` endpoint.
* @param null|string $secret API key secret. If provided, Sentinel checks that it
* matches the API key associated with the payload.
* @param null|HttpClientInterface $httpClient Custom HTTP client. Defaults to a built-in stream-based client.
* @param array<string, string> $headers Additional headers to send with the request.
* @param float $timeout Per-attempt request timeout in seconds. Defaults to `10.0`.
* @param int $retries Number of retry attempts after the first try. Defaults to `0`.
* @param int $retryDelay Base delay in milliseconds between retry attempts. Defaults to `300`.
*/
public function __construct(
public readonly array|string $payload,
public readonly string $url,
public readonly ?string $secret = null,
public readonly ?HttpClientInterface $httpClient = null,
public readonly array $headers = [],
public readonly float $timeout = 10.0,
public readonly int $retries = 0,
public readonly int $retryDelay = 300,
public readonly RetryBackoff $retryBackoff = RetryBackoff::Exponential,
) {
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
class VerifyServerResult
{
public function __construct(
public readonly bool $verified,
public readonly ?string $apiKey = null,
public readonly ?string $reason = null,
public readonly ?ServerSignatureVerificationData $verificationData = null,
) {
}
/**
* @param array<string, mixed> $arr
*/
public static function fromArray(array $arr): self
{
/** @var null|array<string, mixed> $verificationData */
$verificationData = isset($arr['verificationData']) && \is_array($arr['verificationData']) ? $arr['verificationData'] : null;
return new self(
verified: isset($arr['verified']) && \is_bool($arr['verified']) && $arr['verified'],
apiKey: isset($arr['apiKey']) && \is_string($arr['apiKey']) ? $arr['apiKey'] : null,
reason: isset($arr['reason']) && \is_string($arr['reason']) ? $arr['reason'] : null,
verificationData: null !== $verificationData ? new ServerSignatureVerificationData($verificationData) : null,
);
}
}
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
use HGCFVendor\AltchaOrg\Altcha\Algorithm\DeriveKeyInterface;
class VerifySolutionOptions
{
public readonly Payload $payload;
/**
* @param array<string, mixed>|Payload|string $payload A `Payload` object, a raw base64-encoded
* payload string (as posted by the widget),
* or an already-decoded associative array.
*/
public function __construct(
Payload|string|array $payload,
public readonly DeriveKeyInterface $algorithm,
) {
$this->payload = match (true) {
$payload instanceof Payload => $payload,
\is_string($payload) => Payload::fromBase64($payload),
default => Payload::fromArray($payload),
};
}
}
+15
View File
@@ -0,0 +1,15 @@
<?php
namespace HGCFVendor\AltchaOrg\Altcha;
class VerifySolutionResult
{
public function __construct(
public readonly bool $verified,
public readonly bool $expired = false,
public readonly ?bool $invalidSignature = null,
public readonly ?bool $invalidSolution = null,
public readonly float $time = 0.0,
) {
}
}
+61
View File
@@ -0,0 +1,61 @@
{
"widget": {
"version": "3.3.0",
"source": "https://registry.npmjs.org/altcha/-/altcha-3.3.0.tgz",
"integrity": "sha512-olIeb1A5K2wzbFSxV3qgeknygbdJt7qmzCfAZn704PWsE9iGrfc/oTw1FfiESjsvaJf8Uk6elJX8opKq5u7dTw=="
},
"php": {
"version": "2.3.0",
"source": "https://api.github.com/repos/altcha-org/altcha-lib-php/tarball/v2.3.0",
"archive_sha256": "3502eaaf884a04174324b432aaf2a3b7e98275a8482516e1ae6b4ab9c22343ec",
"namespace": "HGCFVendor\\AltchaOrg\\Altcha"
},
"files_sha256": {
"assets/vendor/altcha/LICENSE.txt": "bee1fb9d9c97d42c12c22332c5250f2fb1ef5c2321f6f82beb23e3b77be50a29",
"assets/vendor/altcha/widget.js": "6274613eb63f019f256327a371155710f17b1ff7d2b5cfcc8b8fa50e8dc056bc",
"includes/vendor/altcha/LICENSE.txt": "acf2b86dd7e2f5810c27d2f1c83a5bb4677d56b95249988586014fb2e818a695",
"includes/vendor/altcha/composer.json": "a915f93614e96ce4e62429a04fe7081e58f837606cf126fff1a41d19fafb8785",
"includes/vendor/altcha/src/Algorithm/Argon2id.php": "e407af4b7072764dc144e8636d765be18f3e1ee2a93b5e77d7df872c5867df65",
"includes/vendor/altcha/src/Algorithm/DeriveKeyInterface.php": "8b445c280607c9f1fdd9539308f1916c69c0024d63bc1b82a005c0171b403563",
"includes/vendor/altcha/src/Algorithm/DeriveKeyResult.php": "64a4a51fd52a5607f201a2d6cbf51c335dafdf3587be95a0f6d8cb67a7797afb",
"includes/vendor/altcha/src/Algorithm/Pbkdf2.php": "7220244a80e4689bdb0a3e0cb2dd35055e774e2c37257d85d081f05cf225cda8",
"includes/vendor/altcha/src/Algorithm/Scrypt.php": "7b19487042fcb30d0bbfbb44f535c535a041883f4a12a78730b5195eace6410f",
"includes/vendor/altcha/src/Algorithm/Sha.php": "c5f189334d1c784293507d9d7d92c42d3955a7b735e6f825c3f43310599af289",
"includes/vendor/altcha/src/Algorithm/ShaAlgorithm.php": "79355cd8e87a91eb6389896f29451e7e7a5a064f393185a39c22de44dec9af52",
"includes/vendor/altcha/src/Altcha.php": "635aba69ebb2a07c02729ed8af270370f0f0b52636d20561a0ee0ff5aeeabf53",
"includes/vendor/altcha/src/Challenge.php": "609343cce82d5305cd9c1c382b7f183f7b7888c68dc5975fccc09343cee2dec2",
"includes/vendor/altcha/src/ChallengeParameters.php": "fd439cf48246e587ff7ae70a010ee59c97d894d1f98fc6121d3e33125b51fee1",
"includes/vendor/altcha/src/CreateChallengeOptions.php": "3bccaea255abf5d75b2c5638f5e5830aad539c176c500e15ce916d7825795599",
"includes/vendor/altcha/src/HmacAlgorithm.php": "20154f3100275a6a0bdf9626d6b5e05590ca8486299f5f0fe2fafd257594403a",
"includes/vendor/altcha/src/Http/HttpClientInterface.php": "7f08599a4d842e197abb5d013fc3dade4328b6b21afc7d43d742ad810e9839a6",
"includes/vendor/altcha/src/Http/HttpResponse.php": "bdb407dda438d8c32465adf12d52d06be3646b8a5485297a26bcee7a8a7be47b",
"includes/vendor/altcha/src/Http/StreamHttpClient.php": "d985310e23f150eec2a8f57dd5d0e6e6f153c1faf1f1c56e16341ca424877cad",
"includes/vendor/altcha/src/Obfuscator.php": "9ddb78f1fbc98329abca53991b1969f53cc8eb81fa9d4463d3d61a4219566ca4",
"includes/vendor/altcha/src/Payload.php": "aaadea995193cd2ac5531343405c1e32cf501e2e943e330891b766b371cf959c",
"includes/vendor/altcha/src/RetryBackoff.php": "efe00dcf4bfb5fed52a9475009541fcd7c6f3f3c88f2054b8b31430206c61471",
"includes/vendor/altcha/src/Sentinel.php": "011f64a88f5268cf52aeff28376f31bbb0fbd95eacaba72fd217e5bb9cffc6ae",
"includes/vendor/altcha/src/ServerSignature.php": "4ae057926022703e8d33763125554fc031572f9983314039cb563620976a0d73",
"includes/vendor/altcha/src/ServerSignatureVerification.php": "1a95b0b24d967dd069a208b7215c041be64b7828838bd2b2da3361119a801050",
"includes/vendor/altcha/src/ServerSignatureVerificationData.php": "363ae141dcdbec12a13c6d7bc4c3ca28ae8cdf583853057e9d8888ca6070febe",
"includes/vendor/altcha/src/Solution.php": "637b1195cb573eccc67cc392d215af4c82dc1f0ec169f8e2bd040ec17d0b010f",
"includes/vendor/altcha/src/SolveChallengeOptions.php": "1d6a728e6f04f7058fa3e0320a3ba2c2b28eeb6097e32b7fd10c4ba514a1d3bc",
"includes/vendor/altcha/src/V1/Altcha.php": "470dad3632f5bb2ef857a168b32407ac63308be4e759a725e946aa07e803b880",
"includes/vendor/altcha/src/V1/BaseChallengeOptions.php": "9fa61ab32a62af89ab7cb0e7623fe1bf3ea1ffe82a23fe0a325f25647eb68a39",
"includes/vendor/altcha/src/V1/Challenge.php": "c5704fea061441c012d4aa837136a5acb15ae579346aa7ee46fedae8a3284a86",
"includes/vendor/altcha/src/V1/ChallengeOptions.php": "b295d10301476b04a946396e9a02b72c20fcddacbae894afbb472862cf2530c8",
"includes/vendor/altcha/src/V1/CheckChallengeOptions.php": "f869a628f66e859922d23fc119a3fb04fdcff8dc7ed2603d0d37eff229a443f1",
"includes/vendor/altcha/src/V1/Hasher/Algorithm.php": "e1bc0d28c3e7f0a1e00e0b5f551ffad924094a1d464df3b1e04eb57e3acb9fb7",
"includes/vendor/altcha/src/V1/Hasher/Hasher.php": "be03a781c72c7e40d4c80d061631fb97d59ca2e53e74371d7ab905918352332d",
"includes/vendor/altcha/src/V1/Hasher/HasherInterface.php": "1f5d6a64019dca688d5751b69395ae3fe705fbe4410ad172ebf88057cb4c6a12",
"includes/vendor/altcha/src/V1/Obfuscator.php": "b24d07a7156de21d1627299aa1e2003784301aa8a7b4721433c8e1c7b33becd5",
"includes/vendor/altcha/src/V1/Payload.php": "2d049bb73b5c24718e6ef431dcca41e027be0a3ddc84c804458bca0bc339802f",
"includes/vendor/altcha/src/V1/ServerSignaturePayload.php": "595d5875d3f40df21d4b5c4cebdad1e57bc58184232aa1c84fd478802f343256",
"includes/vendor/altcha/src/V1/ServerSignatureVerification.php": "b0349710a68dc4c83136d4b9a97b3ed59a0ce9abe41758f5621aef4ca1d04035",
"includes/vendor/altcha/src/V1/ServerSignatureVerificationData.php": "1a5370c6dfadbcf9afc3e681ae34c14b7224c91263e91133b947516ddb24661d",
"includes/vendor/altcha/src/V1/Solution.php": "6496aaaacab8daf98bdbb21267ad7f37f9f0780db94ec3eee709c03b1a3c0ec8",
"includes/vendor/altcha/src/VerifyServerOptions.php": "7f108d0a5075786d84a0624214b98a7462a7bf0bad136a29d5b5d486be5f3c8d",
"includes/vendor/altcha/src/VerifyServerResult.php": "1445552daab68d643b95f22a688fc4a39f0b27832c57be6f46b144c6006ff685",
"includes/vendor/altcha/src/VerifySolutionOptions.php": "4ca88774e3e5e44bda93bae728dc77ff61fab06ed24b4f9ae526571bc7873523",
"includes/vendor/altcha/src/VerifySolutionResult.php": "36d1a9c67b6325f5fee79e82f0a69fb088374dff5babebac2dee749728a0d769"
}
}
+26 -4
View File
@@ -1,15 +1,37 @@
=== HG Contactformulier === === HG Contactformulier ===
Requires at least: 6.5 Requires at least: 6.5
Requires PHP: 8.0 Requires PHP: 8.1
Stable tag: 1.1.0 Stable tag: 1.5.0
License: GPLv2 or later License: GPLv2 or later
Configureerbaar NL/EN-contactformulier met vraagmodus en optionele afspraakaanvragen. Contactformulier met workflows, talen en optionele lokaal gehoste ALTCHA-antispamcontrole.
== Installation == == Installation ==
Upload en activeer de plugin. Stel Contactformulier in de beheerzijbalk in en plaats [hg_contactform] op een pagina. Upload en activeer de plugin. Stel HG Plugins → Contactformulier in de beheerzijbalk in en plaats [hg_contactform] op een pagina.
== Changelog == == Changelog ==
= 1.5.0 =
Per workflow een vrij eurobedrag of keuzelijst, en vrije tekst voor meerdere voorkeursmomenten naast de bestaande tijd- en dagdeelkeuze.
= 1.4.2 =
Openbare releases controleren via HG Plugins → Updates.
= 1.4.1 =
Een actieve workflow vooraf kiezen via de contactlink; ongeldige keuzes vallen veilig terug op de standaard.
= 1.4.0 =
Tijdvoorkeur per workflow instelbaar als exact tijdstip of dagdeel. De neutrale massagekeuze staat onderaan.
= 1.3.4 =
Toestemmingsvinkje en toelichting per website aan- of uitzetten; validatie volgt de weergave-instelling.
= 1.3.3 =
HG Plugins-menu met herkenbare zijbalkkleur, gedeeld overzicht en behoud van bestaande beheerlinks.
= 1.3.2 =
Gebruik de effectieve WordPress-sitetaal, ook wanneer de WPLANG-optie ontbreekt of afwijkt van de ingestelde locale.
= 1.3.1 =
Beknopte antispaminstelling en een apart informatietabblad met gebruikte techniek en actuele versies.
= 1.3.0 =
Optionele lokale ALTCHA-controle zonder externe diensten, met verlopen en eenmalige uitdagingen. PHP 8.1 of hoger vereist.
= 1.2.0 =
Nieuw beheer met tabs, meerdere configureerbare workflows, invoerrijen voor diensten en talen vanuit Polylang of de WordPress-sitetaal. Bestaande instellingen worden behouden.
= 1.1.0 = = 1.1.0 =
Configureerbaar afzenderadres en afzendernaam voor formuliermails, met behouden Reply-To en header-validatie. Configureerbaar afzenderadres en afzendernaam voor formuliermails, met behouden Reply-To en header-validatie.
= 1.0.0 = = 1.0.0 =
+3
View File
@@ -2,7 +2,10 @@
"""Build a WordPress-installable ZIP from this checkout.""" """Build a WordPress-installable ZIP from this checkout."""
from pathlib import Path from pathlib import Path
import zipfile import zipfile
from sync_shared import verify_shared
root=Path(__file__).resolve().parents[1] root=Path(__file__).resolve().parents[1]
verify_shared(root)
destination=root/'dist/hg-contactform.zip' destination=root/'dist/hg-contactform.zip'
destination.parent.mkdir(exist_ok=True) destination.parent.mkdir(exist_ok=True)
files=[root/'hg-contactform.php',root/'readme.txt',root/'LICENSE'] files=[root/'hg-contactform.php',root/'readme.txt',root/'LICENSE']
+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)
+82
View File
@@ -0,0 +1,82 @@
#!/usr/bin/env python3
"""Vendor pinned official ALTCHA releases; --check only reports available versions."""
import argparse
import base64
import hashlib
import io
import json
from pathlib import Path
import tarfile
from urllib.request import Request, urlopen
ROOT = Path(__file__).resolve().parents[1]
MANIFEST = ROOT / 'includes/vendor/altcha/versions.json'
def fetch(url):
with urlopen(Request(url, headers={'User-Agent': 'HG-Contactform-dependency-update'}), timeout=30) as response:
return response.read()
def members(blob):
with tarfile.open(fileobj=io.BytesIO(blob), mode='r:gz') as archive:
return {member.name: archive.extractfile(member).read() for member in archive if member.isfile()}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true')
parser.add_argument('--widget-version')
parser.add_argument('--php-version')
args = parser.parse_args()
if args.check:
current = json.loads(MANIFEST.read_text())
widget = json.loads(fetch('https://registry.npmjs.org/altcha/latest'))['version']
php = json.loads(fetch('https://api.github.com/repos/altcha-org/altcha-lib-php/releases/latest'))['tag_name'].removeprefix('v')
print(f"Widget: installed {current['widget']['version']}, latest {widget}")
print(f"PHP: installed {current['php']['version']}, latest {php}")
return
if not args.widget_version or not args.php_version:
parser.error('Supply both explicit versions; no automatic upgrades.')
import re
if any(not re.fullmatch(r'\d+\.\d+\.\d+', value) for value in (args.widget_version, args.php_version)):
parser.error('Use stable x.y.z versions.')
metadata = json.loads(fetch(f'https://registry.npmjs.org/altcha/{args.widget_version}'))
widget_url = metadata['dist']['tarball']
widget_blob = fetch(widget_url)
integrity = 'sha512-' + base64.b64encode(hashlib.sha512(widget_blob).digest()).decode()
if integrity != metadata['dist']['integrity']:
raise RuntimeError('NPM integrity mismatch')
php_url = f'https://api.github.com/repos/altcha-org/altcha-lib-php/tarball/v{args.php_version}'
php_blob = fetch(php_url)
widget_files, php_files = members(widget_blob), members(php_blob)
outputs = {
'assets/vendor/altcha/widget.js': widget_files['package/dist/main/altcha.i18n.min.js'],
'assets/vendor/altcha/LICENSE.txt': widget_files['package/LICENSE.txt'],
}
for name, data in php_files.items():
relative = name.split('/', 1)[1]
if relative.startswith('src/') and relative.endswith('.php'):
# Private namespace avoids conflicts with other WordPress plugins.
outputs['includes/vendor/altcha/' + relative] = data.replace(b'AltchaOrg\\Altcha', b'HGCFVendor\\AltchaOrg\\Altcha')
elif relative in ('LICENSE.txt', 'composer.json'):
outputs['includes/vendor/altcha/' + relative] = data
if 'includes/vendor/altcha/src/Altcha.php' not in outputs:
raise RuntimeError('Missing PHP library entry point')
# Parse and validate both archives completely before replacing vendored files.
php_source = ROOT / 'includes/vendor/altcha/src'
if php_source.exists():
for old in php_source.rglob('*.php'):
if str(old.relative_to(ROOT)) not in outputs:
old.unlink()
for relative, data in outputs.items():
path = ROOT / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
manifest = {
'widget': {'version': args.widget_version, 'source': widget_url, 'integrity': integrity},
'php': {'version': args.php_version, 'source': php_url, 'archive_sha256': hashlib.sha256(php_blob).hexdigest(), 'namespace': 'HGCFVendor\\AltchaOrg\\Altcha'},
'files_sha256': {name: hashlib.sha256(data).hexdigest() for name, data in sorted(outputs.items())},
}
MANIFEST.write_text(json.dumps(manifest, indent=2) + '\n')
print('ALTCHA bundled. Review diff, run security/browser tests, then build the plugin ZIP.')
if __name__ == '__main__':
main()
+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"
}
}
+65
View File
@@ -0,0 +1,65 @@
<?php
if(!defined('WP_CLI')||!WP_CLI)exit;
function hgcf_pow_assert($ok,$label){if(!$ok)WP_CLI::error($label);WP_CLI::log('PASS '.$label);}
function hgcf_pow_solve($challenge){
$c=HGCFVendor\AltchaOrg\Altcha\Challenge::fromArray($challenge);
$solution=hgcf_altcha_engine()->solveChallenge(new HGCFVendor\AltchaOrg\Altcha\SolveChallengeOptions(
challenge:$c,algorithm:new HGCFVendor\AltchaOrg\Altcha\Algorithm\Pbkdf2(),timeout:20
));
hgcf_pow_assert($solution!==null,'official PHP solver solves generated challenge');
return (new HGCFVendor\AltchaOrg\Altcha\Payload($c,$solution))->toBase64();
}
$original=hgcf_settings();$config=$original;$override=function()use(&$config){return $config;};add_filter('pre_option_hgcf_settings',$override);
$config['altcha_enabled']=true;
$challenge=hgcf_create_altcha_challenge(42);$valid=hgcf_pow_solve($challenge);
foreach(['',[],str_repeat('A',8193),'invalid',base64_encode('{}'),base64_encode('{"challenge":[]}')] as $raw)hgcf_pow_assert(!hgcf_verify_altcha($raw,42),'malformed or missing proof rejected');
hgcf_pow_assert(!hgcf_verify_altcha($valid,43),'proof bound to its form page');
foreach(['signature','cost','derivedKey','expiresAt','page','keySignature','counter'] as $field){
$tampered=json_decode(base64_decode($valid),true);
if($field==='signature')$tampered['challenge']['signature']=str_repeat('0',64);
elseif($field==='derivedKey')$tampered['solution']['derivedKey']=str_repeat('0',64);
elseif($field==='counter')$tampered['solution']['counter']=1000001;
elseif($field==='page')$tampered['challenge']['parameters']['data']['page']=43;
else $tampered['challenge']['parameters'][$field]=match($field){'cost'=>1000000000,'expiresAt'=>time()-1,default=>str_repeat('0',64)};
hgcf_pow_assert(!hgcf_verify_altcha(base64_encode(wp_json_encode($tampered)),42),'tampered '.$field.' rejected');
}
hgcf_pow_assert(hgcf_verify_altcha($valid,42),'valid proof accepted');
hgcf_pow_assert(!hgcf_verify_altcha($valid,42),'replayed proof rejected');
$used='hgcf_pow_used_'.hash('sha256',$challenge['signature']);delete_option($used);
$expired=hgcf_altcha_engine()->createChallenge(new HGCFVendor\AltchaOrg\Altcha\CreateChallengeOptions(
algorithm:new HGCFVendor\AltchaOrg\Altcha\Algorithm\Pbkdf2(),cost:1000,keyPrefix:'00',expiresAt:time()-1,data:['page'=>42]
));
hgcf_pow_assert(!hgcf_verify_altcha(hgcf_pow_solve($expired->toArray()),42),'authentic expired proof rejected');
$cleanup='hgcf_pow_used_'.hash('sha256','hgcf-test-expired');add_option($cleanup,time()-1,'',false);hgcf_altcha_cleanup();hgcf_pow_assert(get_option($cleanup)===false,'expired replay record cleaned');
$pages=get_posts(['post_type'=>['page','post'],'post_status'=>'publish','numberposts'=>-1]);$page=null;
foreach($pages as $post)if(has_shortcode($post->post_content,'hg_contactform')||has_shortcode($post->post_content,'mlh_contact')){$page=$post;break;}
hgcf_pow_assert($page!==null,'existing public form page found');
query_posts(['page_id'=>$page->ID]);
$savedPost=$_POST;$savedServer=$_SERVER;$_SERVER['REMOTE_ADDR']='192.0.2.123';$_SERVER['REQUEST_METHOD']='POST';
$ipKey='hgcf_pow_rate_'.hash_hmac('sha256',$_SERVER['REMOTE_ADDR'],wp_salt('auth'));delete_transient($ipKey);
$request=new WP_REST_Request('GET','/hg-contactform/v1/challenge');$request->set_param('page',$page->ID);
$response=hgcf_altcha_endpoint($request);hgcf_pow_assert($response instanceof WP_REST_Response&&$response->get_status()===200&&str_contains($response->get_headers()['Cache-Control'],'no-store'),'public challenge endpoint and no-cache');
$endpointChallenge=$response->get_data();$proof=hgcf_pow_solve($endpointChallenge);
$request->set_param('page',999999999);hgcf_pow_assert(is_wp_error(hgcf_altcha_endpoint($request)),'non-form page rejected');$request->set_param('page',$page->ID);
set_transient($ipKey,['count'=>30,'until'=>time()+300],300);hgcf_pow_assert(hgcf_altcha_endpoint($request)->get_error_data()['status']===429,'challenge rate limit');delete_transient($ipKey);
$config['altcha_enabled']=false;hgcf_pow_assert(hgcf_altcha_endpoint($request)->get_error_data()['status']===404,'disabled challenge endpoint');ob_start();$off=hgcf_render();ob_end_clean();hgcf_pow_assert(!str_contains($off,'altcha-widget'),'disabled feature has no widget');
$config['altcha_enabled']=true;ob_start();$on=hgcf_render(['lang'=>'nl']);ob_end_clean();hgcf_pow_assert(str_contains($on,'altcha-widget')&&str_contains($on,'language="nl"'),'enabled localized widget');
$config['workflows']=['question'=>hgcf_workflow_defaults()];$config['recipient']='recipient@example.com';
$start=(string)(time()-3);$_POST=['mlhc_action'=>'send','mlhc_nonce'=>wp_create_nonce('hgcf_send'),'mlhc_started'=>$start,'mlhc_signature'=>hash_hmac('sha256',$start,wp_salt('nonce')),'mlhc_name'=>'Test Visitor','mlhc_email'=>'visitor@example.com','mlhc_mode'=>'question','mlhc_message'=>'Integration test without email delivery','mlhc_consent'=>'1'];
$sent=[];$mock=function($result,$atts)use(&$sent){$sent[]=$atts;return true;};add_filter('pre_wp_mail',$mock,PHP_INT_MAX,2);
$rateKey='mlhc_rate_'.hash_hmac('sha256',$_SERVER['REMOTE_ADDR'],wp_salt('auth'));delete_transient($rateKey);
unset($GLOBALS['mlhc_errors']);hgcf_handle_submission();hgcf_pow_assert(count($sent)===0&&($GLOBALS['mlhc_errors']->get_error_code()??'')==='altcha','real handler rejects missing proof before mail');
$_POST['mlhc_altcha']='invalid';unset($GLOBALS['mlhc_errors']);hgcf_handle_submission();hgcf_pow_assert(count($sent)===0&&$GLOBALS['mlhc_errors']->get_error_code()==='altcha','real handler rejects forged proof');
$_POST['mlhc_altcha']=$proof;unset($GLOBALS['mlhc_errors']);
$redirect=function($location){throw new RuntimeException('hgcf-test-redirect');};add_filter('wp_redirect',$redirect);
try{hgcf_handle_submission();}catch(RuntimeException $e){hgcf_pow_assert($e->getMessage()==='hgcf-test-redirect','successful handler redirects');}
remove_filter('wp_redirect',$redirect);
hgcf_pow_assert(count($sent)===1&&!isset($GLOBALS['mlhc_errors']),'valid proof reaches mock mail');
delete_transient($rateKey);hgcf_handle_submission();hgcf_pow_assert(count($sent)===1&&$GLOBALS['mlhc_errors']->get_error_code()==='altcha','handler rejects replay before mail');
delete_option('hgcf_pow_used_'.hash('sha256',$endpointChallenge['signature']));delete_transient($rateKey);delete_transient($ipKey);
remove_filter('pre_wp_mail',$mock,PHP_INT_MAX);$_POST=$savedPost;$_SERVER=$savedServer;unset($GLOBALS['mlhc_errors']);wp_reset_query();
$config=$original;$out=hgcf_sanitize_settings(['altcha_enabled'=>'1']);hgcf_pow_assert($out['altcha_enabled']===true,'enable via settings');$out=hgcf_sanitize_settings(['altcha_enabled'=>'0']);hgcf_pow_assert($out['altcha_enabled']===false,'disable via settings');
$out=hgcf_sanitize_settings(['altcha_enabled'=>['bad']]);hgcf_pow_assert($out['altcha_enabled']===$original['altcha_enabled'],'malformed setting preserves value');
remove_filter('pre_option_hgcf_settings',$override);
WP_CLI::success('ALTCHA verification, replay protection, endpoint and real handler passed; no email sent.');
+91
View File
@@ -0,0 +1,91 @@
// Usage: HGCF_BASE_URL=https://test.example PLAYWRIGHT_MODULE=/path/to/playwright node tests/browser.cjs /contact/ /en/contact/
// Valid form POSTs are intercepted in the browser; they never reach the mail handler.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const base = process.env.HGCF_BASE_URL;
if (!base || process.argv.length < 3) throw new Error('Provide HGCF_BASE_URL and contact page paths.');
const artifacts = process.env.HGCF_ARTIFACTS || '/tmp/hg-contact-browser';
fs.mkdirSync(artifacts, { recursive: true, mode: 0o700 });
(async () => {
const browser = await chromium.launch({ headless: true, ...(process.env.HGCF_BROWSER_EXECUTABLE ? { executablePath: process.env.HGCF_BROWSER_EXECUTABLE } : {}) });
const proofs = [];
try {
for (const [index, route] of process.argv.slice(2).entries()) {
for (const mobile of [false, true]) {
const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 } });
const page = await context.newPage();
const errors = []; const requests = []; let submitted = null;
page.on('pageerror', error => errors.push(error.message));
page.on('request', request => requests.push(request.url()));
const url = new URL(route, base).href;
await page.route('**/*', async handler => {
const request = handler.request();
if (request.method() === 'POST' && new URL(request.url()).pathname === new URL(url).pathname) {
submitted = Object.fromEntries(new URLSearchParams(request.postData()));
await handler.fulfill({ status: 200, contentType: 'text/html', body: '<p>Test POST intercepted; no mail sent.</p>' });
} else await handler.continue();
});
const response = await page.goto(url, { waitUntil: 'networkidle' });
assert.equal(response.status(), 200);
await page.waitForFunction(() => !!customElements.get('altcha-widget'));
const widget = page.locator('altcha-widget');
assert.equal(await widget.count(), 1);
const lang = await widget.getAttribute('language');
assert.equal(await page.locator('script#hgcf-altcha-js').getAttribute('type'), 'module');
const challengeURL = await widget.getAttribute('challenge');
assert.equal(new URL(challengeURL).origin, new URL(base).origin);
assert(await page.locator('.mlhc-form').evaluate(form => !form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }))));
assert.equal(await page.locator('.mlhc-form button[type=submit]').isDisabled(), false);
await page.locator('[name=mlhc_name]').fill('Test Visitor');
await page.locator('[name=mlhc_email]').fill('visitor@example.com');
await page.locator('[name=mlhc_message]').fill('Browser verification test intercepted before delivery.');
if(await page.locator('[name=mlhc_consent]').count())await page.locator('[name=mlhc_consent]').check();
await page.waitForFunction(() => {
const input = document.querySelector('.mlhc-form input[name=mlhc_altcha]');
return !!input?.value;
}, null, { timeout: 45000 }).catch(async error => {
console.error('Widget diagnostic', await widget.textContent(), errors);
await page.screenshot({ path: path.join(artifacts, 'failure.png'), fullPage: true });
throw error;
});
const proof = await page.locator('input[name=mlhc_altcha]').inputValue();
const decoded = JSON.parse(Buffer.from(proof, 'base64').toString());
assert.equal(decoded.challenge.parameters.algorithm, 'PBKDF2/SHA-256');
assert.equal(decoded.challenge.parameters.data.page, Number(new URL(challengeURL).searchParams.get('page')));
assert(await widget.textContent().then(text => text.includes(lang === 'nl' ? 'Geverifieerd' : 'Verified')));
assert.equal(await page.locator('[data-hgcf-field=service]').isVisible(), false);
const requestMode = page.locator('[name=mlhc_mode][value=request]');
if (await requestMode.count()) {
await requestMode.check();
assert.equal(await page.locator('[data-hgcf-field=service]').isVisible(), true);
assert.equal(await page.locator('[name=mlhc_message]').getAttribute('required'), null);
const config=JSON.parse(await page.locator('.mlhc-form').getAttribute('data-hgcf-workflows')).request;
if(config.timeMode==='text'){assert.equal(await page.locator('#mlhc-preferences').isVisible(),true);assert.equal(await page.locator('#mlhc-daypart').isDisabled(),true);await page.locator('#mlhc-preferences').fill('Monday afternoon\nWednesday after 16:00\nFriday morning');}
assert.equal(config.services.at(-1).value,'unsure');
if(config.timeMode==='daypart'){assert.equal(await page.locator('#mlhc-daypart').isVisible(),true);assert.equal(await page.locator('#mlhc-time').isDisabled(),true);await page.locator('#mlhc-daypart').selectOption(Object.keys(config.dayparts)[0]);assert.equal(await page.locator('#mlhc-daypart').getAttribute('required'),null);}
await page.locator('[name=mlhc_mode][value=question]').check();
}
const giftMode=page.locator('[name=mlhc_mode][value=gift]');const configs=JSON.parse(await page.locator('.mlhc-form').getAttribute('data-hgcf-workflows'));
if(await giftMode.count()&&configs.gift.serviceMode==='amount'){
await giftMode.check();assert.equal(await page.locator('#mlhc-amount').isVisible(),true);assert.equal(await page.locator('#mlhc-massage').isDisabled(),true);await page.locator('#mlhc-amount').fill('37,50');
assert.equal(await page.locator('form.mlhc-form').evaluate(f=>new FormData(f).get('mlhc_massage')),'37,50');await page.locator('[name=mlhc_mode][value=question]').check();
}
const geometry = await widget.boundingBox();
assert(geometry.x >= 0 && geometry.x + geometry.width <= (mobile ? 390 : 1440));
await page.locator('.hgcf-contact').screenshot({ path: path.join(artifacts, `form-${lang}-${mobile ? 'mobile' : 'desktop'}.png`) });
assert.deepEqual(errors, []);
const runtimeExternal = requests.filter(request => new URL(request).protocol.startsWith('http') && new URL(request).origin !== new URL(base).origin);
assert.deepEqual(runtimeExternal, [], 'No external requests from contact page or ALTCHA');
await page.locator('.mlhc-form button[type=submit]').click();
await page.waitForFunction(() => document.body.textContent.includes('Test POST intercepted'));
assert.equal(submitted.mlhc_altcha, proof);
proofs.push({ page: decoded.challenge.parameters.data.page, proof });
console.log(`PASS ${lang} ${mobile ? 'mobile' : 'desktop'}: local widget, solved proof, workflow switch, submit interception, no console errors`);
await context.close();
}
}
fs.writeFileSync(path.join(artifacts, 'proofs.json'), JSON.stringify(proofs), { mode: 0o600 });
} finally { await browser.close(); }
})().catch(error => { console.error(error); process.exitCode = 1; });
+29
View File
@@ -0,0 +1,29 @@
<?php
if(!defined('WP_CLI')||!WP_CLI)exit;
function hgcf_daypart_assert($ok,$label){if(!$ok)WP_CLI::error($label);WP_CLI::log('PASS '.$label);}
$config=hgcf_normalize_settings(['recipient'=>'recipient@example.com','site_name'=>'Example','show_consent'=>false]);
$flow=hgcf_workflow_defaults('request');$flow['time']='optional';$flow['time_mode']='daypart';$flow['service']='optional';$flow['message_required']=false;$flow['services']=['combo'=>['nl'=>'Combinatie','en'=>'Combination']];
$config['workflows']=['request'=>$flow];$override=function()use(&$config){return $config;};add_filter('pre_option_hgcf_settings',$override);
$source=['name'=>'Test Visitor','email'=>'visitor@example.com','mode'=>'request','massage'=>'combo','preferred_time'=>'afternoon'];
hgcf_daypart_assert(!is_wp_error(hgcf_validate($source)),'daypart and combination accepted without hidden consent');
foreach(['morning','afternoon','evening',''] as $time)hgcf_daypart_assert(!is_wp_error(hgcf_validate(array_replace($source,['preferred_time'=>$time]))),'optional time of day '.$time);
foreach(['11:30','night','<script>','AFTERNOON',['array']] as $time)hgcf_daypart_assert(is_wp_error(hgcf_validate(array_replace($source,['preferred_time'=>$time]))),'forged or malformed daypart rejected');
$config['workflows']['request']['time']='required';hgcf_daypart_assert(is_wp_error(hgcf_validate(array_replace($source,['preferred_time'=>'']))),'required daypart enforced');$config['workflows']['request']['time']='optional';
$config['workflows']['request']['opening_time']='12:00';$config['workflows']['request']['closing_time']='15:00';
hgcf_daypart_assert(array_keys(hgcf_dayparts($config['workflows']['request']))===['afternoon'],'only overlapping dayparts offered');
hgcf_daypart_assert(is_wp_error(hgcf_validate(array_replace($source,['preferred_time'=>'morning']))),'daypart outside opening range rejected');
$config['workflows']['request']=$flow;
$messages=[];$mock=function($result,$atts)use(&$messages){$messages[]=$atts;return true;};add_filter('pre_wp_mail',$mock,PHP_INT_MAX,2);
foreach(['nl'=>'Voorkeursdagdeel: Middag','en'=>'Preferred time of day: Afternoon'] as $lang=>$expected){hgcf_daypart_assert(hgcf_send(hgcf_validate($source,$lang),$lang),'mock send '.$lang);hgcf_daypart_assert(str_contains(end($messages)['message'],$expected),'mail contains readable daypart '.$lang);}
remove_filter('pre_wp_mail',$mock,PHP_INT_MAX);
$html=hgcf_render(['lang'=>'nl']);preg_match('/data-hgcf-workflows="([^"]+)"/',$html,$match);$frontend=json_decode(html_entity_decode($match[1],ENT_QUOTES),true);
hgcf_daypart_assert(array_column($frontend['request']['services'],'value')===['combo','unsure'],'unsure option is last');
hgcf_daypart_assert($frontend['request']['timeMode']==='daypart'&&$frontend['request']['timeLabel']==='Voorkeursdagdeel','localized daypart config');
hgcf_daypart_assert(str_contains($html,'id="mlhc-daypart"')&&!str_contains($html,'name="mlhc_consent"'),'daypart control and hidden consent render');
$config['workflows']['request']['time_mode']='exact';hgcf_daypart_assert(!is_wp_error(hgcf_validate(array_replace($source,['preferred_time'=>'11:30']))),'exact-time workflow remains compatible');
hgcf_daypart_assert(is_wp_error(hgcf_validate($source)),'exact-time workflow rejects a daypart');
$row=$flow;$row['enabled']='1';$row['message_required']='0';$row['services']=[['id'=>'combo','labels'=>['nl'=>'Combinatie','en'=>'Combination']]];
$clean=hgcf_sanitize_workflows([$row],$config['workflows'],['nl'=>'Nederlands','en'=>'English']);hgcf_daypart_assert(!is_wp_error($clean)&&$clean['request']['time_mode']==='daypart','daypart mode saves in admin');
$row['time_mode']=['bad'];hgcf_daypart_assert(is_wp_error(hgcf_sanitize_workflows([$row],$config['workflows'],['nl'=>'Nederlands','en'=>'English'])),'malformed time mode rejected');
remove_filter('pre_option_hgcf_settings',$override);
WP_CLI::success('Dayparts, exact-time compatibility, ordering and mail checks passed; no real mail sent.');
+30
View File
@@ -0,0 +1,30 @@
<?php
if(!defined('WP_CLI')||!WP_CLI)exit;
function hgcf_free_assert($ok,$label){if(!$ok)WP_CLI::error($label);WP_CLI::log('PASS '.$label);}
$config=hgcf_normalize_settings(['recipient'=>'recipient@example.com','site_name'=>'Example','show_consent'=>false]);
$gift=hgcf_workflow_defaults('gift');$gift['service']='optional';$gift['service_mode']='amount';$gift['service_label']=['nl'=>'Gewenst bedrag','en'=>'Preferred amount'];$gift['message_required']=false;
$request=hgcf_workflow_defaults('request');$request['time']='optional';$request['time_mode']='text';$request['date']='hidden';$request['message_required']=false;
$config['workflows']=['gift'=>$gift,'request'=>$request];$override=function()use(&$config){return $config;};add_filter('pre_option_hgcf_settings',$override);
$source=['name'=>'Test Visitor','email'=>'visitor@example.com','mode'=>'gift','message'=>''];
foreach(['37,50'=>'37.50','37.5'=>'37.50','35'=>'35.00','0,01'=>'0.01','00050'=>'50.00'] as $raw=>$expected){$data=hgcf_validate(array_replace($source,['massage'=>(string)$raw]));hgcf_free_assert(!is_wp_error($data)&&$data['massage']===$expected,'free amount '.$raw);}
foreach(['0','0.00','-5','1e2','1.234','10,50.00','unsure','<script>',str_repeat('9',10),['array']] as $raw)hgcf_free_assert(is_wp_error(hgcf_validate(array_replace($source,['massage'=>$raw]))),'invalid free amount rejected');
hgcf_free_assert(!is_wp_error(hgcf_validate($source)),'optional amount may be blank');$config['workflows']['gift']['service']='required';hgcf_free_assert(is_wp_error(hgcf_validate($source)),'required amount enforced');$config['workflows']['gift']['service']='optional';
$preferences="Monday afternoon\nWednesday after 4 pm\nFriday morning";$booking=array_replace($source,['mode'=>'request','preferred_time'=>$preferences,'preferred_date'=>'bad']);$data=hgcf_validate($booking);
hgcf_free_assert(!is_wp_error($data)&&$data['preferred_time']===$preferences&&$data['preferred_date']==='','free preferences preserve lines and ignore hidden date');
hgcf_free_assert(is_wp_error(hgcf_validate(array_replace($booking,['preferred_time'=>str_repeat('x',1001)]))),'overlong preference rejected');
hgcf_free_assert(is_wp_error(hgcf_validate(array_replace($booking,['preferred_time'=>['array']]))),'array preference rejected');
$config['workflows']['request']['time']='required';hgcf_free_assert(is_wp_error(hgcf_validate(array_replace($booking,['preferred_time'=>'']))),'required preference enforced');$config['workflows']['request']['time']='optional';
$messages=[];$mock=function($result,$atts)use(&$messages){$messages[]=$atts;return true;};add_filter('pre_wp_mail',$mock,PHP_INT_MAX,2);
foreach(['nl'=>'€37,50','en'=>'€37.50'] as $lang=>$expected){hgcf_free_assert(hgcf_send(hgcf_validate(array_replace($source,['massage'=>'37,50'])),$lang),'mock amount mail '.$lang);hgcf_free_assert(str_contains(end($messages)['message'],$expected),'formatted amount in mail '.$lang);}
hgcf_free_assert(hgcf_send(hgcf_validate($booking),'en'),'mock free preference mail');hgcf_free_assert(str_contains(end($messages)['message'],"Preferred times: \n".$preferences),'multiline preferences in email');
remove_filter('pre_wp_mail',$mock,PHP_INT_MAX);
foreach(['anonymous'=>0,'authenticated'=>(int)(get_users(['role'=>'administrator','number'=>1,'fields'=>'ID'])[0]??0)] as $label=>$id){wp_set_current_user($id);hgcf_free_assert(!is_wp_error(hgcf_validate(array_replace($source,['massage'=>'37,50'])))&&!is_wp_error(hgcf_validate($booking)),'validation '.$label);}
$config['workflows']['gift']['service']='hidden';hgcf_free_assert(hgcf_validate(array_replace($source,['massage'=>'bad']))['massage']==='','hidden free amount ignored');$config['workflows']['gift']['service']='optional';
$rows=[];foreach($config['workflows'] as $f){$f['enabled']='1';$f['message_required']='0';$f['services']=[];$rows[]=$f;}
$clean=hgcf_sanitize_workflows($rows,$config['workflows'],['nl'=>'Nederlands','en'=>'English']);hgcf_free_assert(!is_wp_error($clean)&&$clean['gift']['service_mode']==='amount'&&$clean['request']['time_mode']==='text','admin stores free input modes');
$rows[0]['service']='required';hgcf_free_assert(!is_wp_error(hgcf_sanitize_workflows($rows,$config['workflows'],['nl'=>'Nederlands','en'=>'English'])),'required amount needs no choice list');
$rows[0]['service_mode']=['bad'];hgcf_free_assert(is_wp_error(hgcf_sanitize_workflows($rows,$config['workflows'],['nl'=>'Nederlands','en'=>'English'])),'invalid service mode rejected');
$_GET['hgcf_workflow']='gift';$html=hgcf_render(['lang'=>'nl']);hgcf_free_assert(str_contains($html,'id="mlhc-amount"')&&str_contains($html,'inputmode="decimal"'),'amount field rendered');
$_GET['hgcf_workflow']='request';$html=hgcf_render(['lang'=>'en']);hgcf_free_assert(str_contains($html,'id="mlhc-preferences"')&&str_contains($html,'maxlength="1000"'),'preferences textarea rendered');
unset($_GET['hgcf_workflow']);remove_filter('pre_option_hgcf_settings',$override);wp_set_current_user(0);
WP_CLI::success('Free amounts, free preferences, required/hidden modes and anonymous/authenticated mail validation passed; no mail sent.');
+47 -33
View File
@@ -1,37 +1,51 @@
<?php <?php
// Run with wp eval-file tests/integration.php. No options, posts or email are written.
if(!defined('WP_CLI')||!WP_CLI)exit; if(!defined('WP_CLI')||!WP_CLI)exit;
if(!function_exists('hgcf_validate'))WP_CLI::error('Activate HG Contactformulier first.'); function hgcf_assert($ok,$label){if(!$ok)WP_CLI::error($label);WP_CLI::log('PASS '.$label);}
function hgcf_assert($ok,$name){if(!$ok)WP_CLI::error($name);WP_CLI::log('PASS '.$name);} $legacy=array_replace(hgcf_defaults(),['recipient'=>'recipient@example.com','sender_email'=>'forms@example.com','sender_name'=>'Example Practice','site_name'=>'Example practice','contact_name'=>'Taylor','enable_requests'=>true,'show_phone'=>true,'opening_time'=>'10:00','closing_time'=>'18:00','services'=>['consultation'=>['Kennismaking','Introduction']],'title_nl'=>'Vraag aan {contact_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'; $config=$legacy;$override=function()use(&$config){return $config;};add_filter('pre_option_hgcf_settings',$override);
$override=function()use(&$config){return $config;};add_filter('pre_option_hgcf_settings',$override); $languages=['nl'=>'Nederlands','en'=>'English'];$language_override=function()use(&$languages){return $languages;};add_filter('hgcf_languages',$language_override);
hgcf_assert(hgcf_defaults()['show_consent']===true&&hgcf_defaults()['show_note']===true,'existing sites keep consent and note defaults');
$config['show_consent']=false;$config['show_note']=false;
$withoutConsent=['name'=>'Test Visitor','email'=>'visitor@example.com','message'=>'A useful question','mode'=>'question'];
hgcf_assert(!is_wp_error(hgcf_validate($withoutConsent)),'consent disabled allows missing field');
foreach(['nl','en'] as $language){$rendered=hgcf_render(['lang'=>$language]);hgcf_assert(!str_contains($rendered,'name="mlhc_consent"')&&!str_contains($rendered,hgcf_local_setting('note',$language)),'disabled consent and note absent in '.$language);}
$config['show_consent']=true;$config['show_note']=true;
hgcf_assert(is_wp_error(hgcf_validate($withoutConsent)),'enabled consent still enforced');
$rendered=hgcf_render(['lang'=>'nl']);hgcf_assert(str_contains($rendered,'name="mlhc_consent"')&&str_contains($rendered,hgcf_local_setting('note','nl')),'enabled consent and note retained');
$toggleClean=hgcf_sanitize_settings(['show_consent'=>'0','show_note'=>'0']);hgcf_assert(!$toggleClean['show_consent']&&!$toggleClean['show_note'],'display toggles save as booleans');
$toggleClean=hgcf_sanitize_settings(['show_consent'=>['bad'],'show_note'=>'bad']);hgcf_assert($toggleClean['show_consent']&&$toggleClean['show_note'],'invalid display toggles preserve values');
$config=$legacy;
$normalized=hgcf_settings();hgcf_assert(count($normalized['workflows'])===2&&$normalized['workflows']['request']['services']['consultation']['en']==='Introduction','legacy question/request and translated services preserved');
hgcf_assert($normalized['sender_email']==='forms@example.com'&&$normalized['recipient']==='recipient@example.com','sender and recipient preserved during migration');
$config=$normalized;
$question=['name'=>'Test Visitor','email'=>'visitor@example.com','message'=>'A useful question','mode'=>'question','consent'=>'1']; $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_date'=>wp_date('Y-m-d',time()+DAY_IN_SECONDS),'preferred_time'=>'11:30']);
$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($question))&&!is_wp_error(hgcf_validate($request)),'existing workflows validate');
hgcf_assert(!is_wp_error(hgcf_validate($request,'en')),'configured service with optional empty message'); foreach([['email'=>"attacker@example.com\r\nBcc: victim@example.com"],['name'=>['array']],['consent'=>'0'],['message'=>'']] as $patch)hgcf_assert(is_wp_error(hgcf_validate(array_replace($question,$patch))),'reject invalid '.array_key_first($patch));
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_date'=>'2000-01-01'],['preferred_date'=>'2027-02-30'],['preferred_time'=>'09:30'],['preferred_time'=>'18:30']] as $patch)hgcf_assert(is_wp_error(hgcf_validate(array_replace($request,$patch))),'request validation '.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)); $result=hgcf_validate(array_replace($question,['massage'=>'unknown','preferred_time'=>'bad']));hgcf_assert(!is_wp_error($result)&&$result['massage']===''&&$result['preferred_time']==='','workflow ignores hidden fields');
$config['enable_requests']=false;hgcf_assert(is_wp_error(hgcf_validate($request)),'reject forged disabled request'); $third=hgcf_workflow_defaults('callback');$third['label']=['nl'=>'Bel mij terug','en'=>'Call me back'];$third['subject']=['nl'=>'terugbelverzoek','en'=>'callback'];$third['phone']='required';$third['message_required']=false;$third['recipient']='callback@example.com';$config['workflows']['callback']=$third;
$html=hgcf_render(['lang'=>'en']);hgcf_assert(!str_contains($html,'class="request-fields"')&&!str_contains($html,'value="request"'),'disabled request hidden'); $callback=array_replace($question,['mode'=>'callback','message'=>'']);hgcf_assert(is_wp_error(hgcf_validate($callback)),'third workflow enforces required phone');$callback['phone']='+31 6 12345678';hgcf_assert(!is_wp_error(hgcf_validate($callback)),'third workflow independently validates');
$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'); $config['workflows']['callback']['enabled']=false;hgcf_assert(is_wp_error(hgcf_validate($callback)),'disabled workflow rejected');$config['workflows']['callback']['enabled']=true;
$html=hgcf_render(['lang'=>'nl']);hgcf_assert(!str_contains($html,'name="mlhc_phone"'),'disabled phone hidden'); $config['workflows']['request']['service']='required';hgcf_assert(is_wp_error(hgcf_validate(array_replace($request,['massage'=>'unsure']))),'required service excludes unsure');$config['workflows']['request']['service']='optional';
$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'); $config['workflows']['request']['date']='required';hgcf_assert(is_wp_error(hgcf_validate(array_replace($request,['preferred_date'=>'']))),'required date enforced');$config['workflows']['request']['date']='optional';
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($callback),'nl'),'mock mail for third workflow');remove_filter('pre_wp_mail',$mock,PHP_INT_MAX);
$config['sender_email']='forms@example.com';$config['sender_name']='Example Practice'; hgcf_assert($messages[0]['to']==='callback@example.com'&&str_contains($messages[0]['subject'],'terugbelverzoek')&&in_array('Reply-To: visitor@example.com',$messages[0]['headers'],true)&&in_array('From: "Example Practice" <forms@example.com>',$messages[0]['headers'],true),'workflow recipient, subject, sender and Reply-To');
$messages=[];$mock=function($result,$atts)use(&$messages){$messages[]=$atts;return true;};add_filter('pre_wp_mail',$mock,PHP_INT_MAX,2); $config['sender_email']="forms@example.com\r\nBcc: victim@example.com";hgcf_assert(hgcf_send(hgcf_validate($question),'nl')===false,'sender injection rejected');$config['sender_email']='forms@example.com';
hgcf_assert(hgcf_send(hgcf_validate($request),'en')===true,'mocked email');remove_filter('pre_wp_mail',$mock,PHP_INT_MAX); $html=hgcf_render(['lang'=>'en']);hgcf_assert(str_contains($html,'Call me back')&&str_contains($html,'data-hgcf-workflows')&&str_contains($html,'name="mlhc_nonce"'),'frontend renders all active workflows and security token');
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');
hgcf_assert(in_array('From: "Example Practice" <forms@example.com>',$messages[0]['headers'],true)&&in_array('Reply-To: visitor@example.com',$messages[0]['headers'],true),'configured From with visitor Reply-To');
$config['sender_name']="Example \"Practice\""; $messages=[];add_filter('pre_wp_mail',$mock,PHP_INT_MAX,2);hgcf_send(hgcf_validate($question),'nl');remove_filter('pre_wp_mail',$mock,PHP_INT_MAX);hgcf_assert(in_array('From: "Example \"Practice\"" <forms@example.com>',$messages[0]['headers'],true),'sender display name quotes escaped');
$config['sender_email']="forms@example.com\r\nBcc: victim@example.com";hgcf_assert(hgcf_send(hgcf_validate($question),'nl')===false,'unsafe sender rejected before sending');
$config['sender_email']='';$messages=[];add_filter('pre_wp_mail',$mock,PHP_INT_MAX,2);hgcf_send(hgcf_validate($question),'nl');remove_filter('pre_wp_mail',$mock,PHP_INT_MAX);hgcf_assert(!array_filter($messages[0]['headers'],fn($header)=>str_starts_with($header,'From:')),'empty sender preserves mail provider defaults');
require_once ABSPATH.'wp-admin/includes/template.php'; require_once ABSPATH.'wp-admin/includes/template.php';
$input=array_merge($config,['enable_requests'=>'1','show_phone'=>'1','services_text'=>'consultation|Kennismaking|Introduction']); function hgcf_post_rows($flows){$rows=[];foreach($flows as $flow){$row=$flow;$row['enabled']=$flow['enabled']?'1':'0';$row['message_required']=$flow['message_required']?'1':'0';$row['services']=[];foreach($flow['services'] as $key=>$names)$row['services'][]=['id'=>$key,'labels'=>$names];$rows[]=$row;}return $rows;}
$clean=hgcf_sanitize_settings($input);hgcf_assert($clean['services']===['consultation'=>['Kennismaking','Introduction']],'services sanitization'); $input=array_merge($config,['_complete'=>'1','workflows'=>hgcf_post_rows($config['workflows'])]);$clean=hgcf_sanitize_settings($input);hgcf_assert(count($clean['workflows'])===3&&$clean['workflows']['callback']['recipient']==='callback@example.com','structured workflow rows accepted');
$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'); $bad=$input;$bad['workflows'][1]['id']='question';$clean=hgcf_sanitize_settings($bad);hgcf_assert($clean['workflows']===$config['workflows'],'duplicate workflow rejects entire workflow change');
$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'); $bad=$input;foreach($bad['workflows'] as &$row)$row['enabled']='0';unset($row);$clean=hgcf_sanitize_settings($bad);hgcf_assert($clean['workflows']===$config['workflows'],'at least one active workflow required');
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');} $bad=$input;$bad['workflows'][0]['label']='malformed';$clean=hgcf_sanitize_settings($bad);hgcf_assert($clean['workflows']===$config['workflows'],'malformed workflow rejected safely');
$good=hgcf_sanitize_settings(array_replace($input,['sender_email'=>'forms@example.com','sender_name'=>'Example Practice']));hgcf_assert($good['sender_email']==='forms@example.com'&&$good['sender_name']==='Example Practice','sender settings accepted'); $bad=$input;$bad['workflows'][1]['services'][]=$bad['workflows'][1]['services'][0];$clean=hgcf_sanitize_settings($bad);hgcf_assert($clean['workflows']===$config['workflows'],'duplicate service rejected');
$bad=hgcf_sanitize_settings(array_replace($input,['sender_email'=>"forms@example.com\r\nBcc: victim@example.com",'sender_name'=>"Unsafe\nName"]));hgcf_assert($bad['sender_email']===$config['sender_email']&&$bad['sender_name']===$config['sender_name'],'sender header injection settings rejected'); $bad=$input;$bad['sender_email']="forms@example.com\r\nBcc: victim@example.com";$clean=hgcf_sanitize_settings($bad);hgcf_assert($clean['sender_email']===$config['sender_email'],'sender settings reject injection');
remove_filter('pre_option_hgcf_settings',$override); $_POST['option_page']='hgcf';$bad=$input;unset($bad['_complete']);$bad['site_name']='Lost form';$clean=hgcf_sanitize_settings($bad);hgcf_assert($clean===$config,'truncated admin form retains all settings');unset($_POST['option_page']);
WP_CLI::success('Reusable form, settings, admin menu and mail handling verified; no message sent.'); $admin=get_users(['role'=>'administrator','number'=>1]);if($admin){wp_set_current_user($admin[0]->ID);ob_start();hgcf_admin_page();$html=ob_get_clean();hgcf_assert(str_contains($html,'hgcf-general')&&str_contains($html,'hgcf-workflows')&&str_contains($html,'hgcf-texts')&&str_contains($html,'Workflow toevoegen'),'new admin tabs and workflow builder rendered');hgcf_assert(str_contains($html,'{contact_name}')&&str_contains($html,'Question')===false,'raw placeholders retained in settings');
$languages=['nl'=>'Nederlands'];ob_start();hgcf_admin_page();$html=ob_get_clean();hgcf_assert(!str_contains($html,'[label][en]')&&!str_contains($html,'[title_en]')&&str_contains($html,'Eén website-taal'),'single-language admin hides irrelevant translations');
$single=$input;foreach($single['workflows'] as &$row)foreach(['label','subject','message_label','service_label','hint'] as $field)unset($row[$field]['en']);unset($row);$clean=hgcf_sanitize_settings($single);hgcf_assert($clean['workflows']['callback']['label']['en']==='Call me back','inactive translations preserved');
}
$languages=['nl'=>'Nederlands','en'=>'English'];hgcf_assert(hgcf_language('[hg_contactform lang="en"]')==='en'&&hgcf_language('[mlh_contact lang="nl"]')==='nl','current and legacy shortcode languages');
remove_filter('pre_option_hgcf_settings',$override);remove_filter('hgcf_languages',$language_override);
WP_CLI::success('Workflow migration, settings, languages, frontend and mail checks passed; no email sent.');
+16
View File
@@ -0,0 +1,16 @@
<?php
// Isolated PHP check: no WordPress boot, no Polylang, no persistent state.
define('ABSPATH',__DIR__);
$locale='nl_NL';$stored_locale=false;
function get_option($key){global $stored_locale;return $stored_locale;}
function get_locale(){global $locale;return $locale;}
function apply_filters($name,$value){return $value;}
require dirname(__DIR__).'/includes/language.php';
if(hgcf_languages()!==['nl'=>'Nederlands']||hgcf_default_language()!=='nl')throw new RuntimeException('Single site language failed');
$stored_locale='en_US';
if(hgcf_languages()!==['nl'=>'Nederlands']||hgcf_language()!=='nl')throw new RuntimeException('Effective locale must override stale option');
$locale='en_US';$stored_locale='nl_NL';
if(hgcf_languages()!==['en'=>'English'])throw new RuntimeException('English site locale failed');
$locale='de_DE';$stored_locale=false;
if(hgcf_languages()!==['de'=>'de_DE'])throw new RuntimeException('Other site locale failed');
echo "PASS effective WordPress site locale, empty/stale WPLANG option and no language plugin\n";
+17
View File
@@ -0,0 +1,17 @@
<?php
if(!defined('WP_CLI')||!WP_CLI)exit;
function hgcf_link_assert($ok,$label){if(!$ok)WP_CLI::error($label);WP_CLI::log('PASS '.$label);}
$config=hgcf_normalize_settings(['recipient'=>'recipient@example.com','site_name'=>'Example','show_consent'=>false]);
$gift=hgcf_workflow_defaults('gift');$gift['service']='optional';$gift['date']='hidden';$gift['time']='hidden';$gift['message_required']=false;$gift['label']=['nl'=>'Cadeaubon aanvragen','en'=>'Request a gift voucher'];$gift['subject']=['nl'=>'cadeaubonaanvraag','en'=>'gift voucher request'];$gift['service_label']=['nl'=>'Gewenst bedrag','en'=>'Preferred amount'];$gift['services']=['amount_25'=>['nl'=>'€25','en'=>'€25'],'amount_50'=>['nl'=>'€50','en'=>'€50']];
$config['workflows']['gift']=$gift;$override=function()use(&$config){return $config;};add_filter('pre_option_hgcf_settings',$override);
$originalGet=$_GET;$originalPost=$_POST;$_POST=[];
foreach(['nl','en'] as $lang){$_GET['hgcf_workflow']='gift';$html=hgcf_render(['lang'=>$lang]);hgcf_link_assert(preg_match('/name="mlhc_mode" value="gift"\s+checked/',$html)===1,'active linked workflow selected '.$lang);hgcf_link_assert(str_contains($html,$gift['service_label'][$lang]),'gift amount label '.$lang);}
foreach(['unknown',['gift'],'<script>alert(1)</script>'] as $bad){$_GET['hgcf_workflow']=$bad;$html=hgcf_render(['lang'=>'nl']);hgcf_link_assert(preg_match('/name="mlhc_mode" value="question"\s+checked/',$html)===1,'invalid link falls back safely');}
$config['workflows']['gift']['enabled']=false;$_GET['hgcf_workflow']='gift';hgcf_link_assert(!str_contains(hgcf_render(['lang'=>'nl']),'value="gift"'),'disabled workflow unavailable');$config['workflows']['gift']['enabled']=true;
$GLOBALS['mlhc_errors']=new WP_Error('email','Test validation error');$_POST['mlhc_mode']='question';$html=hgcf_render(['lang'=>'nl']);hgcf_link_assert(preg_match('/name="mlhc_mode" value="question"\s+checked/',$html)===1,'posted selection takes priority after validation error');unset($GLOBALS['mlhc_errors']);$_POST=[];
$source=['name'=>'Test Visitor','email'=>'visitor@example.com','mode'=>'gift','massage'=>'amount_50','message'=>'','preferred_date'=>'invalid','preferred_time'=>'invalid'];$data=hgcf_validate($source,'nl');hgcf_link_assert(!is_wp_error($data)&&$data['preferred_date']===''&&$data['preferred_time']==='','gift request accepts amount and ignores appointment fields');
hgcf_link_assert(is_wp_error(hgcf_validate(array_replace($source,['massage'=>'forged']))),'forged amount rejected');hgcf_link_assert(!is_wp_error(hgcf_validate(array_replace($source,['massage'=>'unsure']))),'undecided amount accepted');
$messages=[];$mock=function($result,$atts)use(&$messages){$messages[]=$atts;return true;};add_filter('pre_wp_mail',$mock,PHP_INT_MAX,2);
foreach(['nl'=>'Gewenst bedrag: €50','en'=>'Preferred amount: €50'] as $lang=>$expected){hgcf_link_assert(hgcf_send($data,$lang),'mock gift email '.$lang);$mail=end($messages);hgcf_link_assert(str_contains($mail['message'],$expected)&&str_contains($mail['subject'],$gift['subject'][$lang])&&!str_contains($mail['message'],'Voorkeursdatum:'),'gift label, amount and subject in mail '.$lang);}
remove_filter('pre_wp_mail',$mock,PHP_INT_MAX);remove_filter('pre_option_hgcf_settings',$override);$_GET=$originalGet;$_POST=$originalPost;
WP_CLI::success('Workflow links and gift requests passed; no email sent.');