$name,
'form_id' => $form_id,
/* General */
'recipient_email' => get_option( 'admin_email' ),
'recipient_name' => get_bloginfo( 'name' ),
'subject' => 'New contact form submission',
'select_placeholder' => '— Please select —',
/* Post-submission */
'after_submit' => 'inline',
'inline_message' => 'Thank you, {name}! Your message has been sent.',
'thankyou_page_id' => 0,
'thankyou_heading' => 'Message Sent!',
'thankyou_body' => "Thank you, {name}! We've received your message and will be in touch soon.",
'thankyou_link_enabled' => false,
'thankyou_link_url' => '',
'thankyou_link_text' => 'Return to Home',
'redirect_page_id' => 0,
/* Fields */
'fields' => [
[ 'id' => 'name', 'label' => 'Your Name', 'type' => 'text', 'required' => true, 'placeholder' => 'e.g. Jane Smith', 'options' => '' ],
[ 'id' => 'email', 'label' => 'Email Address', 'type' => 'email', 'required' => true, 'placeholder' => 'you@example.com', 'options' => '' ],
[ 'id' => 'phone', 'label' => 'Phone Number', 'type' => 'tel', 'required' => false, 'placeholder' => '', 'options' => '' ],
[ 'id' => 'message', 'label' => 'Message', 'type' => 'textarea', 'required' => true, 'placeholder' => 'How can we help?', 'options' => '' ],
],
/* Upload */
'upload_max_mb' => 5,
'upload_allowed_types' => 'jpg,jpeg,png,gif,webp',
/* Rate limit */
'rate_limit_enabled' => true,
'rate_limit_max' => 5,
'rate_limit_window' => 60,
/* Font */
'form_font' => 'theme',
'form_font_custom' => '',
/* Button style */
'btn_align' => 'left',
'btn_label' => 'Send Message',
'btn_color' => '#2563eb',
'btn_size' => 'medium',
'btn_radius' => '8',
/* Label alignment */
'label_align' => 'left',
/* Auto-reply */
'autoreply_enabled' => true,
'autoreply_email_field' => 'email',
'autoreply_name_field' => 'name',
'autoreply_subject' => 'We received your message!',
'autoreply_body' => "Hi {name},\n\nThank you for reaching out! We've received your message and will get back to you shortly.\n\nHere's a copy of what you sent:\n\n{message}\n\nWarm regards,\n{site_name}",
];
}
/* ================================================================== *
* HELPERS — get/list forms
* ================================================================== */
function ajb_cfm_get_form_ids() {
return (array) get_option( 'ajb_cfm_forms', [ 'default' ] );
}
function ajb_cfm_get_form( $form_id ) {
$data = get_option( 'ajb_cfm_form_' . sanitize_key( $form_id ) );
// Return null if the form does not exist (e.g. was deleted).
// Callers must check for null before using — the shortcode will
// render nothing rather than silently recreating a deleted form.
if ( ! $data ) return null;
return $data;
}
function ajb_cfm_save_form( $form_id, $data ) {
update_option( 'ajb_cfm_form_' . sanitize_key( $form_id ), $data );
$ids = ajb_cfm_get_form_ids();
if ( ! in_array( $form_id, $ids, true ) ) {
$ids[] = $form_id;
update_option( 'ajb_cfm_forms', $ids );
}
}
function ajb_cfm_delete_form( $form_id ) {
delete_option( 'ajb_cfm_form_' . sanitize_key( $form_id ) );
$ids = array_values( array_filter( ajb_cfm_get_form_ids(), fn($i) => $i !== $form_id ) );
if ( empty( $ids ) ) $ids = [];
update_option( 'ajb_cfm_forms', $ids );
}
/* ================================================================== *
* ADMIN MENU
* ================================================================== */
add_action( 'admin_menu', 'ajb_cfm_admin_menu' );
function ajb_cfm_admin_menu() {
add_menu_page( 'AJB Clean Form Mail', 'AJB Clean Form Mail', 'manage_options',
'ajb-cfm', 'ajb_cfm_admin_page', 'dashicons-email-alt', 58 );
add_submenu_page( 'ajb-cfm', 'All Forms', 'All Forms',
'manage_options', 'ajb-cfm', 'ajb_cfm_admin_page' );
}
/* ================================================================== *
* ADMIN ASSETS
* ================================================================== */
add_action( 'admin_enqueue_scripts', 'ajb_cfm_admin_assets' );
function ajb_cfm_admin_assets( $hook ) {
if ( strpos( $hook, 'ajb-cfm' ) === false ) return;
wp_enqueue_style( 'ajb-cfm-admin', AJB_CFM_PLUGIN_URL . 'assets/admin.css', [], AJB_CFM_VERSION );
wp_enqueue_script( 'ajb-cfm-admin', AJB_CFM_PLUGIN_URL . 'assets/admin.js', ['jquery'], AJB_CFM_VERSION, true );
wp_localize_script( 'ajb-cfm-admin', 'ajbCfmData', [
'nonce' => wp_create_nonce( 'ajb_cfm_admin' ),
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'confirm_del' => 'Are you sure you want to delete this form? This cannot be undone.',
]);
}
/* ================================================================== *
* SAVE FORM SETTINGS (admin-post)
* ================================================================== */
add_action( 'admin_post_ajb_cfm_save_settings', 'ajb_cfm_save_settings' );
function ajb_cfm_save_settings() {
check_admin_referer( 'ajb_cfm_save', 'ajb_cfm_nonce' );
if ( ! current_user_can( 'manage_options' ) ) wp_die( 'Unauthorised' );
// wp_unslash strips the magic quotes WordPress automatically adds to $_POST,
// preventing apostrophes and special characters gaining extra backslashes on every save.
$p = wp_unslash( $_POST );
$form_id = sanitize_key( $p['ajb_cfm_form_id'] ?? 'default' );
// Rebuild fields
$fields = [];
if ( ! empty( $p['field_id'] ) ) {
foreach ( $p['field_id'] as $i => $id ) {
$id = sanitize_key( $id );
if ( ! $id ) continue;
$fields[] = [
'id' => $id,
'label' => sanitize_text_field( $p['field_label'][$i] ?? '' ),
'type' => sanitize_key( $p['field_type'][$i] ?? 'text' ),
'required' => ! empty( $p['field_required'][$i] ),
'placeholder' => sanitize_text_field( $p['field_placeholder'][$i] ?? '' ),
'options' => sanitize_text_field( $p['field_options'][$i] ?? '' ),
];
}
}
// Sanitize form name & ID
$form_name = sanitize_text_field( $p['ajb_cfm_form_name'] ?? 'Untitled Form' );
$new_form_id = sanitize_key( $p['ajb_cfm_form_id_edit'] ?? $form_id );
if ( empty( $new_form_id ) ) $new_form_id = $form_id;
$settings = [
'name' => $form_name,
'form_id' => $new_form_id,
'recipient_email' => sanitize_email( $p['recipient_email'] ?? '' ),
'recipient_name' => sanitize_text_field( $p['recipient_name'] ?? '' ),
'subject' => sanitize_text_field( $p['subject'] ?? '' ),
'select_placeholder' => sanitize_text_field( $p['select_placeholder'] ?? '— Please select —' ),
'after_submit' => sanitize_key( $p['after_submit'] ?? 'inline' ),
'inline_message' => wp_kses_post( $p['inline_message'] ?? '' ),
'thankyou_page_id' => absint( $p['thankyou_page_id'] ?? 0 ),
'thankyou_heading' => sanitize_text_field( $p['thankyou_heading'] ?? '' ),
'thankyou_body' => sanitize_textarea_field( $p['thankyou_body'] ?? '' ),
'thankyou_link_enabled' => ! empty( $p['thankyou_link_enabled'] ),
'thankyou_link_url' => esc_url_raw( $p['thankyou_link_url'] ?? '' ),
'thankyou_link_text' => sanitize_text_field( $p['thankyou_link_text'] ?? '' ),
'redirect_page_id' => absint( $p['redirect_page_id'] ?? 0 ),
'fields' => $fields,
'upload_max_mb' => absint( $p['upload_max_mb'] ?? 5 ),
'upload_allowed_types' => sanitize_text_field( $p['upload_allowed_types'] ?? 'jpg,jpeg,png,gif,webp' ),
'rate_limit_enabled' => ! empty( $p['rate_limit_enabled'] ),
'rate_limit_max' => absint( $p['rate_limit_max'] ?? 5 ),
'rate_limit_window' => absint( $p['rate_limit_window'] ?? 60 ),
'form_font' => sanitize_key( $p['form_font'] ?? 'theme' ),
'form_font_custom' => sanitize_text_field( $p['form_font_custom'] ?? '' ),
'btn_align' => sanitize_key( $p['btn_align'] ?? 'left' ),
'btn_label' => sanitize_text_field( $p['btn_label'] ?? 'Send Message' ),
'btn_color' => sanitize_hex_color( $p['btn_color'] ?? '#2563eb' ) ?: '#2563eb',
'btn_size' => sanitize_key( $p['btn_size'] ?? 'medium' ),
'btn_radius' => absint( $p['btn_radius'] ?? 8 ),
'label_align' => sanitize_key( $p['label_align'] ?? 'left' ),
'autoreply_enabled' => ! empty( $p['autoreply_enabled'] ),
'autoreply_email_field' => sanitize_key( $p['autoreply_email_field'] ?? 'email' ),
'autoreply_name_field' => sanitize_key( $p['autoreply_name_field'] ?? 'name' ),
'autoreply_subject' => sanitize_text_field( $p['autoreply_subject'] ?? '' ),
'autoreply_body' => sanitize_textarea_field( $p['autoreply_body'] ?? '' ),
];
// Handle form ID rename
if ( $new_form_id !== $form_id ) {
ajb_cfm_delete_form( $form_id );
}
ajb_cfm_save_form( $new_form_id, $settings );
wp_safe_redirect( esc_url_raw( admin_url( 'admin.php?page=ajb-cfm&edit=' . $new_form_id . '&saved=1' ) ) );
exit;
}
/* ================================================================== *
* AJAX — create new form
* ================================================================== */
add_action( 'wp_ajax_ajb_cfm_create_form', 'ajb_cfm_ajax_create_form' );
function ajb_cfm_ajax_create_form() {
check_ajax_referer( 'ajb_cfm_admin', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();
$name = sanitize_text_field( wp_unslash( $_POST['name'] ?? 'New Form' ) );
$form_id = sanitize_key( wp_unslash( $_POST['form_id'] ?? '' ) );
if ( ! $form_id ) $form_id = sanitize_key( strtolower( preg_replace( '/\s+/', '-', $name ) ) );
if ( ! $form_id ) $form_id = 'form-' . time();
// Ensure unique
$ids = ajb_cfm_get_form_ids();
$base = $form_id; $n = 2;
while ( in_array( $form_id, $ids, true ) ) { $form_id = $base . '-' . $n++; }
$data = ajb_cfm_default_form_settings( $name, $form_id );
$data['name'] = $name;
$data['form_id'] = $form_id;
ajb_cfm_save_form( $form_id, $data );
wp_send_json_success( [ 'form_id' => $form_id, 'redirect' => admin_url( 'admin.php?page=ajb-cfm&edit=' . $form_id ) ] );
}
/* ================================================================== *
* AJAX — duplicate form
* ================================================================== */
add_action( 'wp_ajax_ajb_cfm_duplicate_form', 'ajb_cfm_ajax_duplicate_form' );
function ajb_cfm_ajax_duplicate_form() {
check_ajax_referer( 'ajb_cfm_admin', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();
$src_id = sanitize_key( $_POST['form_id'] ?? '' );
$src = ajb_cfm_get_form( $src_id );
$new_id = $src_id . '-copy'; $n = 2;
$ids = ajb_cfm_get_form_ids();
while ( in_array( $new_id, $ids, true ) ) { $new_id = $src_id . '-copy-' . $n++; }
$src['name'] = $src['name'] . ' (Copy)';
$src['form_id'] = $new_id;
ajb_cfm_save_form( $new_id, $src );
wp_send_json_success( [ 'form_id' => $new_id, 'redirect' => admin_url( 'admin.php?page=ajb-cfm&edit=' . $new_id ) ] );
}
/* ================================================================== *
* AJAX — delete form
* ================================================================== */
add_action( 'wp_ajax_ajb_cfm_delete_form', 'ajb_cfm_ajax_delete_form' );
function ajb_cfm_ajax_delete_form() {
check_ajax_referer( 'ajb_cfm_admin', 'nonce' );
if ( ! current_user_can( 'manage_options' ) ) wp_send_json_error();
$form_id = sanitize_key( $_POST['form_id'] ?? '' );
if ( $form_id === 'default' ) wp_send_json_error( [ 'message' => 'Cannot delete the default form.' ] );
ajb_cfm_delete_form( $form_id );
wp_send_json_success( [ 'redirect' => admin_url( 'admin.php?page=ajb-cfm' ) ] );
}
/* ================================================================== *
* ADMIN PAGE — forms list + form editor
* ================================================================== */
function ajb_cfm_admin_page() {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only, no data mutation
$editing = isset( $_GET['edit'] ) ? sanitize_key( wp_unslash( $_GET['edit'] ) ) : null;
if ( $editing ) {
ajb_cfm_render_form_editor( $editing );
} else {
ajb_cfm_render_forms_list();
}
}
/* ── Forms list ──────────────────────────────────────────────────── */
function ajb_cfm_render_forms_list() {
$ids = ajb_cfm_get_form_ids();
?>
✓ Form saved successfully.
The default form can be used without an id: [ajb_cfm_form]
[ 'page', 'post' ], 'post_status' => 'publish',
'numberposts' => -1, 'orderby' => 'title', 'order' => 'ASC',
]);
?>
✓ Settings saved.
".esc_html(ucfirst($t))."";
}
// Allow the JS placeholder string '__INDEX__' to pass through unchanged;
// for real (numeric) indices use absint() for safety.
$idx = ( $i === '__INDEX__' ) ? '__INDEX__' : absint( $i );
$type = $f['type'] ?? 'text';
$is_sel = $type === 'select';
$opts_hidden = $is_sel ? '' : ' cfm-hidden';
?>
function($s){
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
},
'fields' => function($s){
foreach($s['fields'] as $i=>$f){
$idx = absint( $i );
echo '';
echo '';
echo '';
echo '';
echo '';
if($f['required']) echo '';
}
},
'submission' => function($s){
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
echo '';
},
'autoreply' => function($s){
echo '';
echo '';
echo '';
echo '';
echo '';
},
];
foreach($map as $t=>$fn) if($t!==$active) $fn($s);
}
/* ================================================================== *
* FRONT-END ASSETS
* ================================================================== */
add_action( 'wp_enqueue_scripts', 'ajb_cfm_frontend_assets' );
function ajb_cfm_frontend_assets() {
wp_enqueue_style( 'ajb-cfm-front', AJB_CFM_PLUGIN_URL . 'assets/front.css', [], AJB_CFM_VERSION );
wp_enqueue_script( 'ajb-cfm-front', AJB_CFM_PLUGIN_URL . 'assets/front.js', ['jquery'], AJB_CFM_VERSION, true );
wp_localize_script( 'ajb-cfm-front', 'ajbCfmAjax', [
'ajaxurl' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('ajb_cfm_submit'),
]);
// Scan the current post/page content for [ajb_cfm_form] shortcodes so we can
// enqueue per-form Google Fonts and scoped CSS via wp_enqueue_style /
// wp_add_inline_style — both of which must be called before wp_head fires.
global $post;
if ( ! $post ) return;
$content = $post->post_content;
// Find every [ajb_cfm_form ...] shortcode on this page
if ( ! has_shortcode( $content, 'ajb_cfm_form' ) ) return;
preg_match_all( '/\[ajb_cfm_form[^\]]*id=["\'](\w[\w-]*)["\']/i', $content, $matches );
$form_ids = ! empty( $matches[1] ) ? $matches[1] : [ 'default' ];
// Also catch bare [ajb_cfm_form] with no id attribute
if ( has_shortcode( $content, 'ajb_cfm_form' ) && empty( $matches[1] ) ) {
$form_ids = [ 'default' ];
}
foreach ( $form_ids as $form_id ) {
$s = ajb_cfm_get_form( sanitize_key( $form_id ) );
if ( ! $s ) continue;
// Google Font
if ( ( $s['form_font'] ?? 'theme' ) === 'custom' && ! empty( $s['form_font_custom'] ) ) {
$fn = trim( $s['form_font_custom'] );
$family_encoded = str_replace( ' ', '+', $fn );
$font_url = 'https://fonts.googleapis.com/css2?family=' . $family_encoded . ':wght@400;500;600&display=swap';
$handle = 'ajb-cfm-font-' . sanitize_key( $fn );
wp_enqueue_style( $handle, $font_url, [], null ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion -- external font URL; version is part of the query string
$fid_css = sanitize_key( $form_id );
$font_css = '.cfm-form-wrap[data-form="' . $fid_css . '"],'
. '.cfm-form-wrap[data-form="' . $fid_css . '"] input,'
. '.cfm-form-wrap[data-form="' . $fid_css . '"] textarea,'
. '.cfm-form-wrap[data-form="' . $fid_css . '"] select,'
. '.cfm-form-wrap[data-form="' . $fid_css . '"] button,'
. '.cfm-form-wrap[data-form="' . $fid_css . '"] label,'
. '.cfm-form-wrap[data-form="' . $fid_css . '"] p'
. '{font-family:"' . esc_attr( $fn ) . '",sans-serif !important;}';
wp_add_inline_style( $handle, $font_css );
}
// Per-form scoped CSS (button colour, size, radius, alignment, label alignment)
$btn_color = $s['btn_color'] ?? '#2563eb';
$btn_size = $s['btn_size'] ?? 'medium';
$btn_radius = absint( $s['btn_radius'] ?? 8 );
$btn_align = $s['btn_align'] ?? 'left';
$label_align = $s['label_align'] ?? 'left';
$btn_padding = $btn_size === 'small' ? '8px 18px' : ( $btn_size === 'large' ? '16px 36px' : '12px 28px' );
$btn_font = $btn_size === 'small' ? '.85rem' : ( $btn_size === 'large' ? '1.05rem' : '1rem' );
list( $rr, $gg, $bb ) = sscanf( $btn_color, '#%02x%02x%02x' );
$luminance = ( 0.299 * ( $rr ?? 37 ) + 0.587 * ( $gg ?? 99 ) + 0.114 * ( $bb ?? 235 ) ) / 255;
$btn_text = $luminance > 0.55 ? '#1a1a1a' : '#ffffff';
$btn_width = $btn_align === 'full' ? 'width:100%;' : '';
$btn_margin = $btn_align === 'center' ? 'display:block;margin-left:auto;margin-right:auto;' : ( $btn_align === 'full' ? 'display:block;' : '' );
$fid_css = sanitize_key( $form_id );
$scoped_css = '.cfm-form-wrap[data-form="' . $fid_css . '"] .cfm-field label{text-align:' . esc_attr( $label_align ) . ';}'
. '.cfm-form-wrap[data-form="' . $fid_css . '"] .cfm-submit{'
. 'background:' . esc_attr( $btn_color ) . ' !important;'
. 'color:' . esc_attr( $btn_text ) . ' !important;'
. 'border-radius:' . $btn_radius . 'px !important;'
. 'padding:' . esc_attr( $btn_padding ) . ' !important;'
. 'font-size:' . esc_attr( $btn_font ) . ' !important;'
. $btn_width . $btn_margin . '}';
wp_add_inline_style( 'ajb-cfm-front', $scoped_css );
}
}
/* ================================================================== *
* [ajb_cfm_form] SHORTCODE
* ================================================================== */
add_shortcode( 'ajb_cfm_form', 'ajb_cfm_shortcode' );
function ajb_cfm_shortcode( $atts ) {
$atts = shortcode_atts(['id'=>'default','recipient'=>'','subject'=>''], $atts, 'ajb_cfm_form');
$form_id = sanitize_key( $atts['id'] );
$s = ajb_cfm_get_form( $form_id );
if ( ! $s ) {
// Form has been deleted — render nothing (shows a comment in source for debugging)
return '';
}
if ( empty($atts['recipient']) ) $atts['recipient'] = $s['recipient_email'];
if ( empty($atts['subject']) ) $atts['subject'] = $s['subject'];
$has_upload = false;
foreach($s['fields'] as $f) if($f['type']==='file'){$has_upload=true;break;}
// After-submit config
$after = $s['after_submit'] ?? 'inline';
$redirect_url = '';
$thankyou_url = '';
if ($after==='redirect' && !empty($s['redirect_page_id'])) $redirect_url = get_permalink($s['redirect_page_id']);
if ($after==='thankyou' && !empty($s['thankyou_page_id'])) $thankyou_url = get_permalink($s['thankyou_page_id']);
ob_start();
?>
'default'], $atts, 'ajb_cfm_thankyou');
$form_id = sanitize_key( $atts['id'] );
$s = ajb_cfm_get_form( $form_id );
if ( ! $s ) return '';
$data = [];
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- ajb_cfm_data is display-only placeholder data, not sensitive
if ( ! empty( $_GET['ajb_cfm_data'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only data passed via URL from our own redirect
$raw = base64_decode( sanitize_text_field( wp_unslash( $_GET['ajb_cfm_data'] ) ) );
$dec = json_decode($raw,true);
if(is_array($dec)) foreach($dec as $k=>$v) $data[sanitize_key($k)]=sanitize_text_field($v);
}
$heading = ajb_cfm_replace_placeholders($s['thankyou_heading']??'Thank you!',$data);
$body = ajb_cfm_replace_placeholders($s['thankyou_body']??'',$data);
$link_on = !empty($s['thankyou_link_enabled'])&&!empty($s['thankyou_link_url']);
ob_start();
?>
'Form not found.']);
if(!empty($_POST['ajb_cfm_website'])) wp_send_json_error(['message'=>'Submission blocked.']);
if(!empty($s['rate_limit_enabled'])){
$ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ?? '' ) );
$key = 'ajb_cfm_rl_'.md5($form_id.$ip);
$max = absint($s['rate_limit_max']??5);
$win = absint($s['rate_limit_window']??60);
$cnt = (int)get_transient($key);
if($cnt>=$max) wp_send_json_error(['message'=>'Too many submissions. Please wait before trying again.']);
set_transient($key,$cnt+1,$win*MINUTE_IN_SECONDS);
}
$data=[];$upload_info=[];
foreach($s['fields'] as $f){
$fid=$f['id'];
if($f['type']==='note') continue; // display-only, no POST value
if($f['type']==='file'){
if(!empty($_FILES[$fid]['name'])){
$res=ajb_cfm_handle_upload($fid,$s);
if(is_wp_error($res)) wp_send_json_error(['message'=>$res->get_error_message()]);
$data[$fid]=$res['url'];$upload_info[$fid]=$res;
} elseif($f['required']){ wp_send_json_error(['message'=>esc_html($f['label']).' is required.']); }
else $data[$fid]='';
continue;
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- nonce verified above; sanitized on next lines
$raw_val = wp_unslash( $_POST[ $fid ] ?? '' );
$val = $f['type']==='textarea' ? sanitize_textarea_field( $raw_val )
: ( $f['type']==='email' ? sanitize_email( $raw_val )
: ( $f['type']==='checkbox'? ( ! empty( $_POST[ $fid ] ) ? 'Yes' : 'No' )
: sanitize_text_field( $raw_val ) ) );
if($f['required']&&$val==='') wp_send_json_error(['message'=>esc_html($f['label']).' is required.']);
$data[$fid]=$val;
}
// Notification email
$to = sanitize_email( wp_unslash( $_POST['recipient'] ?? $s['recipient_email'] ) );
$subj = sanitize_text_field( wp_unslash( $_POST['subject'] ?? $s['subject'] ) );
$body = "New contact form submission [{$form_id}]:\n\n";
foreach($s['fields'] as $f){
if($f['type']==='file'&&!empty($upload_info[$f['id']])) { $body.=$f['label'].': '.$upload_info[$f['id']]['url']."\n"; }
elseif($f['type']!=='file'){
$v=$data[$f['id']]??'';
if($v!==''||$f['required']) $body.=$f['label'].': '.$v."\n";
}
}
$body.="\n--\n".get_bloginfo('name').' ('.get_bloginfo('url').')';
$headers=['Content-Type: text/plain; charset=UTF-8'];
$efid=$s['autoreply_email_field']??'email';
$nfid=$s['autoreply_name_field'] ??'name';
if(!empty($data[$efid])) $headers[]='Reply-To: '.($data[$nfid]??'Visitor').' <'.$data[$efid].'>';
$atts=array_filter(array_column($upload_info,'path'));
if(!wp_mail($to,$subj,$body,$headers,$atts))
wp_send_json_error(['message'=>'Sorry, there was a problem sending your message. Please try again.']);
if(!empty($s['autoreply_enabled'])&&!empty($data[$efid])){
wp_mail($data[$efid],ajb_cfm_replace_placeholders($s['autoreply_subject'],$data),ajb_cfm_replace_placeholders($s['autoreply_body'],$data),
['Content-Type: text/plain; charset=UTF-8','From: '.$s['recipient_name'].' <'.$s['recipient_email'].'>']);
}
$after=$s['after_submit']??'inline';
if($after==='inline'){
wp_send_json_success(['action'=>'inline','message'=>wp_kses_post(ajb_cfm_replace_placeholders($s['inline_message']??'Thank you!',$data)),'form_id'=>$form_id]);
}
if($after==='thankyou'&&!empty($s['thankyou_page_id'])){
$safe=[];
foreach($data as $k=>$v) if(strlen($k)<40&&$v&&$k!=='file') $safe[$k]=$v;
wp_send_json_success(['action'=>'redirect','url'=>esc_url_raw(add_query_arg('ajb_cfm_data',base64_encode(wp_json_encode($safe)),get_permalink($s['thankyou_page_id']))),'form_id'=>$form_id]);
}
if($after==='redirect'&&!empty($s['redirect_page_id'])){
wp_send_json_success(['action'=>'redirect','url'=>esc_url_raw(get_permalink($s['redirect_page_id'])),'form_id'=>$form_id]);
}
wp_send_json_success(['action'=>'inline','message'=>'Thank you! Your message has been sent.','form_id'=>$form_id]);
}
/* ================================================================== *
* FILE UPLOAD
* ================================================================== */
function ajb_cfm_handle_upload($fid,$s){
if(!function_exists('wp_handle_upload')){
require_once ABSPATH.'wp-admin/includes/file.php';
}
// phpcs:ignore WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized,WordPress.Security.ValidatedSanitizedInput.InputNotValidated -- nonce verified in ajb_cfm_handle_submit; file array validated below; wp_handle_upload() handles sanitization
if ( ! isset( $_FILES[ $fid ] ) || ! is_array( $_FILES[ $fid ] ) ) {
return new WP_Error( 'ajb_cfm', 'No file received.' );
}
$file = $_FILES[ $fid ];
$max=absint($s['upload_max_mb']??5);
$allowed=array_map('trim',explode(',',strtolower($s['upload_allowed_types']??'jpg,jpeg,png,gif,webp')));
if($file['size']>$max*1024*1024) return new WP_Error('ajb_cfm','File too large. Max '.$max.'MB.');
$ext=strtolower(pathinfo($file['name'],PATHINFO_EXTENSION));
if(!in_array($ext,$allowed,true)) return new WP_Error('ajb_cfm','File type not allowed. Accepted: '.implode(', ',$allowed));
// Build a restricted MIME list from the admin-configured extensions,
// explicitly blocking any executable or web-executable file types.
$dangerous = ['php','php3','php4','php5','php7','phtml','phar','js','jsx','ts','html','htm','xhtml','svg','svgz','css','pl','py','rb','sh','bash','exe','dll','bat','cmd','com','scr','vbs','htaccess','htpasswd','asp','aspx','cfm','cgi','shtml'];
add_filter('upload_mimes',function($m)use($allowed,$dangerous){
$safe=array_diff($allowed,$dangerous);
$k=[];
foreach($safe as $e){
if(isset($m[$e])) $k[$e]=$m[$e];
}
return $k;
});
$up=wp_handle_upload($file,['test_form'=>false]);
if(isset($up['error'])) return new WP_Error('ajb_cfm',$up['error']);
return['url'=>$up['url'],'path'=>$up['file'],'name'=>basename($up['file'])];
}
/* ================================================================== *
* PLACEHOLDER REPLACEMENT
* ================================================================== */
function ajb_cfm_replace_placeholders($text,$data){
foreach($data as $k=>$v) $text=str_replace('{'.$k.'}',$v,$text);
$text=str_replace('{site_name}',get_bloginfo('name'),$text);
$text=str_replace('{site_url}', get_bloginfo('url'), $text);
$text=str_replace('{date}', date_i18n(get_option('date_format')),$text);
$text=preg_replace('/^[^\n]*\{[a-z0-9_]+\}[^\n]*(\n|$)/m','',$text);
return trim($text);
}