Skip to content

5. Contact Form & Lead Alerting Pipeline

Repository: Webpage (planovi-webpage) • Rule Prefix: BR-CNT • Documented Rules: 7 • Open [TEAM_WHY_NEEDED] Questions: 2

1. Business Purpose & Actors

  • Problem solved: Captures inbound commercial inquiries/quote requests from the homepage #contact section, blocks automated spam via Cloudflare Turnstile, stores leads in website.website_form_messages, and alerts the sales/ops team immediately in Google Chat.
  • Actors: Prospective customers submitting #contact-form on index.php; Cloudflare Turnstile; Supabase PostgREST; PLANOVI team monitoring Google Chat.

2. All Features & End-to-End Flows

  • Flow A — Contact Submission (index.php:573-587 → js/script.js:231-313 → POST /contact-handler.php):
    • Trigger: User fills name, email, message, completes implicit .cf-turnstile widget, clicks submit.
    • Client Processing (js/script.js:237-311): Prevents default submit; reads cf-turnstile-response from FormData (fallback window.turnstile.getResponse()); disables button (opacity: 0.7); sends JSON POST to contact-handler.php (retries POST to response.url if redirected); displays green success or red error banner in #contact-response-msg; resets form on success; always re-enables button and calls window.turnstile.reset('#contact-form .cf-turnstile') in finally.
    • Server Processing (contact-handler.php:1-182):
      1. Rejects non-POST with HTTP 405 + Allow: POST.
      2. Parses JSON body if valid non-empty array, else falls back to $_POST.
      3. Validates $name (1..150 UTF-8 chars), $email (1..254 bytes + FILTER_VALIDATE_EMAIL), $message (1..4000 UTF-8 chars) → HTTP 400 (contact.err_fields).
      4. Verifies Turnstile (turnstile.secret_key, 10s timeout, fail-closed) → HTTP 400 (contact.err_captcha).
      5. Collects client metadata: ip_address (HTTP_CF_CONNECTING_IP → REMOTE_ADDR → '0.0.0.0'), country (HTTP_CF_IPCOUNTRY → 'N/A'), user_agent (substr(..., 0, 500) → 'Unknown').
      6. Inserts row into {supabase.url}/rest/v1/{supabase.table} (default website_form_messages, schema website, Prefer: return=minimal, 10s timeout) with status='new' and turnstile_passed=true.
      7. Dispatches Polish-formatted message card to google_chat.webhook_url (10s timeout) unless empty or contains 'YOUR_GOOGLE_CHAT'.
      8. Responds HTTP 200 with {"success": true, "message": "...", "supabase": bool, "google_chat": bool}.

3. Hard Business Rules, Validations, Calculations & Edge Cases

  • BR-CNT-01 (Field Length & Format Constraints): name required & <= 150 UTF-8 chars; email required, <= 254 bytes, valid FILTER_VALIDATE_EMAIL; message required & <= 4000 UTF-8 chars; user_agent truncated to 500 bytes (contact-handler.php:46-58,101).
  • BR-CNT-02 (Fail-Closed Turnstile Without Action/Hostname Binding): Contact Turnstile verification fails closed ($turnstilePassed = false) when secret or token is missing or siteverify fails, returning HTTP 400. Unlike waitlist (BR-WLT-05), it does not check action, hostname, or token length <= 2048 (contact-handler.php:61-96).
  • BR-CNT-03 (Dual Input Format Support): contact-handler.php:21-36 accepts both application/json and application/x-www-form-urlencoded / multipart/form-data ($_POST).
  • BR-CNT-04 (Silent Downstream Failure — False Success Risk): Even if both Supabase insert ($supabaseSaved === false) AND Google Chat webhook ($googleChatSent === false) fail or are unconfigured, contact-handler.php:177-182 still returns HTTP 200 with "success": true! Leads can be silently dropped without notifying the user or logging an error.
  • BR-CNT-05 (Language Resolution Bug in Responses): contact-handler.php:11 loads i18n.php (setting $translations from session/cookie) before reading $lang from the POST body (lines 29-43). Consequently, __() responses ignore the submitted lang field and use the session language. Similarly, js/script.js:294,301 hardcodes Polish fallback error strings ('Wystąpił błąd.', 'Wystąpił błąd podczas połączenia z serwerem.') even in EN mode.
  • BR-CNT-06 (Google Chat Unescaped Markdown Interpolation): Raw $name, $email, and $message are interpolated directly into Google Chat markdown (*...*) without escaping markdown control characters (contact-handler.php:152-159).

4. State Machines & Data Lifecycle

website.website_form_messages.status is initialized to 'new' on insert (contact-handler.php:121, supabase/website_schema.sql:46). No further status transitions or update endpoints exist in this repository.

5. Technical Contract (Inputs → Processing → Side Effects)

  • Endpoint: POST /contact-handler.php (JSON or form-data: name, email, message, cf-turnstile-response, lang).
  • DB Table (supabase/website_schema.sql:34-96): website.website_form_messages (id UUID PK, created_at, created_by, updated_at with trigger trg_website_form_messages_updated_at, name, email, message, user_agent, ip_address, country, language VARCHAR(10) DEFAULT 'pl', status TEXT DEFAULT 'new', turnstile_passed BOOLEAN DEFAULT TRUE). RLS enabled: INSERT allowed for anon, authenticated, service_role; ALL allowed for service_role.
  • External APIs: Cloudflare Turnstile siteverify (10s); Supabase PostgREST POST /rest/v1/website_form_messages (10s, Content-Profile: website); Google Chat webhook POST (10s).

6. Cross-Repository Dependencies

Caller → CalleeProtocol & AuthExact Endpoint / Contract
planovi-webpage → Supabase (planovi-backend DB)HTTPS PostgREST (apikey + Authorization: Bearer)POST /rest/v1/website_form_messages (schema website)
planovi-webpage → Cloudflare TurnstileHTTPS form-urlencoded (secret)https://challenges.cloudflare.com/turnstile/v0/siteverify
planovi-webpage → Google Chat SpaceHTTPS JSON (webhook URL secret token)site_config('google_chat.webhook_url')

7. Why It Works This Way (Decisions, Trade-offs & Workarounds)

  • RLS allows anon INSERT on website_form_messages: Enables contact-handler.php to insert using the supabase.key (anon key) without exposing SELECT/UPDATE/DELETE to anon (supabase/website_schema.sql:81-95). Note: GRANT ALL ON TABLE website.website_form_messages TO anon (line 96) is present in SQL, though RLS restricts anon to INSERT only.
  • Note in config.example.php:47-49: Comments explicitly indicate contact form settings (turnstile.*, supabase.*, google_chat.webhook_url) are currently in config.php and intended to be moved into out-of-webroot ../config/{dev,prod}.php once rotated.
  • [TEAM_WHY_NEEDED: Should contact-handler.php return HTTP 500/502 (and log errors) when both Supabase persistence and Google Chat alerting fail, instead of returning HTTP 200 success: true?]
  • [TEAM_WHY_NEEDED: Should contact-handler.php validate Turnstile hostname/action like waitlist-handler.php to prevent cross-widget/cross-site token replay?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to VerifyFix
Form shows success, but row missing from Supabase and no Google Chat alertcontact-handler.php:177-182 returns success: true with supabase: false, google_chat: false when keys/URLs fail or contain placeholder stringsInspect Network tab response JSON for supabase and google_chat booleansVerify supabase.url, supabase.key, website schema exposure in Supabase PostgREST settings, and google_chat.webhook_url
HTTP 400 contact.err_captcha on submitMissing/expired Turnstile token or mismatched turnstile.site_key / turnstile.secret_key (contact-handler.php:64-96)Inspect cf-turnstile-response in POST payloadVerify Turnstile key pair for current hostname
405 Method Not Allowed after redirectHostinger/proxy redirected contact-handler.php to clean URL; retry logic in js/script.js:271-279 handles response.redirected only if redirect completesCheck Network tab for 301/302 on /contact-handler.phpExclude *-handler.php from clean-URL redirects on web server