From 552c60981c67d8ffa6cade4ddd7d30780afc6da1 Mon Sep 17 00:00:00 2001
From: josh
Date: Wed, 28 Oct 2026 13:14:12 -0400
Subject: [PATCH] Add Houzez form exports and verified Gitea release updates
---
.gitea/workflows/release.yaml | 43 ++++
.gitignore | 5 +
CHANGELOG.md | 14 ++
README.md | 99 +++++++++
crm-display.php | 142 +++++++++++++
forms.js | 134 ++++++++++++
gitea-updater.php | 145 +++++++++++++
jenhome-contact-exports.php | 376 ++++++++++++++++++++++++++++++++++
scripts/build-release.py | 22 ++
scripts/publish-release.py | 54 +++++
tests/unit.php | 115 +++++++++++
11 files changed, 1149 insertions(+)
create mode 100644 .gitea/workflows/release.yaml
create mode 100644 .gitignore
create mode 100644 CHANGELOG.md
create mode 100644 crm-display.php
create mode 100644 forms.js
create mode 100644 gitea-updater.php
create mode 100644 jenhome-contact-exports.php
create mode 100644 scripts/build-release.py
create mode 100644 scripts/publish-release.py
create mode 100644 tests/unit.php
diff --git a/.gitea/workflows/release.yaml b/.gitea/workflows/release.yaml
new file mode 100644
index 0000000..e5a2204
--- /dev/null
+++ b/.gitea/workflows/release.yaml
@@ -0,0 +1,43 @@
+name: Test and publish WordPress plugin
+on:
+ push:
+ branches: [main]
+ tags: ['v*']
+
+jobs:
+ release:
+ runs-on: ubuntu-latest
+ container:
+ image: php:8.4-cli-bookworm
+ permissions:
+ contents: write
+ env:
+ SOURCE_COMMIT: ${{ gitea.sha }}
+ steps:
+ - name: Install build tools
+ run: |
+ apt-get update -qq
+ apt-get install -y --no-install-recommends git python3 libzip-dev
+ docker-php-ext-install zip
+ - name: Check out the triggering commit
+ run: |
+ git init .
+ git remote add origin https://git.labs.casa/josh/jenhomeforms.git
+ git fetch --depth=1 origin "$SOURCE_COMMIT"
+ git checkout --detach FETCH_HEAD
+ - name: Validate PHP and behavior
+ run: |
+ php -l jenhome-contact-exports.php
+ php -l crm-display.php
+ php -l gitea-updater.php
+ php tests/unit.php
+ - name: Build release package
+ run: python3 scripts/build-release.py
+ - name: Publish stable tag
+ if: startsWith(gitea.ref, 'refs/tags/v')
+ env:
+ GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
+ RELEASE_TAG: ${{ gitea.ref_name }}
+ run: |
+ python3 scripts/build-release.py "$RELEASE_TAG"
+ python3 scripts/publish-release.py
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..802fb54
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+/dist/
+.env
+*.log
+__pycache__/
+*.pyc
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..e72c5c8
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,14 @@
+## 1.2.0
+
+- Add WordPress-managed updates from published stable Gitea releases.
+- Verify the release checksum, package contents and version before installation.
+- Reduce Inquiries exports to Submission Date, First Name, Middle Name, Last Name,
+ Referral Source, Referrer Name, Source Link, Email and Mobile.
+- Keep Leads exports, CRM views, saved records and staging-only restrictions intact.
+
+## 1.1.1
+
+- Separate first, optional middle and last names across contact forms and exports.
+- Submission Date first in both CSVs, with the site's timezone and UTC offset.
+- Show referral source and friend/referrer names in CRM views and exports.
+- Author: Josh Stevens Sr. Website: https://hostlabs.pro/.
diff --git a/README.md b/README.md
index e69de29..bac57c4 100644
--- a/README.md
+++ b/README.md
@@ -0,0 +1,99 @@
+# Jen Home Contact Fields and Exports
+
+WordPress/Houzez customization for **staging.jenhome.net**.
+
+Author: **Josh Stevens Sr** · Website: [hostLabs](https://hostlabs.pro/)
+
+The installed plugin directory remains `jenhome-contact-exports`; the Gitea
+repository is named `jenhomeforms`.
+
+## Behavior
+
+Contact forms collect First Name, optional Middle Name, Last Name and the visitor's
+answer to “How did you hear about us?”. The existing friend-name question is
+identified separately from a property address. Original forms, CRM persistence,
+notifications and existing security checks remain in place.
+
+Inquiries CSV columns, in order:
+
+1. Submission Date
+2. First Name
+3. Middle Name
+4. Last Name
+5. Referral Source
+6. Referrer Name
+7. Source Link
+8. Email
+9. Mobile
+
+Submission dates use America/New_York with an explicit UTC offset. Leads exports
+retain their existing fields. CRM views still show inquiry/property details even
+though the shorter Inquiries CSV omits them. Historical records are not backfilled
+or split; relationships use IDs, never email matching.
+
+The plugin creates a prefixed `jenhome_contact_fields` extension table for middle
+names and exact submission provenance. Native Houzez tables and vendor files are
+not modified. Keep this table when rolling back or deactivating the plugin.
+
+## Releases and WordPress updates
+
+The owner-created repository is public. WordPress needs no repository credential.
+The `Update URI` points to this repository, while the plugin website remains
+hostLabs. An active staging installation checks the latest published stable
+`vMAJOR.MINOR.PATCH` Gitea release through WordPress's update system.
+
+Every release must include:
+
+- `jenhome-contact-exports-VERSION.zip`
+- `jenhome-contact-exports-VERSION.zip.sha256`
+
+Only the four runtime files belong in the ZIP, under `jenhome-contact-exports/`.
+The build script produces that layout. The updater checks the checksum, exact
+file list, ZIP version and same-host HTTPS download redirects. Drafts, prereleases,
+incomplete releases and unverified packages are ignored or rejected. A failed
+check leaves the installed plugin in place. Metadata is cached for one hour;
+opening WordPress Dashboard → Updates clears this plugin's metadata cache.
+
+WordPress can install through **Update now** or its native **Enable auto-updates**
+setting. Automatic updates run on WordPress's cron schedule, not on every Git push.
+The plugin must remain active for its updater to run.
+
+## Publishing
+
+Gitea Actions must have an online Docker-capable runner labeled `ubuntu-latest`.
+The workflow uses the official PHP 8.4 container and the job's ephemeral repository
+token. It never needs the WordPress SSH key or a permanent Gitea token.
+
+1. Edit code and `CHANGELOG.md`; update both the plugin header Version and
+ `Jenhome_Contact_Exports::VERSION`.
+2. Commit and push to `main`. The workflow lints PHP, runs the standalone updater
+ and CSV tests, and builds the ZIP.
+3. After checks and staging validation pass, create and push a matching tag:
+ `git tag v1.2.1` then `git push origin v1.2.1`.
+4. The tag workflow repeats checks, builds the package, uploads both assets to a
+ draft, and publishes the release only after uploads succeed.
+
+Published versions are not overwritten. If a publishing job stops with a partial
+draft, review that draft and its assets before retrying, or publish a new version.
+Do not use Gitea's automatically generated source archive as the WordPress ZIP.
+
+Local checks (PHP 8.1+ with ZIP support, Python 3):
+
+```sh
+php tests/unit.php
+python3 scripts/build-release.py v1.2.0
+```
+
+## Scope and rollback
+
+The plugin runs only when both the home URL and WordPress directory identify
+`staging.jenhome.net`. Installing it on production does not enable its behavior or
+updater. A production rollout requires a separately reviewed scope change.
+
+Back up the current plugin directory before the first updater installation.
+Deactivate this plugin to return to native behavior, or reinstall the previous
+verified plugin ZIP. Preserve the extension table and all contact records.
+
+The repository contains no credentials, contact records, database dumps or vendor
+source. Server integration tests use separate private synthetic fixtures with
+email/webhook suppression and transaction rollback.
diff --git a/crm-display.php b/crm-display.php
new file mode 100644
index 0000000..85a2c26
--- /dev/null
+++ b/crm-display.php
@@ -0,0 +1,142 @@
+createElement($tag);
+ $node->appendChild($doc->createTextNode(is_scalar($value) ? (string)$value : ''));
+ return $node;
+ }
+
+ private static function row_id($xpath, $row) {
+ $input = $xpath->query('.//input[@name="enquiry_multi_delete[]"]', $row)->item(0);
+ if ($input) return absint($input->getAttribute('value'));
+ foreach ($xpath->query('.//a[@href]', $row) as $link) {
+ parse_str(wp_parse_url(html_entity_decode($link->getAttribute('href')), PHP_URL_QUERY) ?: '', $args);
+ if (isset($args['enquiry'])) return absint($args['enquiry']);
+ }
+ return 0;
+ }
+
+ public static function decorate($html, $detail_id = 0, $lead_id = 0) {
+ if (!is_user_logged_in() || !current_user_can('read') || !class_exists('DOMDocument')) return $html;
+ $doc = new DOMDocument('1.0', 'UTF-8');
+ $old = libxml_use_internal_errors(true);
+ $ok = $doc->loadHTML('
' . $html . '
', LIBXML_NONET);
+ libxml_clear_errors();
+ libxml_use_internal_errors($old);
+ if (!$ok) return $html;
+ $xpath = new DOMXPath($doc);
+ $root = $doc->getElementById('jenhome-fragment');
+ if (!$root) return $html;
+ if ($lead_id) {
+ $middle = Jenhome_Contact_Exports::lead_middle_name($lead_id, get_current_user_id());
+ $list = $xpath->query('.//div[contains(concat(" ", normalize-space(@class), " "), " inquiry-detail ")]/ul', $root)->item(0);
+ if ($list && $middle !== '') {
+ $li = $doc->createElement('li'); $li->setAttribute('class', 'border-bottom pb-2 jenhome-crm-field');
+ $li->appendChild(self::text_node($doc, 'strong', 'Middle Name')); $li->appendChild($doc->createElement('br'));
+ $li->appendChild($doc->createTextNode($middle));
+ $anchor = $xpath->query('./li', $list)->item(0);
+ if ($anchor) $list->insertBefore($li, $anchor->nextSibling); else $list->appendChild($li);
+ }
+ }
+ $ids = $detail_id ? [$detail_id] : [];
+ foreach ($xpath->query('.//tbody/tr', $root) as $tr) { $id = self::row_id($xpath, $tr); if ($id) $ids[] = $id; }
+ $records = [];
+ foreach (Jenhome_Contact_Exports::inquiry_records(get_current_user_id(), $ids) as $record) $records[$record['enquiry_id']] = $record;
+ if ($detail_id && isset($records[$detail_id])) {
+ $record = $records[$detail_id];
+ $meta = Jenhome_Contact_Exports::meta($record['enquiry_meta']);
+ $list = $xpath->query('.//div[contains(concat(" ", normalize-space(@class), " "), " inquiry-detail ")]/ul', $root)->item(0);
+ if ($list) {
+ $anchor = $xpath->query('./li', $list)->item(0);
+ $values = [
+ 'Submission Date' => Jenhome_Contact_Exports::submission_date($record['time'] ?? ''),
+ 'First Name' => $record['first_name'] ?? '', 'Middle Name' => $record['middle_name'] ?? '', 'Last Name' => $record['last_name'] ?? '',
+ 'Referral Source' => Jenhome_Contact_Exports::referral_source($record),
+ 'Referrer Name' => Jenhome_Contact_Exports::referrer_name($record, $meta),
+ 'Source Link' => html_entity_decode($record['source_link'] ?? '', ENT_QUOTES, 'UTF-8'),
+ ];
+ foreach ($values as $label => $value) {
+ $li = $doc->createElement('li'); $li->setAttribute('class', 'border-bottom pb-2 jenhome-crm-field');
+ $li->appendChild(self::text_node($doc, 'strong', $label)); $li->appendChild($doc->createElement('br'));
+ if ($label === 'Source Link' && $value !== '') {
+ $link = self::text_node($doc, 'a', $value); $link->setAttribute('href', esc_url($value)); $li->appendChild($link);
+ } else $li->appendChild($doc->createTextNode($value !== '' ? $value : '—'));
+ if ($anchor) $list->insertBefore($li, $anchor->nextSibling); else $list->appendChild($li);
+ $anchor = $li;
+ }
+ if (Jenhome_Contact_Exports::has_referrer_mapping($record, $meta)) {
+ // The same value is now shown once, under its correct label above.
+ foreach ($xpath->query('./li/strong', $list) as $label) {
+ if (trim($label->textContent) === __('Street Address', 'houzez')) $list->removeChild($label->parentNode);
+ }
+ }
+ }
+ }
+ if (!$detail_id) {
+ foreach ($xpath->query('.//table', $root) as $table) {
+ $header = $xpath->query('./thead/tr', $table)->item(0);
+ if (!$header) continue;
+ $has_records = false;
+ foreach ($xpath->query('./tbody/tr', $table) as $tr) if (self::row_id($xpath, $tr)) $has_records = true;
+ if (!$has_records) continue;
+ $anchor = null;
+ foreach ($xpath->query('./th', $header) as $th) if (trim($th->textContent) === __('Inquiry Type', 'houzez')) $anchor = $th;
+ foreach (['Referral Source', 'Referrer Name'] as $label) {
+ $th = self::text_node($doc, 'th', $label); $th->setAttribute('data-label', $label);
+ if ($anchor) $header->insertBefore($th, $anchor->nextSibling); else $header->appendChild($th);
+ $anchor = $th;
+ }
+ foreach ($xpath->query('./tbody/tr', $table) as $tr) {
+ $record = $records[self::row_id($xpath, $tr)] ?? null;
+ $meta = $record ? Jenhome_Contact_Exports::meta($record['enquiry_meta']) : [];
+ $values = ['Referral Source' => $record ? Jenhome_Contact_Exports::referral_source($record) : '', 'Referrer Name' => $record ? Jenhome_Contact_Exports::referrer_name($record, $meta) : ''];
+ $anchor = null;
+ foreach ($xpath->query('./td', $tr) as $td) if ($td->getAttribute('data-label') === __('Inquiry Type', 'houzez')) $anchor = $td;
+ foreach ($values as $label => $value) {
+ $td = self::text_node($doc, 'td', $value !== '' ? $value : '—'); $td->setAttribute('data-label', $label);
+ if ($anchor) $tr->insertBefore($td, $anchor->nextSibling); else $tr->appendChild($td);
+ $anchor = $td;
+ }
+ }
+ }
+ }
+ $out = '';
+ foreach ($root->childNodes as $child) $out .= $doc->saveHTML($child);
+ return $out;
+ }
+}
diff --git a/forms.js b/forms.js
new file mode 100644
index 0000000..09b0939
--- /dev/null
+++ b/forms.js
@@ -0,0 +1,134 @@
+(function ($) {
+ 'use strict';
+ const config = window.JenhomeContact;
+ if (!config) return;
+ let nextId = 0;
+ const enhanced = new WeakSet();
+ const field = (form, name) => form.elements.namedItem(name);
+ const value = (form, name) => field(form, name)?.value || '';
+ const relevant = form => config.actions.includes(value(form, 'action'));
+ function hidden(form, name, val) {
+ let el = field(form, name);
+ if (!el) { el = document.createElement('input'); el.type = 'hidden'; el.name = name; form.append(el); }
+ el.value = val;
+ return el;
+ }
+ function addField(group, name, label, choices) {
+ const wrap = document.createElement('div');
+ wrap.className = 'jenhome-field' + (choices ? ' jenhome-referral' : '');
+ const el = document.createElement(choices ? 'select' : 'input');
+ el.id = 'jenhome-js-' + (++nextId);
+ el.name = name; el.className = 'form-control'; el.required = name !== 'middle_name';
+ if (choices) {
+ el.add(new Option('Please select', ''));
+ choices.forEach(choice => el.add(new Option(choice, choice)));
+ } else {
+ el.type = 'text';
+ el.autocomplete = name === 'first_name' ? 'given-name' : (name === 'middle_name' ? 'additional-name' : 'family-name');
+ }
+ const lab = document.createElement('label'); lab.htmlFor = el.id; lab.textContent = label;
+ wrap.append(lab, el); group.append(wrap);
+ }
+ function sync(form) {
+ hidden(form, 'name', ['first_name', 'middle_name', 'last_name'].map(name => value(form, name).trim()).filter(Boolean).join(' '));
+ }
+ function enhance(form) {
+ // Elementor copies data attributes when cloning popups, but not event listeners.
+ if (!relevant(form) || enhanced.has(form)) return;
+ enhanced.add(form);
+ form.dataset.jenhomeReady = '1';
+ if (config.referralForms.includes(value(form, 'form_id')) && field(form, 'enquiry_type')) {
+ field(form, 'enquiry_type').name = 'referral_source';
+ }
+ if (['6o0tsaob0', '1cbfa42a'].includes(value(form, 'form_id')) && field(form, 'e_meta[streat_address]')) field(form, 'e_meta[streat_address]').name = 'referrer_name';
+ const group = document.createElement('div'); group.className = 'jenhome-fields';
+ if (!field(form, 'first_name')) addField(group, 'first_name', 'First Name');
+ if (!field(form, 'middle_name')) addField(group, 'middle_name', 'Middle Name (optional)');
+ if (!field(form, 'last_name')) addField(group, 'last_name', 'Last Name');
+ if (!field(form, 'referral_source')) addField(group, 'referral_source', 'How did you hear about us?', config.referrals);
+ const full = field(form, 'name');
+ if (group.children.length) {
+ if (full) full.insertAdjacentElement('beforebegin', group);
+ else (form.querySelector('button[type="submit"],button') || form.lastElementChild)?.insertAdjacentElement('beforebegin', group);
+ }
+ if (full) {
+ const namesGroup = field(form, 'first_name')?.closest('.jenhome-fields');
+ if (namesGroup && namesGroup.contains(field(form, 'last_name')) && !namesGroup.contains(full)) full.insertAdjacentElement('beforebegin', namesGroup);
+ // Never guess a split from an existing full name (including signed-in profile names).
+ if (full.id) form.querySelectorAll('label').forEach(label => { if (label.htmlFor === full.id) label.hidden = true; });
+ full.type = 'hidden'; full.required = false;
+ const siblingLabel = full.parentElement.querySelector(':scope > label');
+ if (siblingLabel && !siblingLabel.closest('.jenhome-fields')) siblingLabel.hidden = true;
+ }
+ // Place the optional field between the existing first/last controls, including popups.
+ const middle = field(form, 'middle_name');
+ const lastGroup = field(form, 'last_name').closest('.elementor-field-group');
+ if (lastGroup) {
+ const middleGroup = middle.closest('.jenhome-field,.elementor-field-group');
+ const oldGroup = middleGroup?.parentElement;
+ if (middleGroup) {
+ middleGroup.className = lastGroup.className.replace(/elementor-field-group-[\w-]+/g, '').replace(/elementor-field-required/g, '');
+ middle.className = field(form, 'last_name').className;
+ middle.placeholder = 'Middle Name (optional)';
+ middle.setAttribute('aria-label', 'Middle Name (optional)');
+ const middleLabel = middleGroup.querySelector('label');
+ const lastLabel = lastGroup.querySelector('label');
+ if (middleLabel && lastLabel) middleLabel.className = lastLabel.className;
+ else if (middleLabel) { middleLabel.hidden = true; middleLabel.style.display = 'none'; }
+ lastGroup.before(middleGroup);
+ [field(form, 'first_name').closest('.elementor-field-group'), middleGroup, lastGroup].filter(Boolean).forEach(wrap => {
+ wrap.className = wrap.className.replace(/elementor-col-\d+/g, 'elementor-col-33');
+ });
+ if (oldGroup?.classList.contains('jenhome-fields') && !oldGroup.children.length) oldGroup.remove();
+ }
+ } else {
+ const middleGroup = middle.closest('.jenhome-field');
+ const lastGroup = field(form, 'last_name').closest('.jenhome-field');
+ if (middleGroup && lastGroup) lastGroup.before(middleGroup);
+ }
+ middle.required = false;
+ middle.autocomplete = 'additional-name';
+ ['first_name', 'last_name', 'referral_source'].forEach(name => { field(form, name).required = true; });
+ hidden(form, 'jenhome_contact_nonce', config.nonce);
+ hidden(form, 'source_link', value(form, 'property_permalink') || location.origin + location.pathname);
+ form.addEventListener('input', () => sync(form));
+ form.addEventListener('change', () => sync(form));
+ form.addEventListener('reset', () => setTimeout(() => sync(form), 0));
+ sync(form);
+ }
+ function scan(root) {
+ if (root instanceof HTMLFormElement) enhance(root);
+ root.querySelectorAll?.('form').forEach(enhance);
+ }
+ scan(document);
+ new MutationObserver(records => records.forEach(record => record.addedNodes.forEach(node => {
+ if (node.nodeType === 1) scan(node);
+ }))).observe(document.documentElement, { childList: true, subtree: true });
+ // Houzez submits some forms from button click handlers, bypassing native validation.
+ document.addEventListener('click', event => {
+ const button = event.target.closest('button,input[type="submit"]');
+ if (!button || (button.type !== 'submit' && !button.matches('.houzez_agent_property_form,.schedule_contact_form,.contact-realtor-btn'))) return;
+ const form = button?.form;
+ if (!form || !relevant(form)) return;
+ enhance(form); sync(form);
+ for (const name of ['first_name', 'last_name', 'referral_source']) {
+ const input = field(form, name);
+ if (!input.value.trim()) {
+ event.preventDefault(); event.stopImmediatePropagation(); input.reportValidity(); return;
+ }
+ }
+ }, true);
+ document.addEventListener('submit', event => {
+ if (relevant(event.target)) { enhance(event.target); sync(event.target); }
+ }, true);
+ // Preserve the vendor export buttons and download behavior while adding CSRF protection.
+ $.ajaxPrefilter(function (options) {
+ const url = new URL(options.url, location.href);
+ if (url.origin !== location.origin || !url.pathname.endsWith('/admin-ajax.php')) return;
+ const params = new URLSearchParams(typeof options.data === 'string' ? options.data : options.data || {});
+ if (['houzez_crm_export_leads', 'crm_export_inquiries'].includes(params.get('action'))) {
+ params.set('jenhome_export_nonce', config.exportNonce);
+ options.data = params.toString();
+ }
+ });
+})(jQuery);
diff --git a/gitea-updater.php b/gitea-updater.php
new file mode 100644
index 0000000..0c7874d
--- /dev/null
+++ b/gitea-updater.php
@@ -0,0 +1,145 @@
+ 20, 'redirection' => 0, 'sslverify' => true,
+ 'limit_response_size' => 1048576,
+ 'headers' => ['Accept' => 'application/json, application/octet-stream'],
+ ]);
+ if (is_wp_error($response)) return $response;
+ $status = wp_remote_retrieve_response_code($response);
+ if ($status === 200) return $response;
+ if (!in_array($status, [301, 302, 303, 307, 308], true)) return new WP_Error('jenhome_update_http', 'The Gitea update service returned HTTP ' . (int)$status . '.');
+ $next = wp_remote_retrieve_header($response, 'location');
+ if (!is_string($next) || $next === '') break;
+ $url = str_starts_with($next, '/') && !str_starts_with($next, '//') ? 'https://git.labs.casa' . $next : $next;
+ }
+ return new WP_Error('jenhome_update_redirect', 'The plugin update redirect could not be verified.');
+ }
+
+ public static function parse_release($release) {
+ if (!is_array($release) || !empty($release['draft']) || !empty($release['prerelease'])
+ || !is_string($release['tag_name'] ?? null)
+ || !preg_match('/^v(\d+\.\d+\.\d+)$/D', $release['tag_name'] ?? '', $matches)) return false;
+ $version = $matches[1];
+ $filename = self::SLUG . '-' . $version . '.zip';
+ $names = array_column(is_array($release['assets'] ?? null) ? $release['assets'] : [], 'name');
+ if (!in_array($filename, $names, true) || !in_array($filename . '.sha256', $names, true)) return false;
+ $package = self::REPO . '/releases/download/v' . $version . '/' . $filename;
+ return ['version' => $version, 'package' => $package, 'checksum_url' => $package . '.sha256',
+ 'url' => self::REPO . '/releases/tag/v' . $version,
+ 'body' => is_string($release['body'] ?? null) ? $release['body'] : '',
+ 'published_at' => is_string($release['published_at'] ?? null) ? $release['published_at'] : ''];
+ }
+
+ public static function latest() {
+ $cached = get_transient(self::CACHE);
+ if ($cached !== false) return $cached ?: false;
+ $response = self::request(self::API);
+ $release = !is_wp_error($response) ? self::parse_release(json_decode(wp_remote_retrieve_body($response), true)) : false;
+ if ($release) {
+ $checksum = self::request($release['checksum_url'], ['limit_response_size' => 1024]);
+ $text = is_wp_error($checksum) ? '' : trim(wp_remote_retrieve_body($checksum));
+ $filename = self::SLUG . '-' . $release['version'] . '.zip';
+ if (!preg_match('/^([a-f0-9]{64})\s+\*?' . preg_quote($filename, '/') . '$/Di', $text, $match)) $release = false;
+ else $release['sha256'] = strtolower($match[1]);
+ }
+ set_transient(self::CACHE, $release ?: [], $release ? 3600 : 300);
+ return $release;
+ }
+
+ public static function update($update, $data, $file, $locales) {
+ if ($file !== self::$plugin || ($data['UpdateURI'] ?? '') !== self::REPO) return $update;
+ $release = self::latest();
+ if (!$release) return false;
+ return ['id' => self::REPO, 'slug' => self::SLUG, 'version' => $release['version'],
+ 'url' => $release['url'], 'package' => $release['package'], 'requires' => '6.2',
+ 'requires_php' => '8.1', 'tested' => '7.1.3'];
+ }
+
+ public static function information($result, $action, $args) {
+ if ($action !== 'plugin_information' || ($args->slug ?? '') !== self::SLUG) return $result;
+ $release = self::latest();
+ if (!$release) return $result;
+ return (object)[
+ 'name' => 'Jen Home Contact Fields and Exports', 'slug' => self::SLUG,
+ 'version' => $release['version'], 'author' => 'Josh Stevens Sr', 'author_profile' => 'https://hostlabs.pro/',
+ 'homepage' => 'https://hostlabs.pro/', 'requires' => '6.2', 'requires_php' => '8.1', 'tested' => '7.1.3',
+ 'download_link' => $release['package'], 'last_updated' => $release['published_at'],
+ 'sections' => ['description' => 'Site-specific Houzez contact fields and CSV exports for staging.jenhome.net.',
+ 'changelog' => wpautop(esc_html($release['body']))],
+ ];
+ }
+
+ public static function validate_package($path, $release) {
+ if (!hash_equals($release['sha256'], hash_file('sha256', $path))) return new WP_Error('jenhome_update_checksum', 'The plugin update checksum does not match its release.');
+ if (!class_exists('ZipArchive')) return new WP_Error('jenhome_update_zip', 'PHP ZIP support is required to verify this update.');
+ $zip = new ZipArchive();
+ if ($zip->open($path) !== true) return new WP_Error('jenhome_update_zip', 'The plugin update is not a valid ZIP file.');
+ try {
+ $required = ['jenhome-contact-exports.php', 'forms.js', 'crm-display.php', 'gitea-updater.php'];
+ $seen = []; $total = 0;
+ for ($i = 0; $i < $zip->numFiles; ++$i) {
+ $entry = $zip->statIndex($i); $name = $entry['name']; $total += $entry['size'];
+ if (!in_array($name, array_map(function($f) { return self::SLUG . '/' . $f; }, $required), true) || isset($seen[$name]) || $total > 10485760) {
+ return new WP_Error('jenhome_update_contents', 'The plugin ZIP contains unexpected files.');
+ }
+ $opsys = $attributes = 0;
+ if ($zip->getExternalAttributesIndex($i, $opsys, $attributes) && (($attributes >> 16) & 0170000) === 0120000) return new WP_Error('jenhome_update_contents', 'The plugin ZIP contains a symbolic link.');
+ $seen[$name] = true;
+ }
+ if (count($seen) !== count($required)) return new WP_Error('jenhome_update_contents', 'The plugin ZIP is incomplete.');
+ $main = $zip->getFromName(self::SLUG . '/jenhome-contact-exports.php');
+ if (!preg_match('/^\s*\*\s*Version:\s*([^\s]+)\s*$/m', $main, $m) || $m[1] !== $release['version']) return new WP_Error('jenhome_update_version', 'The plugin ZIP version does not match the release.');
+ return true;
+ } finally { $zip->close(); }
+ }
+
+ public static function download($reply, $package, $upgrader, $extra) {
+ if ($reply !== false || ($extra['plugin'] ?? '') !== self::$plugin) return $reply;
+ $release = self::latest();
+ if (!$release || $package !== $release['package']) return new WP_Error('jenhome_update_release', 'The plugin package is not the verified published Gitea release.');
+ $path = wp_tempnam(self::SLUG . '.zip');
+ if (!$path) return new WP_Error('jenhome_update_temp', 'A temporary update file could not be created.');
+ $response = self::request($package, ['timeout' => 60, 'stream' => true, 'filename' => $path, 'limit_response_size' => 5242880]);
+ $check = is_wp_error($response) ? $response : self::validate_package($path, $release);
+ if (is_wp_error($check)) { wp_delete_file($path); return $check; }
+ return $path;
+ }
+}
diff --git a/jenhome-contact-exports.php b/jenhome-contact-exports.php
new file mode 100644
index 0000000..02a5f40
--- /dev/null
+++ b/jenhome-contact-exports.php
@@ -0,0 +1,376 @@
+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) ? '