' . __('Forms', 'fillinforge') . ''); return $links; }); } /** * Loads one admin screen script, assets/js/admin-.js, after the * main admin script (which carries `formforgeAdmin`). The values the * screen used to print into an inline block go to the script as * `window.`: the data is JSON with <, >, & and quotes escaped, * so nothing in it (a translation, a field label) can end the script. * * @param string $slug File name part and handle suffix. * @param string $global Name of the window property that gets $data ('' for none). * @param array $data Values for the script. * @param array $deps Script handles to load before it, besides jQuery and the main admin script. * @param bool $append True: $data is one entry of a list the script walks (a widget drawn more than once). */ private function enqueue_screen_script($slug, $global = '', array $data = [], array $deps = [], $append = false) { $rel = 'assets/js/admin-' . $slug . '.js'; $handle = 'formforge-admin-' . $slug; wp_enqueue_script($handle, FORMFORGE_URL . $rel, array_merge(['jquery', 'formforge-admin'], $deps), FORMFORGE_VERSION . '.' . filemtime(FORMFORGE_DIR . $rel), true); if ($global !== '') { $json = wp_json_encode($data, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); // $append: the script serves several instances of one widget; each call adds its own entry to a list. $code = $append ? 'window.' . $global . ' = (window.' . $global . ' || []).concat([' . $json . ']);' : 'window.' . $global . ' = ' . $json . ';'; wp_add_inline_script($handle, $code, 'before'); } } public static function templates_count_text($templates, $categories) { $templates = (int) $templates; $categories = (int) $categories; $in = sprintf( /* translators: %d: number of template categories; the phrase completes "N templates …" */ _n('in %d category', 'in %d categories', $categories, 'fillinforge'), $categories ); return sprintf( /* translators: 1: number of templates, 2: the phrase "in N categories" */ _n('%1$d template %2$s', '%1$d templates %2$s', $templates, 'fillinforge'), $templates, $in ); } /** * The field count on each card of the template picker, worded here in the form of its number: the picker script * (assets/js/admin-editor-templates.js) has no gettext of its own and only puts the text on the card. * * @param array $templates FORMFORGE_Templates::get_all. * @return array template key => "N fields", escaped for markup */ public static function template_field_counts(array $templates) { $counts = []; foreach ($templates as $key => $tpl) { $n = (isset($tpl['fields']) && is_array($tpl['fields'])) ? count($tpl['fields']) : 0; /* translators: %d: number of fields in the template */ $counts[(string) $key] = esc_html(sprintf(_n('%d field', '%d fields', $n, 'fillinforge'), $n)); } return $counts; } private function is_valid_mailchimp_api_key($api_key) { return preg_match('/^[A-Za-z0-9]{8,}-us\d+$/', (string) $api_key) === 1; } private function field_type_feature_gate($type) { if (class_exists('FORMFORGE_Field_Types')) { return FORMFORGE_Field_Types::pro_feature_for_type($type); } return ''; } /** What to tell an operator whose entitlement says yes but whose add-on is absent. */ private function addon_missing_message() { return __('Fillin Forge Pro is not installed on this site, so this integration has nothing to talk to. Install the add-on and try again.', 'fillinforge'); } /** Whether Fillin Forge Pro is loaded — the only thing the core knows about it. */ private function addon_active() { return class_exists('FORMFORGE_Pro_Bridge') && FORMFORGE_Pro_Bridge::addon_active(); } /** Whether the add-on reports one of its features running; the add-on decides. */ private function addon_feature_on($feature) { return class_exists('FORMFORGE_Pro_Bridge') && FORMFORGE_Pro_Bridge::instance()->is_enabled($feature); } /** * Where the settings of a Pro feature stand (Q121): 'live' (open), 'lapsed' (the licence was live and * has ended: read-only, only switching off is taken), 'closed' (no live licence: the same, without * the history). The add-on's code being installed is not a licence. */ private function pro_setting_state($feature) { if ($this->addon_feature_on($feature)) { return 'live'; } return (class_exists('FORMFORGE_Pro_Bridge') && FORMFORGE_Pro_Bridge::instance()->is_lapsed()) ? 'lapsed' : 'closed'; } /** * May a Pro setting be written with $posted when it holds $current? Always with a live licence. Without * one, only turning it off (a value to empty) is taken, and only where the add-on's cards are on the * page at all (the add-on is active). * * @param mixed $current What is stored. * @param mixed $posted What came in. */ private function pro_setting_may_change($feature, $current, $posted) { if ($this->addon_feature_on($feature)) { return true; } if (!$this->addon_active()) { return false; } $off = static function ($v) { return $v === '' || $v === null || $v === false || $v === 0 || $v === '0'; }; return $off($posted) && !$off($current); } /** Prints the attribute for the inputs of a Pro card: read-only text inputs without a live licence. */ private function lock_attr($feature) { if ($this->pro_setting_state($feature) !== 'live') { echo ' readonly="readonly"'; } } /** Prints the attribute for the selects and checkboxes of a Pro card, which readonly does not hold. */ private function lock_disabled($feature) { if ($this->pro_setting_state($feature) !== 'live') { echo ' disabled="disabled"'; } } /** * Is the site in the lapsed standing only because Pro could not reach the licence server? Its licence has not * ended, so no line of the cards may ask for a renewal. False for an ended licence and for an add-on that does * not say (older than the mark): their lines are as they were. */ private function without_contact() { return class_exists('FORMFORGE_Pro_Bridge') && FORMFORGE_Pro_Bridge::instance()->is_lapsed_without_contact(); } /** Prints the link that renews a licence that ended; nothing when the add-on gave no address (Q121 r2). */ private function print_renewal_link() { $url = class_exists('FORMFORGE_Pro_Bridge') ? FORMFORGE_Pro_Bridge::instance()->renewal_url() : ''; if ($url === '') { return; } echo '' . esc_html__('Renew your licence', 'fillinforge') . ''; } /** * The one line that says why a Pro block is read-only: after a licence ended (with the renewal link, as in * the banner), when Pro cannot reach the licence server (no renewal: the licence has not ended), or without * a live licence. $paused: the channel runs through Avakode servers and stops with the licence. */ private function print_lock_line($state, $paused) { $silent = $state === 'lapsed' && $this->without_contact(); if ($silent && $paused) { $text = __('Paused: Pro cannot reach the licence server. This channel runs through Avakode and resumes once this site reaches the server again; forms keep taking submissions.', 'fillinforge'); } elseif ($silent) { $text = __('Pro cannot reach the licence server, so changing this is closed. What is saved here keeps working; you can turn it off.', 'fillinforge'); } elseif ($state === 'lapsed' && $paused) { $text = __('Paused until you renew. Your licence has ended, so this runs through Avakode again once you renew; forms keep taking submissions.', 'fillinforge'); } elseif ($state === 'lapsed') { $text = __('Read-only until you renew. What is saved here keeps working; you can turn it off.', 'fillinforge'); } else { $text = __('Read-only: changing this needs an active Fillin Forge Pro licence.', 'fillinforge'); } echo '

' . esc_html($text) . ' '; if ($state === 'lapsed' && !$silent) { $this->print_renewal_link(); } echo '

'; } /** * The line at the top of a Pro card of Settings whose settings are closed (nothing when the licence is * live). The renewal banner above (drawn by the add-on, with the link) says what keeps working and what * is closed. * * @param string $feature The feature of the card. * @param bool $paused The channel runs through Avakode servers: it stops with the licence. * @param string $turn_off_name Name of an input that turns the setting off, '' for none. */ private function render_card_lock($feature, $paused = false, $turn_off_name = '') { $state = $this->pro_setting_state($feature); if ($state === 'live') { return; } $this->print_lock_line($state, $paused); if ($turn_off_name !== '' && $this->addon_active()) { echo ''; } } /** * The top of the Stripe card of Settings. Read-only without a live licence; after one has ended the owner * can turn payments off (a ticked box saved with the page), and nothing else of Stripe changes. Turned * off, the forms take submissions without payment until the licence is renewed (Q121). */ private function render_stripe_lock() { $state = $this->pro_setting_state('payment'); if ($state === 'live') { return; } if ($state === 'lapsed' && in_array('payment', FORMFORGE_Pro_Bridge::switched_off_features(), true)) { $silent = $this->without_contact(); $text = $silent ? __('Stripe payments are turned off, so your forms take submissions without payment. They take payments again as soon as this site reaches the licence server.', 'fillinforge') : __('Stripe payments are turned off, so your forms take submissions without payment. They take payments again as soon as you renew your licence.', 'fillinforge'); echo '

' . esc_html($text) . ' '; if (!$silent) { $this->print_renewal_link(); } echo '

'; return; } $this->render_card_lock('payment', false, $state === 'lapsed' ? 'stripe_turn_off' : ''); } /** * The top of a Pro block of the form editor whose settings are closed (nothing when the licence is * live): the reason with the renewal link, and, while the setting is on, the "Turn this off" box. The * block's inputs are drawn disabled (lock_disabled) and its script writes none of them; the box is the * one change the block takes: admin.js sets the keys of $off to their off values on Save (the server * takes only that from a closed feature). * * @param string $feature The Pro feature of the block. * @param bool $paused The channel runs through Avakode servers. * @param array $off Setting key => its off value (false, or '' for an address). * @param bool $is_on The setting is on now, so there is something to turn off. */ private function render_editor_lock($feature, $paused, array $off, $is_on) { $state = $this->pro_setting_state($feature); if ($state === 'live') { return; } $this->print_lock_line($state, $paused); if ($is_on && $this->addon_active()) { echo ''; } } /** * Under a Pro block that is open (live licence) whose channel the owner turned off for this form: a box to * turn it on again. The block's script drops the form's off flag on Save when it is ticked. */ private function render_turn_back_on($feature, $id, $is_off) { if (!$is_off || $this->pro_setting_state($feature) !== 'live') { return; } echo ''; } /** Whether Fillin Forge Pro is installed but too old for this core: switched off, not absent. */ private function addon_outdated() { return class_exists('FORMFORGE_Pro_Bridge') && FORMFORGE_Pro_Bridge::pro_addon_is_too_old(); } /** * What a screen says about Fillin Forge Pro when it is installed but too old * for this core: the same sentence and link as the admin notice, so the * person who owns the add-on is told to update it. Without the add-on (or * with a current one) it prints nothing: this plugin does not advertise, * sell or lock anything (wp.org Guidelines 5 and 6). */ private function render_pro_invite() { if (!$this->addon_outdated()) { return; } $installed = defined('FORMFORGE_PRO_VERSION') ? FORMFORGE_PRO_VERSION : ''; $required = defined('FORMFORGE_MIN_PRO') ? FORMFORGE_MIN_PRO : ''; ?>
=> {label, value, * type}` (normalised this). But the stored `label` can be empty * or missing — older rows, the legacy-abandoned flat shape (which * filter_submission_display_data back-fills with the bare id), or * field types that simply didn't persist one (repeater / calculation / * payment were the reported offenders). Sergei's retest saw the View * modal print raw keys like `f4`, `f5` because its JS did * `field.label || key` with nothing better to fall back to. * * Resolution order: * 1. the label stored on the submission row, if non-empty AND not * just a copy of the field id; * 2. the label from the LIVE form definition, matched by field id; * 3. the raw key — last resort only. * * @param string $key Field id / submission data key. * @param array $field The submission's stored field entry. * @param array $field_config_map id => live field config (from $form->fields). * @return string Human label. */ private function resolve_field_label($key, $field, $field_config_map = []) { $key = (string) $key; $stored = is_array($field) ? trim((string) ($field['label'] ?? '')) : ''; // A stored label that just echoes the id is not a real label — the // legacy-abandoned shim writes `'label' => $field_id`, and some // writers default to the key. Treat it as "missing" so the live // form definition gets a chance. if ($stored !== '' && $stored !== $key) { return $stored; } if (isset($field_config_map[$key]) && is_array($field_config_map[$key])) { $live = trim((string) ($field_config_map[$key]['label'] ?? '')); if ($live !== '') { return $live; } } return $stored !== '' ? $stored : $key; } /** * R4: build the id => live field config map used by * resolve_field_label. Centralised so the table and the View modal * data prep build it the same way. */ private function build_field_config_map($form_obj) { $map = []; if ($form_obj && !empty($form_obj->fields) && is_array($form_obj->fields)) { foreach ($form_obj->fields as $fc) { if (!empty($fc['id'])) { $map[(string) $fc['id']] = $fc; } } } return $map; } private function prepare_submission_view_data($data, $submission_id, $field_config_map = []) { if (!is_array($data)) return []; $data = $this->filter_submission_display_data($data); foreach ($data as $key => &$field) { // R4: resolve the real label here so the View modal shows // "Price" instead of the raw "f4" key. The modal JS still does // `field.label || key`, but now `field.label` is always the // properly resolved label — the table and PDF go through the // same resolve_field_label so the three can't disagree. if (is_array($field)) { $field['label'] = $this->resolve_field_label($key, $field, $field_config_map); $field_type = $field['type'] ?? ''; if (in_array($field_type, ['calendar_picker', 'date', 'time'], true)) { $field['value'] = FORMFORGE_Value_Formatter::field_text($field, ''); } elseif ($field_type === 'repeater' && is_array($field['value'] ?? null)) { // BUG-FORM-PROFLD-01: rows are a list of sub-field maps; implode in the list cell cannot join // them and the dialog printed "[object Object]". The text the CSV, the mail and the PDF use: // one row to a line, "Sub-field: value". $field['value'] = FORMFORGE_Value_Formatter::field_text($field, ''); } elseif ($field_type === 'map_address') { $field['value'] = FORMFORGE_Value_Formatter::text($field['value'] ?? '', ''); } elseif ($field_type === 'password') { // The list cell and the details dialog both read this: the mask, as in the CSV, the mail and the webhook. $field['value'] = FORMFORGE_Value_Formatter::plain_text($field, ''); } } if (($field['type'] ?? '') !== 'file_upload' || empty($field['file']) || !is_array($field['file'])) { continue; } $token = (string) ($field['file']['token'] ?? ''); if ($token === '') continue; $field['download_url'] = admin_url('admin-ajax.php?action=formforge_download_file' . '&submission_id=' . (int) $submission_id . '&field=' . rawurlencode((string) $key) . '&token=' . rawurlencode($token) . '&_wpnonce=' . wp_create_nonce('formforge_file_' . (int) $submission_id . '_' . (string) $key)); } unset($field); return $data; } /** * Build a Payment-details payload for the View modal / PDF / CSV. * * Pulls together the fields the QA team wants visible — payment_status, * payment_intent_id, amount, currency, updated_at — from whichever * source is available. The submit-time handler stores them in the * payment field row AND a $data['_payment'] bag; webhooks back-fill * $data['_payment'] with the authoritative Stripe values after capture. * * Returns an empty array if the submission has no payment information, * so callers can omit the section entirely (don't render empty rows). */ private function prepare_payment_details($raw_data, $submission_row) { if (!is_array($raw_data)) return []; $payment_bag = isset($raw_data['_payment']) && is_array($raw_data['_payment']) ? $raw_data['_payment'] : []; $field_row = null; foreach ($raw_data as $key => $field) { if (!is_array($field)) continue; if (($field['type'] ?? '') === 'payment') { $field_row = $field; break; } } // Column on the submission row — authoritative for status. $row_status = is_object($submission_row) ? (string) ($submission_row->payment_status ?? '') : ''; $status = (string) ($payment_bag['status'] ?? ''); if ($status === '' && $row_status !== '') $status = $row_status; $payment_id = (string) ($payment_bag['payment_id'] ?? ''); if ($payment_id === '' && $field_row && is_string($field_row['value'] ?? null)) { $payment_id = (string) $field_row['value']; } $amount = isset($payment_bag['amount']) ? (int) $payment_bag['amount'] : 0; if ($amount <= 0 && $field_row && isset($field_row['amount'])) { $amount = (int) $field_row['amount']; } $currency = strtolower((string) ($payment_bag['currency'] ?? '')); if ($currency === '' && $field_row && !empty($field_row['currency'])) { $currency = strtolower((string) $field_row['currency']); } $updated_at = (string) ($payment_bag['updated_at'] ?? ''); // No payment info at all — let the caller skip the section. if ($status === '' && $payment_id === '' && $amount <= 0) return []; // Stripe Dashboard URL — test-mode submissions get the "test/" // subpath so admins land on the right environment. The mode lives // on the global Stripe settings; safe to look it up here. $stripe_settings = get_option('formforge_stripe_settings', []); $stripe_mode = ($stripe_settings['mode'] ?? 'test') === 'live' ? 'live' : 'test'; $dashboard_url = ''; if ($payment_id !== '' && strpos($payment_id, 'pi_') === 0) { $dashboard_url = ($stripe_mode === 'live') ? 'https://dashboard.stripe.com/payments/' . rawurlencode($payment_id) : 'https://dashboard.stripe.com/test/payments/' . rawurlencode($payment_id); } $details = [ 'status' => $status, // The status in words, and the sentence that explains one that is not simply paid. 'status_label' => FORMFORGE_Value_Formatter::payment_status_label($status), 'note' => FORMFORGE_Value_Formatter::payment_status_note($status, ['amount' => $amount, 'currency' => $currency] + $payment_bag), 'payment_id' => $payment_id, 'amount' => $amount, 'currency' => $currency, 'updated_at' => $updated_at, 'dashboard_url' => $dashboard_url, 'amount_display' => $amount > 0 && $currency !== '' ? FORMFORGE_Value_Formatter::format_payment_amount($amount, $currency) : '', ]; /** * What else can be done with this payment. The payment add-on (it * holds the Stripe client; the core has none) may add * 'recheck' => [action, submission_id, nonce, label, busy]: a button * in the details that posts those to admin-ajax and shows the * 'message' of the answer. * * @param array $details the payment as the details show it * @param object $submission_row the submission's row */ $filtered = apply_filters('formforge/submission_payment_details', $details, $submission_row); return is_array($filtered) ? $filtered : $details; } /** * A booking whose time was not confirmed in the calendar. * * Fillin Forge Pro leaves a '_calendar' record on the submission when it * made no Google Calendar event for the chosen time: the slot was taken, the busy * check could not be made, or the event could not be created. The Submissions screen * shows it as "Time not confirmed" with a sentence on what to do. Returns an empty * array for every other submission, so callers draw nothing. * * @param mixed $raw_data the submission's saved data * @return array{status:string,reason:string,label:string,note:string}|array{} */ private function prepare_calendar_status($raw_data) { if (!is_array($raw_data) || !isset($raw_data['_calendar']) || !is_array($raw_data['_calendar'])) return []; if (($raw_data['_calendar']['status'] ?? '') !== 'unconfirmed') return []; $reason = in_array($raw_data['_calendar']['reason'] ?? '', ['busy', 'create_failed', 'unchecked'], true) ? $raw_data['_calendar']['reason'] : 'check_failed'; // 'unchecked' is written by the form handler itself (BUG-FORM-CAL-03): the booking was accepted while Google // Calendar did not answer, and the add-on has not made an event for it (yet). if ($reason === 'unchecked') { return [ 'status' => 'unconfirmed', 'reason' => $reason, 'label' => __('Time not confirmed with Google Calendar', 'fillinforge'), 'note' => __('Google Calendar did not answer when this booking came in, so the time was not checked against your calendar. Please check your calendar for a clash and confirm the time with the visitor.', 'fillinforge'), ]; } // The sentence says what is true for the reason: a failed creation is neither a taken slot nor an unreadable calendar. $note = $reason === 'create_failed' ? __('The calendar event for this time could not be created. Check your calendar: if the event is not there, add it yourself and confirm the time with the visitor.', 'fillinforge') : __('The calendar showed this time as taken or could not be checked, so no calendar event was created. Please confirm the time with the visitor.', 'fillinforge'); return [ 'status' => 'unconfirmed', 'reason' => $reason, 'label' => __('Time not confirmed', 'fillinforge'), 'note' => $note, ]; } private function payment_status_chip_style($status) { switch (strtolower((string) $status)) { case 'succeeded': return ['bg' => '#ECFDF5', 'fg' => '#047857']; case 'pending': case 'unverified': return ['bg' => '#FEF3C7', 'fg' => '#92400E']; case 'failed': case 'amount_mismatch': case 'not_paid': return ['bg' => '#FEE2E2', 'fg' => '#B91C1C']; case 'refunded': return ['bg' => '#EDE9FE', 'fg' => '#6D28D9']; default: return ['bg' => '#F1F5F9', 'fg' => '#475569']; } } private function is_internal_submission_key($key) { $key = (string) $key; return $key !== '' && $key[0] === '_'; } private function filter_submission_display_data($data) { if (!is_array($data)) return []; $filtered = []; foreach ($data as $key => $field) { if ($this->is_internal_submission_key($key)) continue; // r4: legacy-abandoned compatibility shim. Round 1-3 // abandoned rows (and any row written before the r4 writer fix) // stored captured partial values in a flat // `formforge_field_ => scalar` shape instead of the canonical // ` => {label, value, type}` object a normal submission uses. // The renderer (table, columns, View modal) only understands the // object shape, so those rows rendered empty. Normalise the flat // shape here, once, so every downstream consumer stays // single-pathed — no per-row `status === 'abandoned'` branching. // New rows already arrive in the object shape and skip this. if (!is_array($field)) { if (!is_scalar($field)) continue; $field_id = strpos((string) $key, 'formforge_field_') === 0 ? substr((string) $key, strlen('formforge_field_')) : (string) $key; if ($field_id === '') continue; // Key on the bare field id so the existing // $field_config_map[$id] label lookup in the Submissions // table resolves the human label automatically. $filtered[$field_id] = [ 'label' => $field_id, 'value' => (string) $field, 'type' => 'text', ]; continue; } $filtered[$key] = $field; } return $filtered; } private function get_submission_columns($subs, $form_obj) { $columns = []; if ($form_obj && !empty($form_obj->fields)) { foreach ($form_obj->fields as $field) { $type = $field['type'] ?? ''; $id = (string) ($field['id'] ?? ''); if ($id === '' || in_array($type, ['heading', 'html_block', 'divider', 'page_break'], true)) continue; $columns[] = $id; } } if (!empty($columns)) return $columns; foreach ($subs as $sub) { $data = $this->filter_submission_display_data(json_decode($sub->data, true) ?: []); foreach (array_keys($data) as $key) { if (!in_array($key, $columns, true)) { $columns[] = $key; } } } return $columns; } private function normalize_connect_error($service, $result) { if (!is_wp_error($result)) { return ''; } $message = trim((string) $result->get_error_message()); $normalized = strtolower($message); if ($normalized === 'invalid request' || $normalized === 'api error') { if ($service === 'mailchimp') { return __('Could not connect to Mailchimp. Check the API key and try again.', 'fillinforge'); } if ($service === 'hubspot') { return __('Could not connect to HubSpot. Check the private app token and try again.', 'fillinforge'); } } return $message !== '' ? $message : __('Connection failed. Please try again.', 'fillinforge'); } private function disconnect_failed_message($service) { /* translators: %s = service name (Mailchimp, HubSpot) */ return sprintf(__('Could not disconnect %s. Please try again.', 'fillinforge'), $service); } private function sanitize_service_webhook_url($raw_url, $service) { $url = trim((string) $raw_url); if ($url === '') { return ''; } $sanitized = esc_url_raw($url); if ($sanitized === '') { return new WP_Error('invalid_url', __('Enter a valid webhook URL.', 'fillinforge')); } $host = strtolower((string) wp_parse_url($sanitized, PHP_URL_HOST)); $path = (string) wp_parse_url($sanitized, PHP_URL_PATH); $scheme = strtolower((string) wp_parse_url($sanitized, PHP_URL_SCHEME)); if ($service === 'slack') { if ($scheme !== 'https' || $host !== 'hooks.slack.com' || strpos($path, '/services/') !== 0) { return new WP_Error('invalid_slack_webhook', __('Slack webhook URL must start with https://hooks.slack.com/services/.', 'fillinforge')); } } if ($service === 'discord') { if ($scheme !== 'https' || $host !== 'discord.com' || strpos($path, '/api/webhooks/') !== 0) { return new WP_Error('invalid_discord_webhook', __('Discord webhook URL must start with https://discord.com/api/webhooks/.', 'fillinforge')); } } return $sanitized; } /** * The settings form, read field by field. * * Never the whole $_POST['formforge_settings'] array: core fields come from * the list below, add-on fields from the 'formforge/settings_fields' filter * (name => type; the add-on that posts a field declares it there), and * anything else that was posted is dropped. Each value is unslashed and * cleaned by its type here, so what the handler works with is already clean. * The caller has verified the nonce and the capability. * * @return array Only the fields that were posted. */ private function read_settings_post() { $core = [ 'map_provider' => 'text', 'map_api_key' => 'text', 'map_google_api_key' => 'text', 'map_yandex_js_api_key' => 'text', 'map_yandex_geocoder_key' => 'text', 'map_yandex_suggest_key' => 'text', 'default_notification_email' => 'email', 'email_sender_name' => 'text', 'whatsapp_global_enabled' => 'flag', 'whatsapp_phone_e164' => 'text', ]; $declared = apply_filters('formforge/settings_fields', $core); $fields = $core; if (is_array($declared)) { foreach ($declared as $name => $type) { if (is_string($name) && $name !== '' && !isset($core[$name])) { $fields[$name] = is_string($type) ? $type : 'text'; } } } $out = []; if (!isset($_POST['formforge_settings']) || !is_array($_POST['formforge_settings'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- the caller verifies the nonce before reading. return $out; } foreach ($fields as $name => $type) { if (!isset($_POST['formforge_settings'][$name])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- the caller verifies the nonce before reading. continue; } // One named field, cleaned as it is read; an email is then narrowed to an address. $value = is_scalar($_POST['formforge_settings'][$name]) ? sanitize_text_field(wp_unslash($_POST['formforge_settings'][$name])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- the caller verifies the nonce before reading. if ($type === 'flag') { $out[$name] = '1'; } elseif ($type === 'email') { $out[$name] = sanitize_email($value); } else { $out[$name] = $value; } } return $out; } private function sanitize_whatsapp_recipient_phone($raw_phone) { $raw_phone = trim((string) $raw_phone); if ($raw_phone === '') { return ''; } $has_leading_plus = substr($raw_phone, 0, 1) === '+'; $digits = preg_replace('/\D+/', '', $raw_phone); if (!is_string($digits) || $digits === '') { return ''; } return ($has_leading_plus ? '+' : '') . $digits; } /** * How many submissions each form has saved: the visitors' own, not abandoned drafts, not the editor's test * submissions (the rule the add-on's analytics figure uses) and not the notes about a charge whose submission * was never saved (they are money to reconcile, not responses; they stay in the Submissions list), for all * time. A note is 'captured_unsubmitted' whatever else it holds; with any other payment status (a differing * amount, processing, held for capture, not verified) it is told from a saved submission by its data: the payment * record is there and no field answer holds the id (a saved submission's payment field always does). * One grouped query for the whole list. * * @return array form id => count (a form with none is absent) */ private function saved_submission_counts() { global $wpdb; $rows = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom plugin table; the statement has no outside value. "SELECT form_id, COUNT(*) AS total FROM {$wpdb->prefix}formforge_submissions WHERE COALESCE(status, '') NOT IN ('abandoned', 'test') AND COALESCE(payment_status, '') <> 'captured_unsubmitted' AND NOT (COALESCE(payment_status, '') IN ('amount_mismatch', 'processing', 'requires_capture', 'unverified') AND data LIKE '%\"payment_id\":%' AND data NOT LIKE '%\"value\":%') GROUP BY form_id", ARRAY_A ); $counts = []; foreach ((array) $rows as $row) { $counts[(int) $row['form_id']] = (int) $row['total']; } return $counts; } public function render_forms_list() { // Admin list shows the FULL saved set (incl. forms locked by Free // soft-limit) so the admin can see / edit / delete everything they // own. Runtime REST / shortcode discovery uses get_all which // slices to the Free limit. $forms = FORMFORGE_Form_Builder::instance()->get_all_unfiltered(); // The Responses column is the visitors' saved submissions for all time, counted from the submissions table in one // grouped query, with the add-on or without it (BUG-FORM-BUILD-01; round 5: the add-on's own figure is a window of // 30 days and stays on the Analytics screen). $saved_counts = $this->saved_submission_counts(); ?>
()
get_stats($form->id) : ['views' => 0, 'submissions' => 0, 'conversion_rate' => 0]; $responses = (int) ($saved_counts[(int) $form->id] ?? 0); $field_count = is_array($form->fields) ? count($form->fields) : 0; ?>

→
title); ?>
ID: id); ?> · created_at ?? 'now'))); ?>
[formforge id="id); ?>"] %
enqueue_screen_script('forms-list', 'formforgeAdminFormsList', [ /* translators: %d: number of forms */ 'title' => sprintf(__('Forms (%d)', 'fillinforge'), count($forms)), ]); } /** * Render the AI Submission Analysis entry point (button + panel + JS). * * "AI Submission Analysis" analyzes collected submissions / conversion * data, so its primary home is the Submissions page (and Analytics). The * form editor keeps it as a secondary in-context shortcut. This single * helper renders all three so the button markup, the credit badge and the * job-status polling behaviour stay identical everywhere it appears. * * @param int $form_id Form whose submissions to analyze. * @param string $context 'editor' | 'submissions' | 'analytics' — controls * layout only. Recommendation "apply" actions are * editor-only (they mutate the builder's field JSON). */ public function render_ai_analysis_widget($form_id, $context = 'submissions') { $form_id = intval($form_id); if (!$form_id) return; if (!class_exists('FORMFORGE_Submissions_AI')) return; // Gate identically to the AJAX handler — no point showing a button // that the endpoint will reject. if (!$this->addon_feature_on('submissions_ai')) return; $is_editor = ($context === 'editor'); // Editor: a compact standalone button right under the page heading. // Submissions / Analytics: the button gets its own toolbar row (with a // one-line hint) above the table. Same gradient + .ff-credits-badge // either way so it reads as one consistent control. $btn_style = $is_editor ? 'display:inline-flex;align-items:center;gap:6px;background:linear-gradient(135deg,#2563EB,#3B82F6);color:#fff;border:none;padding:7px 16px;border-radius:6px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.15s;box-shadow:0 1px 4px rgba(59,130,246,0.18);' : 'display:inline-flex;align-items:center;gap:6px;background:linear-gradient(135deg,#2563EB,#3B82F6);color:#fff;border:none;padding:8px 18px;border-radius:8px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.15s;box-shadow:0 1px 4px rgba(59,130,246,0.18);'; $analysis_badge = class_exists('Forge_Wporg_Disabled_Credits') ? Forge_Wporg_Disabled_Credits::render_badge_html('analyze_submissions', 'ff') : ''; ?>
enqueue_screen_script('ai-analysis', 'formforgeAdminAiAnalysis', [ 'formId' => $form_id, 'isEditor' => $is_editor, 'editUrl' => admin_url('admin.php?page=formforge-new&form_id='), 'i18n' => [ 'abandonedPartial' => __('abandoned/partial', 'fillinforge'), 'addPlaceholder' => __('Add placeholder', 'fillinforge'), 'aiUx' => __('AI UX', 'fillinforge'), 'analysisErrorPleaseTry' => __('Analysis error. Please try again.', 'fillinforge'), 'analysisInProgress' => __('Analysis in progress…', 'fillinforge'), 'analysisIsTakingLonger' => __('Analysis is taking longer than expected. Please try again in a moment.', 'fillinforge'), 'analysisQueued' => __('Analysis queued…', 'fillinforge'), 'analyticsDriven' => __('Analytics-driven', 'fillinforge'), 'changedRequiredToOptional' => __('Changed required to optional', 'fillinforge'), 'completed' => __('completed', 'fillinforge'), 'confidence' => __('Confidence', 'fillinforge'), 'conversionIsAboveAverage' => __('Conversion is above average. The recommendations below are fine-tuning suggestions.', 'fillinforge'), 'failedPayments' => __('failed payments', 'fillinforge'), 'fieldRemovedFromForm' => __('Field removed from form', 'fillinforge'), 'fieldWasAlreadyOptional' => __('Field was already optional', 'fillinforge'), 'formConversionIsBelow' => __('Form conversion is below baseline. Apply the recommendations below for a significant uplift.', 'fillinforge'), 'heuristic' => __('Heuristic', 'fillinforge'), 'lastAnalyzed' => __('Last analyzed', 'fillinforge'), 'makeOptional' => __('Make optional', 'fillinforge'), 'moveField' => __('Move field', 'fillinforge'), 'multiStepModeEnabled' => __('Multi-step mode enabled', 'fillinforge'), 'needsAttention' => __('Needs attention', 'fillinforge'), 'networkErrorPleaseTry' => __('Network error. Please try again later.', 'fillinforge'), 'noCachedAnalysisYet' => __('No cached analysis yet. Run a new analysis first.', 'fillinforge'), 'openedInEditor' => __('Opened in editor', 'fillinforge'), 'recommendationApplied' => __('Recommendation applied', 'fillinforge'), 'reduceOptions' => __('Reduce options', 'fillinforge'), 'removeField' => __('Remove field', 'fillinforge'), /* translators: %s: field label */ 'removeFieldSFrom' => __('Remove field "%s" from the form?', 'fillinforge'), 'reviewField' => __('Review field', 'fillinforge'), 'roomToImprove' => __('Room to improve', 'fillinforge'), 'sample' => __('Sample', 'fillinforge'), 'simplifyLabel' => __('Simplify label', 'fillinforge'), 'splitIntoSteps' => __('Split into steps', 'fillinforge'), 'targetFieldHighlighted' => __('Target field highlighted', 'fillinforge'), 'theFormWorksBut' => __('The form works, but there are noticeable issues hurting conversion. Focus on the critical items first.', 'fillinforge'), 'usingCachedAnalysis' => __('Using cached analysis', 'fillinforge'), 'yourFormIsIn' => __('Your form is in good shape', 'fillinforge'), ], 'html' => [ 'outOf' => esc_html__('out of 100', 'fillinforge'), 'recommendations' => esc_html__('Recommendations', 'fillinforge'), ], ], [], true); ?> get_unfiltered($form_id) : null; $field_types = FORMFORGE_Field_Types::get_types(); $shortcode_docs_url = defined('FORGE_DOCS_URL_FORMFORGE') ? rtrim(FORGE_DOCS_URL_FORMFORGE, '/') . '/docs/user-guide/adding-a-form-to-your-website/' : ''; ?>

render_ai_analysis_widget($form_id, 'editor'); } ?>
enqueue_screen_script('editor-start-blank', 'formforgeAdminEditorStartBlank', [ 'untitled' => __('Untitled Form', 'fillinforge'), ]); ?> addon_feature_on('ai_generation')): ?>
AI-Powered

$all_templates, 'categories' => $categories, 'i18n' => [ 'allTemplates' => __('All Templates', 'fillinforge'), ], 'html' => [ // "N fields" of each card, in the form of its number (template key => text). 'fieldCounts' => self::template_field_counts($all_templates), 'noTemplatesFound' => esc_html__('No templates found', 'fillinforge'), ], ]; // The AI generator's link and messages belong to the add-on: the page carries them only when it runs. if ($this->addon_active()) { $templates_data['accountUrl'] = admin_url('admin.php?page=formforge-license'); $templates_data['i18n'] += [ 'activeSubscriptionRequired' => __('Active subscription required', 'fillinforge'), 'aiGenerationIsNot' => __('AI generation is not available on this site yet. Sign in to your Avakode account in the Fillin Forge Pro settings.', 'fillinforge'), 'aiGenerationUnavailable' => __('AI generation unavailable', 'fillinforge'), 'cannotReachTheServer' => __('Cannot reach the server', 'fillinforge'), 'checkYourInternetConnection' => __('Check your internet connection and try again.', 'fillinforge'), 'couldNotGenerateThe' => __('Could not generate the form', 'fillinforge'), 'couldNotUnderstandThe' => __('Could not understand the request', 'fillinforge'), 'notEnoughAiCredits' => __('Not enough AI credits left to generate this form.', 'fillinforge'), 'openProSettings' => __('Open Fillin Forge Pro settings', 'fillinforge'), 'outOfCredits' => __('Out of credits', 'fillinforge'), 'trialCreditsTitle' => __('Not enough trial credits', 'fillinforge'), 'choosePlan' => __('Choose a plan', 'fillinforge'), 'trialCreditsExhausted' => __('Your free trial has too few credits left for this action. Connect a licence or choose a plan to keep using AI.', 'fillinforge'), 'buyCredits' => __('Buy credits', 'fillinforge'), 'resets' => __('Resets:', 'fillinforge'), 'serviceTemporarilyUnavailable' => __('Service temporarily unavailable', 'fillinforge'), 'signInToYour' => __('Sign in to your Avakode account to use AI generation.', 'fillinforge'), 'theAiServiceCould' => __('The AI service could not be reached. Make sure Fillin Forge Pro is active and the WordPress REST API is enabled, then try again.', 'fillinforge'), 'tooManyRequests' => __('Too many requests', 'fillinforge'), 'tryAgainWithA' => __('Try again with a more specific form description (fields, types, required-ness).', 'fillinforge'), 'unknownErrorTryAgain' => __('Unknown error. Try again or contact support.', 'fillinforge'), 'waitAMinuteAnd' => __('Wait a minute and try again. The service limits generation frequency.', 'fillinforge'), 'weAreAlreadyOn' => __('We are already on it — please try again in a couple of minutes.', 'fillinforge'), ]; $templates_data['html'] += [ 'generating' => esc_html__('Generating…', 'fillinforge'), 'tryAgain' => esc_html__('Try again', 'fillinforge'), /* translators: %d: seconds remaining before retry is allowed */ 'tryAgainIn' => esc_html__('Try again (%d)', 'fillinforge'), ]; } $this->enqueue_screen_script('editor-templates', 'formforgeAdminEditorTemplates', $templates_data); ?>

__('Basic', 'fillinforge'), 'choice' => __('Choice', 'fillinforge'), 'advanced' => __('Advanced', 'fillinforge'), 'layout' => __('Layout', 'fillinforge')]; foreach ($categories as $cat => $cat_label): ?>

$info): if (($info['category'] ?? '') !== $cat) continue; // A type whose code lives in the add-on is listed only while the add-on reports it running. $feature_gate = $this->field_type_feature_gate($type); if ($feature_gate !== '' && !$this->addon_feature_on($feature_gate)) continue; ?>
fields)): foreach ($form->fields as $i => $field): $this->render_field_card($field, $i); endforeach; else: ?>

addon_active()): // the switch for the add-on's conversational layout ?> addon_feature_on('conversational'); $conv_enabled = !empty($form->settings['conversational']); // what is stored: a closed switch is drawn as it is saved ?>
render_editor_lock('conversational', false, ['conversational' => false], $conv_enabled); $this->enqueue_screen_script('editor-conversational', 'formforgeAdminEditorConversational', [ 'canUse' => (bool) $conv_can_use, ]); ?> settings['submit_text'] ?? __('Submit', 'fillinforge')); $success_message = (string) ($form->settings['success_message'] ?? __('Thank you! Your submission has been received.', 'fillinforge')); $redirect_url = (string) ($form->settings['redirect_url'] ?? ''); $submit_action = sanitize_key($form->settings['submit_action'] ?? (!empty($form->settings['redirect_url']) ? 'redirect' : 'message')); if (!in_array($submit_action, FORMFORGE_Form_Builder::SUBMIT_ACTIONS, true)) $submit_action = 'message'; $page_actions = FORMFORGE_Form_Builder::sanitize_page_actions($form->settings['page_actions'] ?? []); ?>
enqueue_screen_script('editor-form-settings'); ?> addon_active()): ?> settings['track_abandonment']) ? true : (bool) $form->settings['track_abandonment']; // Capture values stays default OFF — value-level capture is // a separate explicit opt-in for GDPR-friendly behavior. $track_capture_values = !empty($form->settings['track_abandonment_capture_values']); ?>
enqueue_screen_script('editor-abandon'); ?> settings['notify_admin']); $notify_email = (string) ($form->settings['notify_email'] ?? get_option('admin_email')); $auto_reply = !empty($form->settings['auto_reply']); $auto_reply_field = (string) ($form->settings['auto_reply_field'] ?? ''); $auto_reply_subject = (string) ($form->settings['auto_reply_subject'] ?? __('Thank you for your submission', 'fillinforge')); $auto_reply_message = (string) ($form->settings['auto_reply_message'] ?? __('Thank you for contacting us. We have received your submission and will get back to you soon.', 'fillinforge')); ?>
enqueue_screen_script('editor-notifications', 'formforgeAdminEditorNotifications', [ 'autoReplyField' => $auto_reply_field, 'html' => [ 'selectEmailField' => esc_html__('Select email field...', 'fillinforge'), ], ]); ?> addon_active()): ?> settings['slack_webhook_url'] ?? ''); // An empty address means "use the global one", so a form sends with no address of its own; its own off flag is what stops it. $slack_off = FORMFORGE_Form_Builder::setting_is_turned_off($form->settings ?? [], 'slack_enabled'); $slack_on = !$slack_off && ($slack_url !== '' || get_option('formforge_slack_webhook_url', '') !== ''); ?>
enqueue_screen_script('editor-slack'); ?> addon_active()): ?> settings['discord_webhook_url'] ?? ''); // An empty address means "use the global one", so a form sends with no address of its own; its own off flag is what stops it. $discord_off = FORMFORGE_Form_Builder::setting_is_turned_off($form->settings ?? [], 'discord_enabled'); $discord_on = !$discord_off && ($discord_url !== '' || get_option('formforge_discord_webhook_url', '') !== ''); ?>
enqueue_screen_script('editor-discord'); ?> addon_active()): ?> settings['telegram_enabled']); $tg_chat_id = (string) ($form->settings['telegram_chat_id'] ?? ''); ?>
enqueue_screen_script('editor-telegram'); ?> addon_active()): ?> settings['whatsapp_enabled']); ?>
enqueue_screen_script('editor-whatsapp'); ?> settings['webhook_url'] ?? ''); $webhook_headers = (string) ($form->settings['webhook_headers'] ?? ''); ?>
enqueue_screen_script('editor-webhook'); ?> addon_active()): ?> settings['mailchimp_enabled']); $mc_list_id = (string) ($form->settings['mailchimp_list_id'] ?? ''); $mc_email_field = (string) ($form->settings['mailchimp_email_field'] ?? ''); ?>
enqueue_screen_script('editor-mailchimp', 'formforgeAdminEditorMailchimp', [ 'emailField' => $mc_email_field, 'html' => [ 'autoDetectEmailField' => esc_html__('Auto-detect email field', 'fillinforge'), ], ]); ?> addon_active()): ?> settings['gsheets_enabled']); ?>
enqueue_screen_script('editor-sheets'); ?> addon_active()): ?> settings['calendar_enabled']); ?>
enqueue_screen_script('editor-calendar', 'formforgeAdminEditorCalendar', [ 'i18n' => [ 'failedToLoadCalendars' => __('Failed to load calendars.', 'fillinforge'), 'loadMyCalendars' => __('Load my calendars', 'fillinforge'), 'loading' => __('Loading…', 'fillinforge'), 'networkError' => __('Network error.', 'fillinforge'), 'selectACalendar' => __('— select a calendar —', 'fillinforge'), ], ]); ?> addon_active()): ?> settings['hubspot_enabled']); ?>
enqueue_screen_script('editor-hubspot'); ?> addon_active()): ?> settings['post_submission_enabled']); $ps_type = (string) ($form->settings['post_submission_type'] ?? 'post'); $ps_status = (string) ($form->settings['post_submission_status'] ?? 'draft'); $ps_title_field = (string) ($form->settings['post_title_field'] ?? ''); $ps_content_field = (string) ($form->settings['post_content_field'] ?? ''); $ps_can_use = $this->addon_feature_on('post_submission'); $post_types = get_post_types(['public' => true], 'objects'); ?>
enqueue_screen_script('editor-postsub', 'formforgeAdminEditorPostsub', [ 'titleField' => $ps_title_field, 'contentField' => $ps_content_field, 'html' => [ 'selectField' => esc_html__('Select field...', 'fillinforge'), ], ]); ?> addon_active()): ?> settings['create_user']); $ur_role = sanitize_key($form->settings['user_role'] ?? 'subscriber'); $ur_email_field = (string) ($form->settings['user_email_field'] ?? ''); $ur_name_field = (string) ($form->settings['user_name_field'] ?? ''); $ur_can_use = $this->addon_feature_on('user_registration'); $ur_roles = [ 'subscriber' => __('Subscriber', 'fillinforge'), 'contributor' => __('Contributor', 'fillinforge'), 'author' => __('Author', 'fillinforge'), ]; if (!isset($ur_roles[$ur_role])) { $ur_role = 'subscriber'; } ?>
enqueue_screen_script('editor-userreg', 'formforgeAdminEditorUserreg', [ 'emailField' => $ur_email_field, 'nameField' => $ur_name_field, 'html' => [ 'autoDetectNameField' => esc_html__('Auto-detect name field', 'fillinforge'), 'selectEmailField' => esc_html__('Select email field...', 'fillinforge'), ], ]); ?>
[formforge id="id); ?>"] → enqueue_screen_script('editor-copy-shortcode'); ?>

admin_url('admin-ajax.php'), 'sending' => __('Sending…', 'fillinforge'), 'failed' => __('The test submission could not be sent. Please try again.', 'fillinforge'), 'unsaved' => __('You have unsaved changes: the test uses the saved version of this form.', 'fillinforge'), ]) . ';' ); wp_add_inline_script('formforge-admin', <<<'FORMFORGE_TEST_SUBMIT_JS' (function(d){ var btn = document.getElementById('ff-send-test-submission'); var out = document.getElementById('ff-test-submit-result'); if (!btn || !out || !d) return; var idleLabel = btn.textContent; // The server HTML-escapes validation messages; show them as plain text. function plain(s){ return new DOMParser().parseFromString(String(s), 'text/html').documentElement.textContent; } function clearOut(){ while (out.firstChild) out.removeChild(out.firstChild); } function line(text, cls, href){ var p = document.createElement('p'); p.className = 'ff-test-submit-line ' + cls; if (href) { var a = document.createElement('a'); a.href = href; a.target = '_blank'; a.rel = 'noopener'; a.textContent = text; p.appendChild(a); } else { p.textContent = text; } out.appendChild(p); } function done(){ if (document.querySelector('.formforge-save-bar--dirty')) { line(d.unsaved, 'is-warn'); } btn.disabled = false; btn.textContent = idleLabel; } btn.addEventListener('click', function(){ btn.disabled = true; btn.textContent = d.sending; clearOut(); var fd = new FormData(); fd.append('action', 'formforge_test_submission'); fd.append('nonce', btn.getAttribute('data-nonce')); fd.append('form_id', btn.getAttribute('data-form-id')); fetch(d.ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' }) .then(function(r){ return r.json(); }) .then(function(body){ var data = (body && body.data) || {}; if (body && body.success) { line(data.record_label, 'is-ok', data.record_url); line(data.mail_text, 'is-' + data.mail_state); } else if (data.errors && data.errors.length) { data.errors.forEach(function(e){ line(plain(e), 'is-error'); }); } else { line(data.message ? plain(data.message) : d.failed, 'is-error'); } done(); }) .catch(function(){ clearOut(); line(d.failed, 'is-error'); done(); }); }); })(window.formforgeTestSubmission); FORMFORGE_TEST_SUBMIT_JS ); endif; ?>
*' : ''; ?>
☰
get_all(); // paginate the submissions list. Default 20 per page, // user-selectable 10/20/50/100 via query string. Numeric pagination // links rendered with paginate_links under the table. $per_page = intval($_GET['per_page'] ?? 20); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation. if (!in_array($per_page, [10, 20, 50, 100], true)) $per_page = 20; $current_page = max(1, intval($_GET['paged'] ?? 1)); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation. // A link to one submission (the "Time not confirmed" mail) opens the page it is on. $focus_id = intval($_GET['ff_sub'] ?? 0); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation. if ($form_id && $focus_id > 0 && !isset($_GET['paged'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation. $current_page = FORMFORGE_Core::submission_page($form_id, $focus_id, $per_page) ?: $current_page; } $offset = ($current_page - 1) * $per_page; $subs = []; $total = 0; if ($form_id) { $total = (int) $wpdb->get_var($wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom plugin table; direct query is intended. "SELECT COUNT(*) FROM {$wpdb->prefix}formforge_submissions WHERE form_id = %d", $form_id )); $subs = $wpdb->get_results($wpdb->prepare( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom plugin table; direct query is intended. "SELECT * FROM {$wpdb->prefix}formforge_submissions WHERE form_id = %d ORDER BY created_at DESC, id DESC LIMIT %d OFFSET %d", $form_id, $per_page, $offset )); } $total_pages = max(1, (int) ceil($total / $per_page)); // The Export buttons offer what visitors submitted. A form whose list // holds only test submissions (the editor's "Send a test submission") // has nothing to export: the list shows them, an export never does. $exportable = $form_id ? FORMFORGE_Core::count_exportable_submissions($form_id) : 0; ?>

0): ?> 0): ?>
render_ai_analysis_widget($form_id, 'submissions'); } ?> field config for radio label lookup. // R4: built via the shared build_field_config_map and // fed into resolve_field_label so the table header, the // View modal, and the PDF all resolve labels identically. // Admin Submissions view must read any saved form (even past // Free soft-limit) so submissions for forms 6..N still render. $form_obj = FORMFORGE_Form_Builder::instance()->get_unfiltered($form_id); $field_config_map = $this->build_field_config_map($form_obj); $columns = $this->get_submission_columns($subs, $form_obj); ?> resolve_field_label($col, ['label' => ''], $field_config_map); ?> data, true) ?: []; $view_data = $this->prepare_submission_view_data($data, $sub->id, $field_config_map); // surface payment metadata in the View modal — // payment_status colored chip + payment_intent_id linked // to Stripe Dashboard + amount/currency + updated_at. $payment_details = $this->prepare_payment_details($data, $sub); $calendar_status = $this->prepare_calendar_status($data); // r4: render table cells from the SAME normalised // data the View modal uses ($view_data). The raw $data of // a legacy-abandoned row keys captured values as // `formforge_field_`, so a direct $data[$col] lookup // (where $col is the plain field id) missed and the row // showed empty cells. filter_submission_display_data // inside prepare_submission_view_data normalises both // the legacy flat shape and the canonical object shape to // ` => {label,value,type}`, so this is now the single // value-extraction path for table + modal alike. $cell_data = $view_data; $payment_chip = $this->payment_status_chip_style($sub->payment_status ?? ''); $is_test_sub = ($sub->status === FORMFORGE_Test_Submission::STATUS); ?>
#
id); ?> created_at))); ?> status); ?> payment_status)): ?> payment_status)); ?>
$per_page) { $base = add_query_arg(['page'=>'formforge-submissions','form_id'=>$form_id,'per_page'=>$per_page], admin_url('admin.php')); $links = paginate_links([ 'base' => $base . '&paged=%#%', 'format' => '', 'current' => $current_page, 'total' => $total_pages, 'prev_text' => '«', 'next_text' => '»', 'type' => 'array', ]); if (is_array($links)) { echo '
'; echo '
' /* translators: %s: number of items */ . esc_html(sprintf(_n('%s item', '%s items', $total, 'fillinforge'), number_format_i18n($total))) /* translators: 1: current page number, 2: total number of pages */ . ' · ' . esc_html(sprintf(__('Page %1$d of %2$d', 'fillinforge'), $current_page, $total_pages)) . '
'; echo '
' . wp_kses_post(implode(' ', $links)) . '
'; echo '
'; } } ?> enqueue_screen_script('submissions', 'formforgeAdminSubmissions', [ 'i18n' => [ 'paymentDetails' => esc_html__('Payment details', 'fillinforge'), 'status' => __('Status', 'fillinforge'), 'amount' => __('Amount', 'fillinforge'), 'paymentId' => __('Payment ID', 'fillinforge'), 'paymentDate' => __('Payment date', 'fillinforge'), 'downloadFile' => __('Download file', 'fillinforge'), 'confirmDelete' => __('Delete this submission? Attached private files will also be removed.', 'fillinforge'), 'deleteFailed' => __('Could not delete submission.', 'fillinforge'), ], ]); ?>

__('Stripe test secret key', 'fillinforge'), 'stripe_live_secret_key' => __('Stripe live secret key', 'fillinforge'), 'stripe_webhook_secret' => __('Stripe webhook secret', 'fillinforge'), 'recaptcha_secret_key' => __('reCAPTCHA secret key', 'fillinforge'), ]; $label = isset($labels[$posted_key]) ? $labels[$posted_key] : __('secret', 'fillinforge'); /* translators: %s: name of the secret, e.g. "Stripe live secret key". */ $save_errors[] = sprintf(__('The %s could not be encrypted, so the saved value was kept.', 'fillinforge'), $label); return $stored_value; } return $encrypted; } /** * The Pro half of the Settings save: WhatsApp, Telegram chat, Slack and Discord webhook URLs, Stripe keys. * Each is written only where pro_setting_may_change says so: freely with a live licence; without one * only a switch-off (the field emptied, or its "Turn this off" box ticked). Stripe is read-only without a * licence. Returns the settings array with the WhatsApp values applied; the options are written here. * * @param array $settings The array that becomes formforge_settings. * @param array $posted_settings read_settings_post. * @param array $existing_strp Stored Stripe settings. * @param callable $preserve_secret Keeps a stored secret when its input came empty. * @param string $save_errors Collects messages for the screen. * @return array */ private function save_pro_global_settings(array $settings, array $posted_settings, $existing_strp, callable $preserve_secret, array &$save_errors) { $existing_strp = is_array($existing_strp) ? $existing_strp : []; $posted = static function ($name) { return isset($_POST[$name]) ? sanitize_text_field(wp_unslash($_POST[$name])) : null; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in render_settings before this runs. }; $turned_off = static function ($name) { return !empty($_POST[$name]); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in render_settings before this runs. }; // WhatsApp: a switch and a number. Without a live licence it is left as it is (it is paused anyway). if ($this->pro_setting_state('whatsapp') === 'live' && $this->addon_active()) { $settings['whatsapp_global_enabled'] = isset($posted_settings['whatsapp_global_enabled']) ? 1 : 0; $settings['whatsapp_phone_e164'] = $this->sanitize_whatsapp_recipient_phone($posted_settings['whatsapp_phone_e164'] ?? ''); } // Global Telegram Chat ID $telegram = $turned_off('telegram_turn_off') ? '' : $posted('telegram_chat_id'); if ($telegram !== null && $this->pro_setting_may_change('telegram', get_option('formforge_telegram_chat_id', ''), $telegram)) { update_option('formforge_telegram_chat_id', $telegram); } // Global Slack Webhook URL $slack_raw = $turned_off('slack_turn_off') ? '' : (isset($_POST['slack_webhook_url']) ? esc_url_raw(wp_unslash($_POST['slack_webhook_url'])) : null); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in render_settings. if ($slack_raw !== null && $this->pro_setting_may_change('slack', get_option('formforge_slack_webhook_url', ''), $slack_raw)) { $slack_url = $this->sanitize_service_webhook_url($slack_raw, 'slack'); if (is_wp_error($slack_url)) { $save_errors[] = $slack_url->get_error_message(); } else { update_option('formforge_slack_webhook_url', $slack_url); } } // Global Discord Webhook URL $discord_raw = $turned_off('discord_turn_off') ? '' : (isset($_POST['discord_webhook_url']) ? esc_url_raw(wp_unslash($_POST['discord_webhook_url'])) : null); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in render_settings. if ($discord_raw !== null && $this->pro_setting_may_change('discord', get_option('formforge_discord_webhook_url', ''), $discord_raw)) { $discord_url = $this->sanitize_service_webhook_url($discord_raw, 'discord'); if (is_wp_error($discord_url)) { $save_errors[] = $discord_url->get_error_message(); } else { update_option('formforge_discord_webhook_url', $discord_url); } } // Stripe settings — secrets pass through preserve_secret so empty inputs keep the stored // ciphertext; non-empty inputs are FORMFORGE_Crypto::encrypt'd before persistence. Open with a // live licence only. After the licence ended only "turn payments off" is taken (below); the keys stay. if ($this->pro_setting_state('payment') === 'live' && $this->addon_active() && isset($_POST['stripe_mode'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in render_settings. $stripe_settings = [ 'mode' => sanitize_text_field(wp_unslash($_POST['stripe_mode'] ?? 'test')), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in render_settings. 'test_publishable_key' => sanitize_text_field(wp_unslash($_POST['stripe_test_publishable_key'] ?? '')), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in render_settings. 'test_secret_key' => $preserve_secret('stripe_test_secret_key', $existing_strp['test_secret_key'] ?? ''), 'live_publishable_key' => sanitize_text_field(wp_unslash($_POST['stripe_live_publishable_key'] ?? '')), // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in render_settings. 'live_secret_key' => $preserve_secret('stripe_live_secret_key', $existing_strp['live_secret_key'] ?? ''), 'webhook_secret' => $preserve_secret('stripe_webhook_secret', $existing_strp['webhook_secret'] ?? ''), ]; update_option('formforge_stripe_settings', $stripe_settings); FORMFORGE_Pro_Bridge::set_switched_off('payment', false); // saved with a live licence: payments are on again } elseif ($turned_off('stripe_turn_off') && $this->pro_setting_state('payment') === 'lapsed' && $this->addon_active()) { // After the licence ended: turning payments off is the one change taken; the keys stay as saved. FORMFORGE_Pro_Bridge::set_switched_off('payment', true); } return $settings; } /** Whether one of the settings screen's buttons was posted (its nonce is checked in render_settings). */ private function settings_button_posted() { foreach (['formforge_mailchimp_connect', 'formforge_mailchimp_disconnect', 'formforge_google_disconnect', 'formforge_hubspot_disconnect', 'formforge_save_settings'] as $button) { if (isset($_POST[$button])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Only asks whether a button was posted; render_settings verifies the nonce before anything is handled. return true; } } return false; } public function render_settings() { // Null on the wp.org package, which ships without the add-on that // carries the API client. Settings is a always-registered screen, so // an unguarded instance here would white-screen it outright; every // use below asks first, and without the add-on the integration cards // render an invitation in place of their inputs. $forge_api = class_exists('FORMFORGE_Forge_API') ? FORMFORGE_Forge_API::instance() : null; // A post from this screen is taken only from a user who may manage options and only with the screen's own // nonce, checked here before any button is handled; anything else stops with a 403. A plain visit passes. if ($this->settings_button_posted()) { if (!current_user_can('manage_options')) { wp_die(esc_html__('Permission denied.', 'fillinforge'), '', ['response' => 403]); } if (!isset($_POST['formforge_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['formforge_nonce'])), 'formforge_settings')) { wp_die(esc_html__('The page has expired. Reload it and try again.', 'fillinforge'), '', ['response' => 403]); } } // Handle Mailchimp connect/disconnect if (isset($_POST['formforge_mailchimp_connect']) && $this->addon_active()) { $api_key = sanitize_text_field(wp_unslash($_POST['mailchimp_api_key'] ?? '')); if (!empty($api_key)) { if (!$this->addon_feature_on('mailchimp')) { // No live licence: refused here, before anything goes to the server (Q121). echo '

' . esc_html__('Read-only: changing this needs an active Fillin Forge Pro licence.', 'fillinforge') . '

'; } elseif (!$this->is_valid_mailchimp_api_key($api_key)) { echo '

' . esc_html__('Enter a Mailchimp API key in the format key-usX.', 'fillinforge') . '

'; } else { $result = $forge_api ? $forge_api->mailchimp_connect($api_key) : new WP_Error('formforge_addon_missing', $this->addon_missing_message()); if (is_wp_error($result)) { echo '

' . esc_html($this->normalize_connect_error('mailchimp', $result)) . '

'; } else { echo '

' . esc_html__('Mailchimp connected successfully.', 'fillinforge') . '

'; } } } } if (isset($_POST['formforge_mailchimp_disconnect']) && $this->addon_active()) { $disconnect_result = $forge_api ? $forge_api->mailchimp_disconnect() : new WP_Error('formforge_addon_missing', $this->addon_missing_message()); if (is_wp_error($disconnect_result)) { // BUG-FORM-SETT-02: a refused call is not a disconnect; the connection stays on screen. echo '

' . esc_html($this->disconnect_failed_message('Mailchimp')) . '

'; } else { echo '

' . esc_html__('Mailchimp disconnected.', 'fillinforge') . '

'; } } // Handle Google disconnect if (isset($_POST['formforge_google_disconnect']) && $this->addon_active()) { $disconnect_result = $forge_api ? $forge_api->google_disconnect() : new WP_Error('formforge_addon_missing', $this->addon_missing_message()); if (is_wp_error($disconnect_result)) { // BUG-FORM-SETT-02: a refused call is not a disconnect, as with Mailchimp and HubSpot. The connection // stays on screen, the forms keep their spreadsheet and calendar (the account may still be linked). echo '

' . esc_html($this->disconnect_failed_message('Google')) . '

'; } else { // Clear stale per-form selections — without this, every form that // referenced the disconnected account kept showing the old // spreadsheet/calendar in the form-builder UI even though the // OAuth token was revoked. The integration would silently fail // on submission, and the editor had to manually open every form // and clear the picker. $cleared = $this->clear_all_forms_google_settings(); if ($cleared > 0) { echo '

' . sprintf( /* translators: %d = number of forms cleared */ esc_html(_n( 'Google disconnected. Cleared Sheets/Calendar selection from %d form.', 'Google disconnected. Cleared Sheets/Calendar selection from %d forms.', $cleared, 'fillinforge' )), (int) $cleared ) . '

'; } else { echo '

' . esc_html__('Google disconnected.', 'fillinforge') . '

'; } } } // HubSpot *connect* is now a dedicated AJAX flow // (wp_ajax_formforge_hubspot_connect → FORMFORGE_Core::ajax_hubspot_connect), // so it no longer posts the whole Settings
. The result renders // inline in the HubSpot card. Only *disconnect* stays a server submit. if (isset($_POST['formforge_hubspot_disconnect']) && $this->addon_active()) { $disconnect_result = $forge_api ? $forge_api->hubspot_disconnect() : new WP_Error('formforge_addon_missing', $this->addon_missing_message()); if (is_wp_error($disconnect_result)) { echo '

' . esc_html($this->disconnect_failed_message('HubSpot')) . '

'; } else { echo '

' . esc_html__('HubSpot disconnected.', 'fillinforge') . '

'; } } if (isset($_POST['formforge_save_settings'])) { $save_errors = []; // Pull the existing settings so we can keep stored secrets when // the password input was submitted EMPTY (we render those fields // with a placeholder rather than echoing ciphertext into the DOM). $existing = get_option('formforge_settings', []); $existing_strp = get_option('formforge_stripe_settings', []); // Preserve-on-empty helper for masked-secret inputs. A non-empty value is encrypted (ffenc2, // authenticated); if that fails the stored value is kept and the person is told. An empty input // keeps whatever is stored, re-wrapping a legacy ffenc1 value as ffenc2 when that works. The // plain value is never stored: no FORMFORGE_Crypto means the stored value stays. $preserve_secret = function ($posted_key, $stored_value) use (&$save_errors) { $posted = isset($_POST[$posted_key]) ? sanitize_text_field(wp_unslash($_POST[$posted_key])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified in render_settings before this closure runs. return $this->secret_for_save($posted_key, $posted, $stored_value, $save_errors); }; // Field by field, cleaned by type (read_settings_post); never the whole array. $posted_settings = $this->read_settings_post(); $map_provider = sanitize_text_field($posted_settings['map_provider'] ?? 'google'); if (!in_array($map_provider, ['google', 'yandex'], true)) { $map_provider = 'google'; } $legacy_map_api_key = (string) ($existing['map_api_key'] ?? ''); $existing_map_provider = (string) ($existing['map_provider'] ?? 'google'); $existing_google_api_key = (string) ($existing['map_google_api_key'] ?? ''); $existing_yandex_js_key = (string) ($existing['map_yandex_js_api_key'] ?? ''); if ($existing_google_api_key === '' && $existing_map_provider === 'google') { $existing_google_api_key = $legacy_map_api_key; } if ($existing_yandex_js_key === '' && $existing_map_provider === 'yandex') { $existing_yandex_js_key = $legacy_map_api_key; } $posted_legacy_map_api_key = sanitize_text_field($posted_settings['map_api_key'] ?? ''); $map_google_api_key = array_key_exists('map_google_api_key', $posted_settings) ? sanitize_text_field($posted_settings['map_google_api_key']) : ($map_provider === 'google' && $posted_legacy_map_api_key !== '' ? $posted_legacy_map_api_key : $existing_google_api_key); $map_yandex_js_key = array_key_exists('map_yandex_js_api_key', $posted_settings) ? sanitize_text_field($posted_settings['map_yandex_js_api_key']) : ($map_provider === 'yandex' && $posted_legacy_map_api_key !== '' ? $posted_legacy_map_api_key : $existing_yandex_js_key); $settings = is_array($existing) ? $existing : []; $settings = array_merge($settings, [ 'default_notification_email' => sanitize_email($posted_settings['default_notification_email'] ?? get_option('admin_email')), 'email_sender_name' => sanitize_text_field($posted_settings['email_sender_name'] ?? get_bloginfo('name')), ]); $settings['recaptcha_site_key'] = sanitize_text_field(wp_unslash($_POST['recaptcha_site_key'] ?? '')); $settings['recaptcha_secret_key'] = $preserve_secret('recaptcha_secret_key', $existing['recaptcha_secret_key'] ?? ''); $settings['recaptcha_threshold'] = isset($_POST['recaptcha_threshold']) ? (float) sanitize_text_field(wp_unslash($_POST['recaptcha_threshold'])) : 0.5; // Fields an add-on declared through 'formforge/settings_fields' are stored as posted (cleaned by type). $core_keys = ['map_provider', 'map_api_key', 'map_google_api_key', 'map_yandex_js_api_key', 'map_yandex_geocoder_key', 'map_yandex_suggest_key', 'default_notification_email', 'email_sender_name', 'whatsapp_global_enabled', 'whatsapp_phone_e164']; foreach ($posted_settings as $posted_name => $posted_value) { if (!in_array($posted_name, $core_keys, true)) { $settings[$posted_name] = $posted_value; } } $settings['map_provider'] = $map_provider; $settings['map_api_key'] = $map_provider === 'yandex' ? $map_yandex_js_key : $map_google_api_key; $settings['map_google_api_key'] = $map_google_api_key; $settings['map_yandex_js_api_key'] = $map_yandex_js_key; $settings['map_yandex_geocoder_key'] = sanitize_text_field($posted_settings['map_yandex_geocoder_key'] ?? ''); $settings['map_yandex_suggest_key'] = sanitize_text_field($posted_settings['map_yandex_suggest_key'] ?? ''); // Pro settings: open with a live licence only; without one only turning off is taken (Q121). $settings = $this->save_pro_global_settings($settings, $posted_settings, $existing_strp, $preserve_secret, $save_errors); update_option('formforge_settings', $settings); // Q125: the plugin's data goes on uninstall only when this box was ticked; an unticked box posts nothing. update_option('formforge_delete_data_on_uninstall', !empty($_POST['formforge_delete_data_on_uninstall'])); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce verified above, before the settings are read. echo '

' . esc_html__('Settings saved.', 'fillinforge') . '

'; foreach ($save_errors as $save_error) { echo '

' . esc_html($save_error) . '

'; } } $s = get_option('formforge_settings', []); ?>

render_pro_invite(); // only says something when an installed add-on is too old for this core ?>
addon_active()): ?>

addon_feature_on('ai_generation')): ?>
addon_active()): ?>

render_card_lock('telegram', true, 'telegram_turn_off'); ?>

@ForgeAPINotifyBot


1. @ForgeAPINotifyBot
2. /start —
3.
lock_attr('telegram'); ?>>

sanitize_whatsapp_recipient_phone($s['whatsapp_phone_e164'] ?? '') : ''; ?> addon_active()): ?>

render_card_lock('whatsapp', true); ?>

lock_attr('whatsapp'); ?>>

form_submission template.', 'fillinforge')); ?>

>
>
>
>

Google Cloud Console. Yandex Developer.

addon_active()): ?>

render_stripe_lock(); ?>

lock_attr('payment'); ?>>
lock_attr('payment'); ?>>
lock_attr('payment'); ?>>
lock_attr('payment'); ?>>
lock_attr('payment'); ?>>

' . esc_html(rest_url('formforge/v1/stripe/webhook')) . ''), ['code' => []]); ?>

Stripe Dashboard.

addon_active()): ?>

render_card_lock('slack', false, 'slack_turn_off'); ?>


1. api.slack.com/apps →
2.
3.
4.
lock_attr('slack'); ?>>

addon_active()): ?>

render_card_lock('discord', false, 'discord_turn_off'); ?>


1.
2.
3.
lock_attr('discord'); ?>>

addon_active()): ?>

render_card_lock('mailchimp', true); ?>

addon_feature_on('mailchimp'); $mc_status = $integrations_ready ? $forge_api->mailchimp_status() : null; $mc_connected = (!is_wp_error($mc_status) && !empty($mc_status['connected'])); ?>
>

Mailchimp → Account → API keys.

addon_active()): ?>

render_card_lock('google_sheets', true); ?>

google_status() : null; $g_connected = (!is_wp_error($g_status) && !empty($g_status['connected'])); $g_email = (!is_wp_error($g_status) && is_array($g_status) && !empty($g_status['email'])) ? (string) $g_status['email'] : ''; ?>
' . esc_html($g_email) . '' ); ?>
on the URL actually being // non-empty: an resolves to the current page, so the // button silently pointed back at Fillin Forge Settings instead of // starting Google OAuth (retest 2026-05-14). // (cross-plugin): gate the Connect button on the add-on's // feature state, NOT on $integrations_ready, which can be false on a // genuinely connected site (linked after boot, or only a site token // exists). google_auth_url resolves a fresh site token via // Forge_Wporg_Disabled_Connect and returns '' only when no connection path // exists; then the actionable "Connect to Avakode" card is rendered // instead of a dead-end note. $google_pro = $this->addon_feature_on('google_sheets') || $this->addon_feature_on('google_calendar'); $ff_google_auth_url = ($google_pro && $forge_api) ? $forge_api->google_auth_url(admin_url('admin.php?page=formforge-settings')) : ''; // an empty auth URL has two different causes and they // need two different screens. Not linked to Avakode yet is a // step the operator can take, and the connect card below is // the right thing to show. Linked but the Worker will not mint // a site capability token is NOT that — showing the connect // card there renders its *connected* state, so the operator // reads "Connected", finds no Google button, and has no next // step at all. HubSpot on this same screen already says the // true thing; Google now says it too. $ff_avakode_linked = class_exists('Forge_Wporg_Disabled_Connect') && \Forge_Wporg_Disabled_Connect::get_saved_license('formforge') !== ''; // ...and "linked" is itself two states. The site token can be // the thing that will not come, or it can arrive fine and the // Worker still refuse to open the sign-in. Telling the operator // to reconnect Avakode in the second case sends them to fix // something that was never broken, so ask which step failed. $ff_google_failure = ($forge_api && method_exists($forge_api, 'google_auth_failure')) ? (string) $forge_api->google_auth_failure() : ''; $ff_init_refused = strpos($ff_google_failure, 'init_') === 0; ?>

addon_active()): ?>

render_card_lock('hubspot', true); ?>

hubspot_status() : null; $hs_connected = (!is_wp_error($hs_status) && !empty($hs_status['connected'])); // HubSpot connect needs a valid site capability token. // Resolve it up front via the SHARED helper so the Connect // button can be disabled (with an inline reason) when the // token can't be obtained, instead of failing mid-flow with // a generic page-top "Missing site capability token" notice. $hs_site_token = ($integrations_ready && $this->addon_feature_on('hubspot') && !$hs_connected && class_exists('Forge_Wporg_Disabled_Connect')) ? \Forge_Wporg_Disabled_Connect::get_or_refresh_site_token('formforge') : ''; $hs_can_connect = $integrations_ready && $this->addon_feature_on('hubspot') && ($hs_connected || $hs_site_token !== ''); ?>

>

HubSpot → Settings → Private Apps.

__('Enter your HubSpot private app token.', 'fillinforge'), 'connecting' => __('Connecting…', 'fillinforge'), 'nonce' => wp_create_nonce('formforge_hubspot_connect'), 'connected' => __('Connected to HubSpot', 'fillinforge'), 'connectedLabel' => __('Connected', 'fillinforge'), 'failed' => __('Could not connect to HubSpot. Check the private app token and try again.', 'fillinforge'), 'networkError' => __('Network error — please try again.', 'fillinforge'), ]) . ';' ); wp_add_inline_script('formforge-admin', <<<'FORMFORGE_HS_JS' (function(d){ var btn = document.getElementById('ff-hs-connect'); var input = document.getElementById('ff-hs-api-key'); var msg = document.getElementById('ff-hs-connect-msg'); if (!btn || !input || !msg) return; var idleLabel = btn.textContent; function showMsg(text, ok){ msg.style.display = 'block'; msg.style.color = ok ? '#059669' : '#ef4444'; msg.textContent = text; } btn.addEventListener('click', function(){ if (window.formforgeSettingsGuard && !window.formforgeSettingsGuard.confirmAction()) { return; } var key = (input.value || '').trim(); if (key === '') { showMsg(d.emptyKey, false); input.focus(); return; } btn.disabled = true; btn.textContent = d.connecting; msg.style.display = 'none'; var fd = new FormData(); fd.append('action', 'formforge_hubspot_connect'); fd.append('_wpnonce', d.nonce); fd.append('hubspot_api_key', key); fetch(formforgeAdmin.ajaxUrl, { method: 'POST', body: fd, credentials: 'same-origin' }) .then(function(r){ return r.json().then(function(j){ return { ok: r.ok, body: j }; }); }) .then(function(res){ var data = (res.body && res.body.data) || {}; if (res.body && res.body.success) { showMsg(data.message || d.connected, true); btn.textContent = d.connectedLabel; input.disabled = true; if (window.formforgeSettingsGuard) { window.formforgeSettingsGuard.markClean(); } // Reload so the card flips to the connected state + Disconnect button. setTimeout(function(){ window.location.reload(); }, 900); } else { showMsg(data.message || d.failed, false); btn.disabled = false; btn.textContent = idleLabel; } }) .catch(function(){ showMsg(d.networkError, false); btn.disabled = false; btn.textContent = idleLabel; }); }); })(window.formforgeHubSpotConnect || {}); FORMFORGE_HS_JS ); endif; ?>

enqueue_screen_script('settings', 'formforgeAdminSettings', [ 'leaveMessage' => __('You have unsaved settings changes. Leave this page?', 'fillinforge'), ]); } /** * Form Analytics page. Lists every form with view / submit / abandon * counts plus conversion rate, pulled from `wp_formforge_analytics` * via FORMFORGE_Analytics::get_stats. Without the add-on it says * where the feature lives. */ public function render_analytics() { global $wpdb; $forms = FORMFORGE_Form_Builder::instance()->get_all(); $addon_active = $this->addon_active(); // Range selector (7 / 30 / 90 days). Default 30. $days = intval($_GET['days'] ?? 30); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Read-only admin UI state, no data mutation. if (!in_array($days, [7, 30, 90], true)) $days = 30; // The Analytics screen is registered only while the add-on is active (FORMFORGE_Core::admin_menu). if (!$addon_active) { return; } // Per-form abandonment count (separate query, not in get_stats). $since = gmdate('Y-m-d H:i:s', strtotime("-{$days} days")); // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the value is %s-prepared; admin read of the plugin's own table $abandon_rows = $wpdb->get_results($wpdb->prepare( "SELECT form_id, COUNT(*) AS abandons FROM {$wpdb->prefix}formforge_analytics WHERE event_type = 'abandon' AND created_at >= %s GROUP BY form_id", $since )); // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching $abandons_by_form = []; foreach ($abandon_rows as $row) { $abandons_by_form[(int) $row->form_id] = (int) $row->abandons; } // Aggregate totals across all forms. $total_views = 0; $total_submits = 0; $total_abandons = 0; $rows = []; // The entitlement above can say yes while the add-on that implements // FORMFORGE_Analytics is absent (a stale or not-yet-installed add-on). // Say so plainly rather than fataling the screen. if (!class_exists('FORMFORGE_Analytics')) { ?>
addon_missing_message()); ?>
get_stats($form->id, $days); $abandons = $abandons_by_form[(int) $form->id] ?? 0; $total_views += $stats['views']; $total_submits += $stats['submissions']; $total_abandons += $abandons; $rows[] = [ 'form' => $form, 'views' => $stats['views'], 'submissions' => $stats['submissions'], 'conversion_rate' => $stats['conversion_rate'], 'abandons' => $abandons, ]; } // BUG-FORM-STATS-01: records can outnumber views (imports, the owner's own tests), and a rate cannot pass 100; the per-form rate is capped the same way. $overall_conversion = $total_views > 0 ? min(100, round(($total_submits / $total_views) * 100, 1)) : 0; ?>
%
title); ?>
ID: id); ?>
%
addon_feature_on('submissions_ai')): ?>
prefix . 'formforge_forms'; $forms = $wpdb->get_results("SELECT id, settings FROM {$wpdb->prefix}formforge_forms"); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- admin read of the plugin's own table if (empty($forms)) return 0; $defaults = [ 'gsheets_enabled' => false, 'gsheets_spreadsheet_id' => '', 'gsheets_sheet_name' => 'Sheet1', 'gsheets_spreadsheet_title' => '', 'calendar_enabled' => false, 'calendar_id' => '', 'calendar_name' => '', 'calendar_event_title' => 'Booking: {name}', 'calendar_work_start' => '', 'calendar_work_end' => '', 'calendar_slot_duration' => '', ]; $updated = 0; foreach ($forms as $f) { $s = json_decode($f->settings, true); if (!is_array($s)) continue; $changed = false; foreach ($defaults as $k => $v) { if (!array_key_exists($k, $s)) continue; if ($s[$k] !== $v) { $s[$k] = $v; $changed = true; } } if ($changed) { $wpdb->update($table, ['settings' => wp_json_encode($s)], ['id' => (int) $f->id]); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- custom plugin table; direct query is intended. $updated++; } } return $updated; } }