Files
wp-plugin-contactform/hg-contactform.php
T

106 lines
13 KiB
PHP
Raw Normal View History

<?php
/**
* Plugin Name: HG Contactformulier
* Description: Tweetalig contactformulier voor vragen en massageaanvragen, zonder inzendingen in WordPress op te slaan.
* Version: 1.0.0
* Requires at least: 6.5
* Requires PHP: 8.0
* Text Domain: hg-contactform
*/
if (!defined('ABSPATH')) { exit; }
require_once __DIR__.'/includes/settings.php';
require_once __DIR__.'/includes/language.php';
function hgcf_text($nl,$en,$lang) { return $lang==='en'?$en:$nl; }
function hgcf_types() { return hgcf_setting('services')+['unsure'=>['Ik weet het nog niet','Not sure yet']]; }
function hgcf_validate(array $source, $lang='nl') {
$errors=new WP_Error(); $data=[];
foreach(['name','email','phone','message','mode','massage','preferred_date','preferred_time'] as $key) {
if(isset($source[$key]) && !is_string($source[$key])) { $errors->add('invalid',hgcf_text('Controleer de ingevulde velden.','Please check the form fields.',$lang)); return $errors; }
$data[$key]=trim(wp_unslash($source[$key]??''));
}
if(strlen($data['name'])<2 || strlen($data['name'])>120) $errors->add('name',hgcf_text('Vul je naam in (2 tot 120 tekens).','Enter your name (2 to 120 characters).',$lang));
if(strlen($data['email'])>254 || !is_email($data['email']) || preg_match('/[\r\n]/',$data['email'])) $errors->add('email',hgcf_text('Vul een geldig e-mailadres in.','Enter a valid email address.',$lang));
if(!in_array($data['mode'],['question','request'],true)) $errors->add('mode',hgcf_text('Kies een vraag of afspraakaanvraag.','Choose a question or appointment request.',$lang));
if(hgcf_setting('show_phone') && (strlen($data['phone'])>40 || (hgcf_setting('show_phone') && $data['phone']!=='' && !preg_match('/^[0-9+() .-]{5,40}$/',$data['phone'])))) $errors->add('phone',hgcf_text('Controleer je telefoonnummer.','Please check your phone number.',$lang));
if(strlen($data['message'])>5000 || ($data['mode']==='question' && strlen($data['message'])<5)) $errors->add('message',hgcf_text('Schrijf je vraag (5 tot 5000 tekens).','Write your question (5 to 5000 characters).',$lang));
if($data['mode']==='request' && !hgcf_setting('enable_requests')) $errors->add('mode',hgcf_text('Afspraakaanvragen zijn niet ingeschakeld.','Appointment requests are not enabled.',$lang));
if(!hgcf_setting('show_phone')) $data['phone']='';
if($data['mode']==='request') {
if(!isset(hgcf_types()[$data['massage']])) $errors->add('massage',hgcf_text('Kies een dienst of “Ik weet het nog niet”.','Choose a service or “Not sure yet”.',$lang));
if($data['preferred_date']!=='') {
$date=DateTimeImmutable::createFromFormat('!Y-m-d',$data['preferred_date'],wp_timezone());
if(!$date || $date->format('Y-m-d')!==$data['preferred_date'] || $data['preferred_date']<wp_date('Y-m-d')) $errors->add('preferred_date',hgcf_text('Kies vandaag of een datum in de toekomst.','Choose today or a future date.',$lang));
}
if($data['preferred_time']!=='' && (!preg_match('/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/',$data['preferred_time']) || $data['preferred_time']<hgcf_setting('opening_time') || $data['preferred_time']>hgcf_setting('closing_time'))) $errors->add('preferred_time',sprintf(hgcf_text('Kies een tijd tussen %s en %s.','Choose a time between %s and %s.',$lang),hgcf_setting('opening_time'),hgcf_setting('closing_time')));
} else { $data['massage']=$data['preferred_date']=$data['preferred_time']=''; }
if(empty($source['consent']) || !is_string($source['consent']) || $source['consent']!=='1') $errors->add('consent',hgcf_text('Geef toestemming om je gegevens voor een reactie te gebruiken.','Allow me to use your details to reply.',$lang));
if($errors->has_errors()) return $errors;
foreach($data as $key=>$value) $data[$key]=$key==='message'?sanitize_textarea_field($value):sanitize_text_field($value);
return $data;
}
function hgcf_send(array $data, $lang) {
$request=$data['mode']==='request';
$body="Contactformulier ".sanitize_text_field(hgcf_setting('site_name'))."\nTaal: ".$lang."\nType: ".($request?'Afspraakaanvraag':'Vraag')."\nNaam: ".$data['name']."\nE-mail: ".$data['email']."\nTelefoon: ".($data['phone']?:'Niet opgegeven')."\n";
if($request) { $type=hgcf_types()[$data['massage']]; $body.="Dienst: ".$type[0]."\nVoorkeursdatum: ".($data['preferred_date']?:'Geen voorkeur')."\nVoorkeurstijd: ".($data['preferred_time']?:'Geen voorkeur')."\nDit is een aanvraag, geen bevestigde afspraak.\n"; }
$body.="\nBericht:\n".$data['message'];
return wp_mail(hgcf_setting('recipient'),sanitize_text_field(hgcf_setting('site_name')).': '.($request?'afspraakaanvraag':'vraag'),$body,['Content-Type: text/plain; charset=UTF-8','Reply-To: '.$data['email']]);
}
add_action('template_redirect', function () {
if(($_SERVER['REQUEST_METHOD']??'')!=='POST' || ($_POST['mlhc_action']??'')!=='send') return;
$id=get_queried_object_id(); $post=get_post($id);
if(!is_singular() || !$post || (!has_shortcode($post->post_content,'hg_contactform') && !has_shortcode($post->post_content,'mlh_contact'))) wp_die('Invalid form page', '', ['response'=>403]);
$lang=hgcf_language($post->post_content);
$error=hgcf_text('Het versturen is niet gelukt. Probeer het opnieuw of gebruik een andere contactmogelijkheid.','Your message could not be sent. Please try again or use another contact option.',$lang);
$nonce=$_POST['mlhc_nonce']??''; $started=$_POST['mlhc_started']??''; $signature=$_POST['mlhc_signature']??'';
if(!is_string($nonce) || !wp_verify_nonce($nonce,'hgcf_send') || !is_string($started) || !ctype_digit($started) || !is_string($signature) || !hash_equals(hash_hmac('sha256',$started,wp_salt('nonce')),$signature) || time()-(int)$started<2 || time()-(int)$started>DAY_IN_SECONDS || !empty($_POST['mlhc_website'])) {
$GLOBALS['mlhc_errors']=new WP_Error('security',$error); return;
}
$submitted=[]; foreach(['name','email','phone','message','mode','massage','preferred_date','preferred_time','consent'] as $field) { if(isset($_POST['mlhc_'.$field])) $submitted[$field]=$_POST['mlhc_'.$field]; }
$data=hgcf_validate($submitted,$lang);
if(is_wp_error($data)) { $GLOBALS['mlhc_errors']=$data; return; }
$ip=$_SERVER['REMOTE_ADDR']??'unknown';
$rate_key='mlhc_rate_'.hash_hmac('sha256',$ip,wp_salt('auth'));
$rate=get_transient($rate_key);
if($rate && ($rate['count']>=5 || time()-$rate['last']<30)) { $GLOBALS['mlhc_errors']=new WP_Error('rate',hgcf_text('Even geduld: probeer het over een minuut opnieuw of gebruik een andere contactmogelijkheid.','Please wait a minute before trying again, or use another contact option.',$lang)); return; }
$rate=$rate?:['count'=>0,'last'=>0]; $rate['count']++;$rate['last']=time();set_transient($rate_key,$rate,15*MINUTE_IN_SECONDS);
if(!hgcf_send($data,$lang)) { $GLOBALS['mlhc_errors']=new WP_Error('mail',$error); return; }
$url=add_query_arg(['contact_status'=>'received','receipt'=>wp_create_nonce('mlhc_received_'.$id)],get_permalink($id));
wp_safe_redirect($url.'#contact-form',303);exit;
});
function hgcf_render($atts=[]) {
$atts=shortcode_atts(['lang'=>'auto'],$atts);$lang=in_array($atts['lang'],['nl','en'],true)?$atts['lang']:hgcf_language();
$t=function($nl,$en)use($lang){return hgcf_text($nl,$en,$lang);};
$errors=$GLOBALS['mlhc_errors']??null;
$receipt=$_GET['receipt']??'';
if(($_GET['contact_status']??'')==='received' && is_string($receipt) && wp_verify_nonce($receipt,'mlhc_received_'.get_queried_object_id())) return '<section id="contact-form" class="contact-form hgcf-contact form-success" role="status"><h2>'.esc_html($t('Bedankt voor je bericht.','Thank you for your message.')).'</h2><p>'.esc_html(hgcf_local_setting('success',$lang).(hgcf_setting('enable_requests')?' '.$t('Een aanvraag is pas een afspraak na bevestiging.','A request becomes an appointment only after confirmation.'):'')).'</p><a href="'.esc_url(get_permalink()).'">'.esc_html($t('Nog een bericht sturen','Send another message')).'</a></section>';
$value=function($key)use($errors){return $errors && isset($_POST['mlhc_'.$key]) && is_string($_POST['mlhc_'.$key])?wp_unslash($_POST['mlhc_'.$key]):'';};
$mode=hgcf_setting('enable_requests') && $value('mode')==='request'?'request':'question';$started=(string)time();
ob_start(); ?>
<section class="contact-form hgcf-contact" id="contact-form"><h2><?php echo esc_html(hgcf_local_setting('title',$lang)); ?></h2>
<?php if($errors): ?><div class="form-errors" role="alert" tabindex="-1"><p><strong><?php echo esc_html($t('Controleer je bericht:','Please check your message:')); ?></strong></p><ul><?php foreach($errors->get_error_messages() as $message): ?><li><?php echo esc_html($message); ?></li><?php endforeach; ?></ul></div><?php endif; ?>
<form class="mlhc-form" action="<?php echo esc_url(get_permalink()); ?>#contact-form" method="post">
<input type="hidden" name="mlhc_action" value="send"><?php wp_nonce_field('hgcf_send','mlhc_nonce',false); ?>
<input type="hidden" name="mlhc_started" value="<?php echo esc_attr($started); ?>"><input type="hidden" name="mlhc_signature" value="<?php echo esc_attr(hash_hmac('sha256',$started,wp_salt('nonce'))); ?>">
<div class="mlhc-trap" aria-hidden="true"><label for="mlhc-website">Website</label><input tabindex="-1" autocomplete="off" id="mlhc-website" name="mlhc_website" type="text"></div>
<fieldset class="form-mode"><legend><?php echo esc_html($t('Ik wil…','I would like to…')); ?></legend><label><input type="radio" name="mlhc_mode" value="question" <?php checked($mode,'question'); ?>><?php echo esc_html($t('Een vraag stellen','Ask a question')); ?></label><?php if(hgcf_setting('enable_requests')): ?><label><input type="radio" name="mlhc_mode" value="request" <?php checked($mode,'request'); ?>><?php echo esc_html(hgcf_local_setting('request_label',$lang)); ?></label><?php endif; ?></fieldset>
<div class="form-fields"><label for="mlhc-name"><?php echo esc_html($t('Naam *','Name *')); ?><input id="mlhc-name" name="mlhc_name" autocomplete="name" required minlength="2" maxlength="120" value="<?php echo esc_attr($value('name')); ?>"></label><label for="mlhc-email"><?php echo esc_html($t('E-mailadres *','Email address *')); ?><input id="mlhc-email" type="email" name="mlhc_email" autocomplete="email" required maxlength="254" value="<?php echo esc_attr($value('email')); ?>"></label></div>
<?php if(hgcf_setting('show_phone')): ?><label for="mlhc-phone"><?php echo esc_html($t('Telefoonnummer (optioneel)','Phone number (optional)')); ?><input id="mlhc-phone" type="tel" name="mlhc_phone" autocomplete="tel" maxlength="40" value="<?php echo esc_attr($value('phone')); ?>"></label>
<?php endif; ?>
<?php if(hgcf_setting('enable_requests')): ?><fieldset class="request-fields"><legend><?php echo esc_html($t('Voor je afspraakaanvraag','For your appointment request')); ?></legend><label for="mlhc-massage"><?php echo esc_html(hgcf_local_setting('service_label',$lang)); ?><select id="mlhc-massage" name="mlhc_massage"><?php foreach(hgcf_types() as $key=>$name): ?><option value="<?php echo esc_attr($key); ?>" <?php selected($value('massage')?:'unsure',$key); ?>><?php echo esc_html($name[$lang==='en'?1:0]); ?></option><?php endforeach; ?></select></label>
<div class="form-fields"><label for="mlhc-date"><?php echo esc_html($t('Voorkeursdatum (optioneel)','Preferred date (optional)')); ?><input id="mlhc-date" name="mlhc_preferred_date" type="date" min="<?php echo esc_attr(wp_date('Y-m-d')); ?>" value="<?php echo esc_attr($value('preferred_date')); ?>"></label><label for="mlhc-time"><?php echo esc_html($t('Voorkeurstijd (optioneel)','Preferred time (optional)')); ?><input id="mlhc-time" name="mlhc_preferred_time" type="time" min="<?php echo esc_attr(hgcf_setting('opening_time')); ?>" max="<?php echo esc_attr(hgcf_setting('closing_time')); ?>" value="<?php echo esc_attr($value('preferred_time')); ?>"></label></div><p class="form-note"><?php echo esc_html($t('Dit is een voorkeur, geen reservering. We stemmen de datum en tijd met je af.','This is a preference, not a reservation. We will confirm the date and time with you.')); ?></p></fieldset><?php endif; ?>
<label for="mlhc-message"><span class="message-label"><?php echo esc_html($t('Je vraag *','Your question *')); ?></span><textarea id="mlhc-message" name="mlhc_message" rows="5" maxlength="5000"><?php echo esc_textarea($value('message')); ?></textarea></label>
<label class="consent"><input type="checkbox" name="mlhc_consent" value="1" required <?php checked($value('consent'),'1'); ?>><span><?php echo esc_html(hgcf_local_setting('consent',$lang)); ?></span></label>
<p class="form-note"><?php echo esc_html(hgcf_local_setting('note',$lang)); ?></p>
<button class="button" type="submit"><?php echo esc_html($t('Verstuur bericht','Send message')); ?></button>
</form></section>
<?php
wp_enqueue_style('hgcf',plugins_url('assets/contact.css',__FILE__),[],'1.0.0');
wp_enqueue_script('hgcf',plugins_url('assets/contact.js',__FILE__),[], '1.0.0',true);
wp_add_inline_script('hgcf','window.hgcfLabels='.wp_json_encode(['question'=>$t('Je vraag *','Your question *'),'request'=>$t('Toelichting (optioneel)','Message (optional)'),'send'=>$t('Verstuur bericht','Send message'),'sending'=>$t('Wordt verstuurd…','Sending…')]).';','before');
return ob_get_clean();
}
add_shortcode('hg_contactform','hgcf_render');
add_shortcode('mlh_contact','hgcf_render');
add_action('wp_enqueue_scripts',function(){
$post=get_post();if(is_singular()&&$post&&(has_shortcode($post->post_content,'hg_contactform')||has_shortcode($post->post_content,'mlh_contact')))wp_enqueue_style('hgcf',plugins_url('assets/contact.css',__FILE__),[],'1.0.0');
});