Files
jenhomeforms/jenhome-contact-exports.php
josh 703e5a8692
All checks were successful
Test and publish WordPress plugin / release (push) Successful in 30s
Remove Source Link from Leads and Inquiries CSV exports
2026-10-28 13:36:18 -04:00

375 lines
22 KiB
PHP

<?php
/**
* Plugin Name: Jen Home Contact Fields and Exports
* Plugin URI: https://hostlabs.pro/
* Update URI: https://git.labs.casa/josh/jenhomeforms
* Description: Staging-only Houzez name/referral capture and protected CSV exports.
* Version: 1.2.2
* Requires at least: 6.2
* Requires PHP: 8.1
* Author: Josh Stevens Sr
* Author URI: https://hostlabs.pro/
*/
defined('ABSPATH') || exit;
final class Jenhome_Contact_Exports {
const VERSION = '1.2.2';
const ACTIONS = ['houzez_ele_inquiry_form', 'houzez_ele_contact_form', 'houzez_property_agent_contact', 'houzez_schedule_send_message', 'houzez_contact_realtor'];
// Verified Elementor widgets: contact page and the two Get Started popups.
const REFERRAL_FORMS = ['6o0tsaob0', '1cbfa42a', '2a2beb9b'];
const REFERRER_FORMS = ['6o0tsaob0', '1cbfa42a'];
private static $referrer_form = '';
private static $middle_name = '';
private static $submission_ready = false;
private static $collector_wrapped = false;
public static function boot() {
// Fail closed on production, including if a staging clone is later copied there.
if (wp_parse_url(home_url(), PHP_URL_HOST) !== 'staging.jenhome.net'
|| basename(untrailingslashit(ABSPATH)) !== 'staging.jenhome.net') return;
require_once __DIR__ . '/gitea-updater.php';
Jenhome_Gitea_Updater::boot(__FILE__);
self::install_storage();
add_action('wp_enqueue_scripts', [__CLASS__, 'assets']);
add_filter('elementor/widget/render_content', [__CLASS__, 'widget'], 30, 2);
add_filter('wp_mail', [__CLASS__, 'mail_fields']);
add_action('wp_loaded', [__CLASS__, 'wrap_collector'], 20);
require_once __DIR__ . '/crm-display.php';
Jenhome_CRM_Display::boot();
foreach (['houzez_property_agent_contact_fields', 'houzez_schedule_tour_fields', 'houzez_realtor_contact_form_fields'] as $hook) {
add_action($hook, [__CLASS__, 'native_fields']);
}
foreach (self::ACTIONS as $action) {
add_action('wp_ajax_' . $action, [__CLASS__, 'prepare'], 0);
add_action('wp_ajax_nopriv_' . $action, [__CLASS__, 'prepare'], 0);
}
// Keep the existing buttons/endpoints. Run before (and terminate before) vendor exports.
add_action('wp_ajax_houzez_crm_export_leads', [__CLASS__, 'export_leads'], 0);
add_action('wp_ajax_crm_export_inquiries', [__CLASS__, 'export_inquiries'], 0);
}
/** Site-owned extension data: no changes to the vendor's tables or historical rows. */
public static function install_storage() {
if (get_option('jenhome_contact_fields_schema') === '1') return;
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$table = $wpdb->prefix . 'jenhome_contact_fields';
$collate = $wpdb->get_charset_collate();
dbDelta("CREATE TABLE $table (
lead_id bigint(20) unsigned NOT NULL,
enquiry_id bigint(20) unsigned NOT NULL DEFAULT 0,
middle_name text NOT NULL,
referrer_form varchar(32) NOT NULL DEFAULT '',
PRIMARY KEY (lead_id)
) ENGINE=InnoDB $collate;");
if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $wpdb->esc_like($table))) === $table) {
update_option('jenhome_contact_fields_schema', '1', false);
}
}
public static function referrals() {
$settings = get_option('hcrm_lead_settings', []);
return array_values(array_filter(array_map('trim', explode(',', (string)($settings['source'] ?? '')))));
}
public static function assets() {
wp_enqueue_script('jenhome-contact-exports', plugins_url('forms.js', __FILE__), ['jquery'], self::VERSION, true);
wp_localize_script('jenhome-contact-exports', 'JenhomeContact', [
'actions' => self::ACTIONS, 'referralForms' => self::REFERRAL_FORMS,
'referrals' => self::referrals(), 'nonce' => wp_create_nonce('jenhome_contact'),
'exportNonce' => is_user_logged_in() ? wp_create_nonce('jenhome_export') : '',
]);
wp_register_style('jenhome-contact-exports', false, [], self::VERSION);
wp_enqueue_style('jenhome-contact-exports');
wp_add_inline_style('jenhome-contact-exports', '.jenhome-fields{width:100%;flex:0 0 100%;display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:16px}.jenhome-field{min-width:0;display:flex;flex-direction:column;justify-content:flex-end}.jenhome-referral{grid-column:1/-1}.jenhome-field label{display:block;margin-bottom:5px}.jenhome-field .form-control{width:100%}@media(max-width:480px){.jenhome-fields{grid-template-columns:1fr}}');
}
public static function fields($first = true, $last = true, $referral = true, $middle = true) {
$html = ($first || $last || $referral || $middle) ? '<div class="jenhome-fields">' : '';
foreach (['first_name' => ['First Name', 'given-name', $first], 'middle_name' => ['Middle Name (optional)', 'additional-name', $middle], 'last_name' => ['Last Name', 'family-name', $last]] as $key => $field) {
if (!$field[2]) continue;
$id = wp_unique_id('jenhome-' . $key . '-');
$html .= '<div class="jenhome-field"><label for="' . esc_attr($id) . '">' . esc_html($field[0]) . '</label><input class="form-control" type="text" name="' . esc_attr($key) . '" id="' . esc_attr($id) . '" autocomplete="' . esc_attr($field[1]) . '"' . ($key === 'middle_name' ? '' : ' required') . '></div>';
}
if ($referral) {
$id = wp_unique_id('jenhome-referral-');
$html .= '<div class="jenhome-field jenhome-referral"><label for="' . esc_attr($id) . '">How did you hear about us?</label><select class="form-control" name="referral_source" id="' . esc_attr($id) . '" required><option value="">Please select</option>';
foreach (self::referrals() as $value) $html .= '<option value="' . esc_attr($value) . '">' . esc_html($value) . '</option>';
$html .= '</select></div>';
}
return $html . (($first || $last || $referral || $middle) ? '</div>' : '') . '<input type="hidden" name="jenhome_contact_nonce" value="' . esc_attr(wp_create_nonce('jenhome_contact')) . '">';
}
public static function native_fields() { echo self::fields(); }
/** Render-time adaptation leaves saved Elementor layouts and vendor templates intact. */
public static function widget($html, $widget) {
if (strpos($widget->get_name(), 'houzez') !== 0 || strpos($html, '<form') === false) return $html;
return preg_replace_callback('~<form\b[^>]*>.*?</form>~is', function($match) {
$form = $match[0];
$p = new WP_HTML_Tag_Processor($form);
$action = $form_id = '';
while ($p->next_tag()) {
if ($p->get_attribute('name') === 'action') $action = $p->get_attribute('value');
if ($p->get_attribute('name') === 'form_id') $form_id = $p->get_attribute('value');
}
if (!in_array($action, self::ACTIONS, true)) return $form;
$p = new WP_HTML_Tag_Processor($form);
$names = [];
while ($p->next_tag()) {
$name = $p->get_attribute('name');
if ($name === 'enquiry_type' && in_array($form_id, self::REFERRAL_FORMS, true)) {
$p->set_attribute('name', 'referral_source');
$name = 'referral_source';
}
if ($name === 'e_meta[streat_address]' && in_array($form_id, self::REFERRER_FORMS, true)) {
$p->set_attribute('name', 'referrer_name');
$name = 'referrer_name';
}
if (in_array($name, ['first_name', 'last_name'], true)) {
$p->set_attribute('required', true);
$p->set_attribute('autocomplete', $name === 'first_name' ? 'given-name' : 'family-name');
}
$names[] = $name;
}
$form = $p->get_updated_html();
if (!in_array('jenhome_contact_nonce', $names, true)) {
$fields = self::fields(!in_array('first_name', $names, true), !in_array('last_name', $names, true), !in_array('referral_source', $names, true), !in_array('middle_name', $names, true));
// Existing name fields stay in place; newly needed fields precede the submit button.
$pos = stripos($form, '<button');
if ($pos === false) $pos = strripos($form, '</form>');
$form = substr_replace($form, $fields, $pos, 0);
}
return $form;
}, $html);
}
private static function input($key) {
return isset($_POST[$key]) && is_scalar($_POST[$key]) ? sanitize_text_field(wp_unslash((string)$_POST[$key])) : '';
}
public static function prepare() {
self::$referrer_form = '';
self::$middle_name = '';
self::$submission_ready = false;
if (!wp_verify_nonce(self::input('jenhome_contact_nonce'), 'jenhome_contact')) {
wp_send_json(['success' => false, 'msg' => 'Please refresh this page and try again.'], 403);
}
$first = self::input('first_name');
$middle = self::input('middle_name');
$last = self::input('last_name');
$referral = self::input('referral_source');
$known = self::input('action') === 'houzez_ele_inquiry_form' && in_array(self::input('form_id'), self::REFERRAL_FORMS, true);
// Compatibility for a previously rendered copy of these three verified forms only.
if ($known && $referral === '') $referral = self::input('enquiry_type');
if ($first === '' || $last === '' || $referral === '') {
wp_send_json(['success' => false, 'msg' => 'Please enter your first name, last name, and how you heard about us.'], 400);
}
if (get_option('jenhome_contact_fields_schema') !== '1') wp_send_json(['success' => false, 'msg' => 'This form is temporarily unavailable. Please try again shortly.'], 503);
// Native Houzez setters do not unslash these fields. Supply clean, scalar values once.
$_POST['first_name'] = $first;
$_POST['middle_name'] = self::$middle_name = $middle;
$_POST['last_name'] = $last;
$_POST['name'] = implode(' ', array_filter([$first, $middle, $last], function($value) { return $value !== ''; }));
self::$submission_ready = true;
$_POST['referral_source'] = $referral;
$_POST['source'] = $referral;
if ($known) unset($_POST['enquiry_type']);
if ($known && in_array(self::input('form_id'), self::REFERRER_FORMS, true)) {
self::$referrer_form = self::input('form_id');
$meta = isset($_POST['e_meta']) && is_array($_POST['e_meta']) ? $_POST['e_meta'] : [];
$friend = isset($_POST['referrer_name']) ? self::input('referrer_name')
: (isset($meta['streat_address']) && is_scalar($meta['streat_address']) ? sanitize_text_field(wp_unslash($meta['streat_address'])) : '');
$_POST['referrer_name'] = $friend;
// Keep the native field editable and compatible; attach its verified meaning below.
$meta['streat_address'] = $friend;
$_POST['e_meta'] = $meta;
}
$link = self::input('property_permalink') ?: self::input('source_link');
$_POST['source_link'] = esc_url_raw($link);
// Original handler still performs its nonce/captcha/rate-limit and mail checks.
// The original collector creates a new lead per submission; no email-based merging.
}
/** Wrap only the existing collector, preserving its persistence and exact new-row identity. */
public static function wrap_collector() {
if (self::$collector_wrapped) return;
global $wp_filter;
foreach (['houzez_after_agent_form_submission', 'houzez_after_contact_form_submission', 'houzez_after_estimation_form_submission'] as $hook) {
foreach (($wp_filter[$hook]->callbacks ?? []) as $priority => $callbacks) {
foreach ($callbacks as $entry) {
$callback = $entry['function'];
if (!is_array($callback) || !($callback[0] instanceof Houzez_Collect_Form_Data) || $callback[1] !== 'save_form_data') continue;
remove_action($hook, $callback, $priority);
add_action($hook, function() use ($callback) {
call_user_func($callback);
self::capture_new_fields();
}, $priority);
self::$collector_wrapped = true;
}
}
}
}
private static function capture_new_fields() {
global $wpdb;
if (!self::$submission_ready) return;
$leads = $wpdb->prefix . 'houzez_crm_leads';
$inquiries = $wpdb->prefix . 'houzez_crm_enquiries';
// Do not infer an ID by email, timestamp, MAX(id), or a later database query.
if ($wpdb->rows_affected !== 1 || !$wpdb->insert_id) return;
$id = (int)$wpdb->insert_id;
$enquiry_id = 0;
if (preg_match('/^INSERT INTO `' . preg_quote($inquiries, '/') . '`\s/i', $wpdb->last_query)) {
$lead_id = (int)$wpdb->get_var($wpdb->prepare("SELECT lead_id FROM $inquiries WHERE enquiry_id=%d", $id));
$enquiry_id = $id;
} elseif (preg_match('/^INSERT INTO `' . preg_quote($leads, '/') . '`\s/i', $wpdb->last_query)) {
$lead_id = $id;
} else return;
if (!$lead_id) return;
$form = $enquiry_id && self::input('is_estimation') === 'yes' && empty($_POST['listing_id']) ? self::$referrer_form : '';
if (self::$middle_name === '' && $form === '') return;
$wpdb->insert($wpdb->prefix . 'jenhome_contact_fields', ['lead_id' => $lead_id, 'enquiry_id' => $enquiry_id, 'middle_name' => self::$middle_name, 'referrer_form' => $form], ['%d', '%d', '%s', '%s']);
}
public static function meta($value) {
$meta = is_serialized($value) ? @unserialize(trim($value), ['allowed_classes' => false]) : [];
return is_array($meta) ? $meta : [];
}
public static function submission_date($utc) {
if (!is_string($utc) || !preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $utc)) return '';
$date = DateTimeImmutable::createFromFormat('!Y-m-d H:i:s', $utc, new DateTimeZone('UTC'));
if (!$date || $date->format('Y-m-d H:i:s') !== $utc) return '';
return $date->setTimezone(wp_timezone())->format('Y-m-d H:i:s P');
}
public static function has_referrer_mapping($row, $meta) {
if (!empty($row['listing_id'])) return false;
if (!empty($row['enquiry_id']) && (int)$row['enquiry_id'] === (int)($row['jenhome_enquiry_id'] ?? 0)
&& in_array($row['jenhome_referrer_form'] ?? '', self::REFERRER_FORMS, true)) return true;
if (in_array($meta['jenhome_referrer_form'] ?? '', self::REFERRER_FORMS, true)) return true;
// Conservative display/export fallback for the verified legacy contact/signup URLs.
// Unclassified legacy values are still exported separately as Street Address.
$url = html_entity_decode($row['source_link'] ?? '', ENT_QUOTES, 'UTF-8');
if (!in_array(wp_parse_url($url, PHP_URL_HOST), ['staging.jenhome.net', 'jenhome.net', 'www.jenhome.net'], true)) return false;
if (!empty($meta['property_type']) || !empty($meta['min_price']) || !empty($meta['min_beds'])) return false;
$path = untrailingslashit(wp_parse_url($url, PHP_URL_PATH) ?: '/');
$query = wp_parse_url($url, PHP_URL_QUERY) ?: '';
foreach ([37, 983] as $id) {
$known_url = get_permalink($id);
$known_path = untrailingslashit(wp_parse_url($known_url, PHP_URL_PATH) ?: '/');
$known_query = wp_parse_url($known_url, PHP_URL_QUERY) ?: '';
if (($known_path !== '' || $known_query !== '') && $path === $known_path && $query === $known_query) return true;
}
$paths = ['/contact', '/elementor_library/get-started-popup-form'];
// A bare home-page URL is not proof of which form collected a historical value.
$paths = array_filter($paths, function($p) { return $p !== ''; });
return in_array($path, $paths, true) && $query === '';
}
public static function referrer_name($row, $meta) {
return self::has_referrer_mapping($row, $meta) && is_scalar($meta['streat_address'] ?? '') ? (string)($meta['streat_address'] ?? '') : '';
}
public static function referral_source($row) {
return !empty($row['source']) ? $row['source'] : ($row['lead_source'] ?? '');
}
public static function authorize_export() {
if (!is_user_logged_in() || !current_user_can('read')) wp_die('Forbidden', '', ['response' => 403]);
check_ajax_referer('jenhome_export', 'jenhome_export_nonce');
}
public static function mail_fields($args) {
if (wp_doing_ajax() && in_array(self::input('action'), self::ACTIONS, true)
&& wp_verify_nonce(self::input('jenhome_contact_nonce'), 'jenhome_contact')
&& self::input('referral_source') !== '') {
// Keep the visitor's answer visible in the existing HTML notification emails.
$args['message'] .= '<p><strong>Referral Source:</strong> ' . esc_html($_POST['referral_source']) . '</p>';
if (self::$referrer_form) $args['message'] = str_replace('Street Address : ', 'Referrer Name : ', $args['message']);
}
return $args;
}
public static function csv_cell($value) {
$value = is_scalar($value) ? (string)$value : '';
// Include whitespace/control characters before formula introducers, and tab/newline prefixes.
if (preg_match('/^[\s\p{Z}\p{Cc}]*[=+@-]|^[\t\r\n]/u', $value)) $value = "'" . $value;
return $value;
}
public static function write_csv($filename, $headings, $rows) {
nocache_headers();
header('Content-Type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
$out = fopen('php://output', 'w');
// BOM makes Unicode names open correctly in Excel; all fields are RFC 4180 quoted.
fwrite($out, "\xEF\xBB\xBF");
fputcsv($out, $headings, ',', '"', '', "\r\n");
foreach ($rows as $row) fputcsv($out, array_map([__CLASS__, 'csv_cell'], $row), ',', '"', '', "\r\n");
fclose($out);
wp_die();
}
public static function lead_rows($user_id) {
global $wpdb;
$fields = ['time', 'first_name', 'middle_name', 'last_name', 'source', 'referrer_name', 'prefix', 'display_name', 'email', 'mobile', 'home_phone', 'work_phone', 'address', 'city', 'state', 'country', 'zipcode', 'type', 'twitter_url', 'linkedin_url', 'facebook_url', 'private_note', 'message', 'inquiry_street_address'];
$rows = $wpdb->get_results($wpdb->prepare("SELECT l.*, f.middle_name FROM {$wpdb->prefix}houzez_crm_leads l LEFT JOIN {$wpdb->prefix}jenhome_contact_fields f ON f.lead_id=l.lead_id WHERE l.user_id = %d ORDER BY l.lead_id", $user_id), ARRAY_A);
$related = [];
foreach (self::inquiry_records($user_id) as $inquiry) {
$meta = self::meta($inquiry['enquiry_meta']);
$friend = self::referrer_name($inquiry, $meta);
$address = self::has_referrer_mapping($inquiry, $meta) ? '' : ($meta['streat_address'] ?? '');
if ($friend !== '') $related[$inquiry['lead_id']]['referrer_name'][] = $friend;
if (is_scalar($address) && $address !== '') $related[$inquiry['lead_id']]['inquiry_street_address'][] = (string)$address;
}
return array_map(function($row) use ($fields, $related) {
$row['time'] = self::submission_date($row['time'] ?? '');
foreach (['referrer_name', 'inquiry_street_address'] as $key) $row[$key] = implode('; ', array_unique($related[$row['lead_id']][$key] ?? []));
return array_map(function($f) use ($row) { return $row[$f] ?? ''; }, $fields);
}, $rows);
}
public static function export_leads() {
self::authorize_export();
self::write_csv('leads.csv', ['Submission Date', 'First Name', 'Middle Name', 'Last Name', 'Referral Source', 'Referrer Name', 'Prefix', 'Full Name', 'Email', 'Mobile', 'Home Phone', 'Work Phone', 'Address', 'City', 'County / State', 'Country', 'Postal Code / Zip', 'Type', 'Twitter', 'Linkedin', 'Facebook', 'Private Note', 'Message', 'Inquiry Street Address'], self::lead_rows(get_current_user_id()));
}
public static function inquiry_records($user_id, $ids = null) {
global $wpdb;
$where = '';
if ($ids !== null) {
$ids = array_values(array_unique(array_filter(array_map('absint', $ids))));
if (!$ids) return [];
$where = ' AND e.enquiry_id IN (' . implode(',', $ids) . ')';
}
return $wpdb->get_results($wpdb->prepare("SELECT e.*, l.first_name, f.middle_name, l.last_name, l.display_name, l.email, l.mobile, l.source AS lead_source, l.source_link, f.referrer_form AS jenhome_referrer_form, f.enquiry_id AS jenhome_enquiry_id FROM {$wpdb->prefix}houzez_crm_enquiries e INNER JOIN {$wpdb->prefix}houzez_crm_leads l ON e.lead_id = l.lead_id LEFT JOIN {$wpdb->prefix}jenhome_contact_fields f ON f.lead_id = l.lead_id WHERE e.user_id = %d AND l.user_id = %d $where ORDER BY e.enquiry_id", $user_id, $user_id), ARRAY_A);
}
public static function lead_middle_name($id, $user_id) {
global $wpdb;
return (string)$wpdb->get_var($wpdb->prepare("SELECT f.middle_name FROM {$wpdb->prefix}houzez_crm_leads l INNER JOIN {$wpdb->prefix}jenhome_contact_fields f ON f.lead_id=l.lead_id WHERE l.lead_id=%d AND l.user_id=%d", $id, $user_id));
}
public static function inquiry_rows($user_id) {
$rows = self::inquiry_records($user_id);
return array_map(function($row) {
// Never reinterpret historical enquiry_type values or split display_name.
$meta = self::meta($row['enquiry_meta']);
return [
self::submission_date($row['time'] ?? ''),
$row['first_name'] ?? '', $row['middle_name'] ?? '', $row['last_name'] ?? '',
self::referral_source($row), self::referrer_name($row, $meta),
$row['email'] ?? '', $row['mobile'] ?? '',
];
}, $rows);
}
public static function export_inquiries() {
self::authorize_export();
self::write_csv('inquiries.csv', ['Submission Date', 'First Name', 'Middle Name', 'Last Name', 'Referral Source', 'Referrer Name', 'Email', 'Mobile'], self::inquiry_rows(get_current_user_id()));
}
}
add_action('plugins_loaded', ['Jenhome_Contact_Exports', 'boot']);