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) ? '
' : ''; + 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 .= '
'; + } + if ($referral) { + $id = wp_unique_id('jenhome-referral-'); + $html .= '
'; + } + return $html . (($first || $last || $referral || $middle) ? '
' : '') . ''; + } + + 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, ']*>.*?~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, ''); + $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'] .= '

Referral Source: ' . esc_html($_POST['referral_source']) . '

'; + 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', 'source_link', '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] ?? [])); + $row['source_link'] = html_entity_decode($row['source_link'] ?? '', ENT_QUOTES, 'UTF-8'); + 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', 'Source Link', '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), + html_entity_decode($row['source_link'] ?? '', ENT_QUOTES, 'UTF-8'), + $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', 'Source Link', 'Email', 'Mobile'], self::inquiry_rows(get_current_user_id())); + } +} +add_action('plugins_loaded', ['Jenhome_Contact_Exports', 'boot']); diff --git a/scripts/build-release.py b/scripts/build-release.py new file mode 100644 index 0000000..4c240b9 --- /dev/null +++ b/scripts/build-release.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python3 +"""Build only the four plugin runtime files; exclude tests, config and Git data.""" +from pathlib import Path +import hashlib, re, sys, zipfile +root = Path(__file__).resolve().parents[1] +main = (root / 'jenhome-contact-exports.php').read_text() +version = re.search(r'^ \* Version: (\d+\.\d+\.\d+)$', main, re.M).group(1) +assert f"const VERSION = '{version}';" in main, 'Header/runtime version mismatch' +if len(sys.argv) > 1: + assert sys.argv[1] == 'v' + version, 'Tag must match plugin version' +out = root / 'dist' +out.mkdir(exist_ok=True) +package = out / f'jenhome-contact-exports-{version}.zip' +with zipfile.ZipFile(package, 'w', zipfile.ZIP_DEFLATED) as archive: + for filename in ['jenhome-contact-exports.php', 'forms.js', 'crm-display.php', 'gitea-updater.php']: + entry = zipfile.ZipInfo('jenhome-contact-exports/' + filename, (2026, 1, 1, 0, 0, 0)) + entry.compress_type = zipfile.ZIP_DEFLATED + entry.external_attr = 0o100644 << 16 + archive.writestr(entry, (root / filename).read_bytes()) +checksum = hashlib.sha256(package.read_bytes()).hexdigest() +package.with_suffix('.zip.sha256').write_text(f'{checksum} {package.name}\n') +print(f'Built {package.name} SHA256 {checksum}') diff --git a/scripts/publish-release.py b/scripts/publish-release.py new file mode 100644 index 0000000..10253e3 --- /dev/null +++ b/scripts/publish-release.py @@ -0,0 +1,54 @@ +#!/usr/bin/env python3 +"""Publish a tested tag using Gitea Actions' ephemeral repository token.""" +from pathlib import Path +import json, os, re, sys, urllib.error, urllib.request, uuid +root = Path(__file__).resolve().parents[1] +base = 'https://git.labs.casa/api/v1/repos/josh/jenhomeforms' +tag = os.environ.get('RELEASE_TAG', '') +if not re.fullmatch(r'v\d+\.\d+\.\d+', tag): + sys.exit('Release requires a stable vMAJOR.MINOR.PATCH tag.') +token = os.environ.get('GITEA_TOKEN', '') +if not token: + sys.exit('Gitea Actions repository token is unavailable.') +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args): + return None +opener = urllib.request.build_opener(NoRedirect()) +def request(method, path, data=None, content_type='application/json'): + body = json.dumps(data).encode() if isinstance(data, dict) else data + req = urllib.request.Request(base + path, data=body, method=method, headers={ + 'Authorization': 'token ' + token, 'Content-Type': content_type, 'Accept': 'application/json'}) + try: + with opener.open(req, timeout=60) as response: + raw = response.read() + return response.status, json.loads(raw) if raw else {} + except urllib.error.HTTPError as error: + if error.code == 404: + return 404, {} + sys.exit(f'Gitea release API failed: HTTP {error.code} ({method} {path}).') +status, release = request('GET', '/releases/tags/' + tag) +if status == 200 and not release.get('draft'): + sys.exit('This version is already published; published releases are not overwritten.') +if status == 404: + status, release = request('POST', '/releases', { + 'tag_name': tag, 'target_commitish': os.environ['SOURCE_COMMIT'], 'name': tag, + 'body': (root / 'CHANGELOG.md').read_text(), 'draft': True, 'prerelease': False}) + if status != 201: + sys.exit('Gitea did not create the draft release.') +release_id = int(release['id']) +_, assets = request('GET', f'/releases/{release_id}/assets') +existing = {asset['name'] for asset in assets} +for suffix in ['.zip', '.zip.sha256']: + path = root / 'dist' / ('jenhome-contact-exports-' + tag[1:] + suffix) + if path.name in existing: + sys.exit('A draft asset already exists. Review the draft before retrying publication.') + boundary = 'jenhome-' + uuid.uuid4().hex + body = (f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{path.name}"\r\n' + 'Content-Type: application/octet-stream\r\n\r\n').encode() + path.read_bytes() + f'\r\n--{boundary}--\r\n'.encode() + status, _ = request('POST', f'/releases/{release_id}/assets?name={path.name}', body, 'multipart/form-data; boundary=' + boundary) + if status != 201: + sys.exit('Release asset upload failed; the release remains a draft.') +status, _ = request('PATCH', f'/releases/{release_id}', {'draft': False}) +if status != 200: + sys.exit('Release publication failed; review the draft in Gitea.') +print('Published ' + tag + ' with the plugin ZIP and SHA256 checksum.') diff --git a/tests/unit.php b/tests/unit.php new file mode 100644 index 0000000..5d3f8f1 --- /dev/null +++ b/tests/unit.php @@ -0,0 +1,115 @@ +' . $s . '

'; } +function wp_timezone() { return new DateTimeZone('America/New_York'); } +function is_serialized($s) { return is_string($s) && str_starts_with($s, 'a:'); } +function absint($v) { return abs((int)$v); } +function is_user_logged_in() { return true; } +function current_user_can($cap) { return true; } +function check_ajax_referer(...$args) {} +function get_current_user_id() { return 321; } +function nocache_headers() {} +function wp_die(...$args) { throw new Test_Die(); } +require dirname(__DIR__) . '/gitea-updater.php'; +require dirname(__DIR__) . '/jenhome-contact-exports.php'; +Jenhome_Gitea_Updater::boot(dirname(__DIR__) . '/jenhome-contact-exports.php'); +$checks = 0; +function check($ok, $name) { global $checks; if (!$ok) throw new RuntimeException('FAIL: ' . $name); ++$checks; } +$version = Jenhome_Contact_Exports::VERSION; +$name = 'jenhome-contact-exports-' . $version . '.zip'; +$release = ['tag_name' => 'v' . $version, 'draft' => false, 'prerelease' => false, 'body' => '', 'assets' => [['name' => $name], ['name' => $name . '.sha256']]]; +$info = Jenhome_Gitea_Updater::parse_release($release); +check($info['version'] === $version, 'stable version parsed'); +foreach ([['draft' => true], ['prerelease' => true], ['tag_name' => 'v1.2.0-rc1'], ['tag_name' => '../escape'], ['tag_name' => []], ['assets' => []]] as $change) check(Jenhome_Gitea_Updater::parse_release(array_replace($release, $change)) === false, 'ineligible release rejected'); +check(Jenhome_Gitea_Updater::allowed_url($info['package']), 'expected package allowed'); +foreach (['http://git.labs.casa/josh/jenhomeforms', 'https://evil.example/asset.zip', 'https://git.labs.casa.evil.example/asset.zip', 'https://user:password@git.labs.casa/attachments/123', $info['package'].'?token=abc', 'https://git.labs.casa/other/repository/file.zip', 'file:///etc/passwd'] as $url) check(!Jenhome_Gitea_Updater::allowed_url($url), 'untrusted URL rejected'); +$files = []; +foreach (['jenhome-contact-exports.php','forms.js','crm-display.php','gitea-updater.php'] as $file) $files['jenhome-contact-exports/'.$file] = file_get_contents(dirname(__DIR__).'/'.$file); +$paths = []; +function test_zip($files) { + $p=tempnam(sys_get_temp_dir(),'jh-zip-'); $GLOBALS['paths'][]=$p; + $zip=new ZipArchive(); $zip->open($p,ZipArchive::OVERWRITE); + foreach($files as $name=>$content) $zip->addFromString($name,$content); + $zip->close(); return $p; +} +try { + $zip = test_zip($files); + $info['sha256'] = hash_file('sha256',$zip); + check(Jenhome_Gitea_Updater::validate_package($zip,$info)===true,'complete versioned ZIP accepted'); + check(is_wp_error(Jenhome_Gitea_Updater::validate_package($zip,array_replace($info,['sha256'=>str_repeat('0',64)]))),'checksum mismatch rejected'); + check(is_wp_error(Jenhome_Gitea_Updater::validate_package($zip,array_replace($info,['version'=>'99.0.0']))),'ZIP version mismatch rejected'); + foreach ([$files+['jenhome-contact-exports/../../outside.php'=>'bad'], array_slice($files,1,null,true), $files+['jenhome-contact-exports/tests.php'=>'unexpected']] as $bad) { + $p=test_zip($bad); check(is_wp_error(Jenhome_Gitea_Updater::validate_package($p,array_replace($info,['sha256'=>hash_file('sha256',$p)]))),'invalid package contents rejected'); + } + $p=test_zip($files); $z=new ZipArchive(); $z->open($p); $z->setExternalAttributesName('jenhome-contact-exports/forms.js', ZipArchive::OPSYS_UNIX, 0120777 << 16); $z->close(); + check(is_wp_error(Jenhome_Gitea_Updater::validate_package($p,array_replace($info,['sha256'=>hash_file('sha256',$p)]))),'symlink rejected'); + $GLOBALS['responses'] = [ + Jenhome_Gitea_Updater::API => ['status'=>200,'body'=>json_encode($release)], + $info['checksum_url'] => ['status'=>200,'body'=>$info['sha256'].' '.$name."\n"], + $info['package'] => ['status'=>200,'body'=>file_get_contents($zip)], + ]; + $GLOBALS['requests']=[]; + check(Jenhome_Gitea_Updater::latest()['sha256']===$info['sha256'],'release and checksum fetched'); + Jenhome_Gitea_Updater::latest(); check(count($GLOBALS['requests'])===2,'metadata cache prevents repeated requests'); + $update=Jenhome_Gitea_Updater::update(false,['UpdateURI'=>Jenhome_Gitea_Updater::REPO],'jenhome-contact-exports/jenhome-contact-exports.php',[]); + check($update['version']===$version && $update['package']===$info['package'],'native WordPress update response'); + check(Jenhome_Gitea_Updater::update('untouched',[],'other/plugin.php',[])==='untouched','other plugins unchanged'); + $details=Jenhome_Gitea_Updater::information(false,'plugin_information',(object)['slug'=>'jenhome-contact-exports']); + check(!str_contains($details->sections['changelog'],'