*/ class Activetrail_Cf7_Admin { /** * The ID of this plugin. * * @since 1.0.0 * @access private * @var string $plugin_name The ID of this plugin. */ private $plugin_name; /** * The version of this plugin. * * @since 1.0.0 * @access private * @var string $version The current version of this plugin. */ private $version; private $meta_prefix = '_at_cf7_key_'; /** * Set while a CF7 form is being duplicated, so the newly-created form can * inherit the source form's ActiveTrail settings (stored in post meta). */ private $copy_source_id = null; private $at_cf7_metafields = array( 'activetrail' => array( 'token_id' => 'token_id', 'group_id' => 'group_id', 'mailing_list_id' => 'mailing_list_id', 'external_name' => 'external_name' ), 'form' => array( 'account_settings' => array( 'external_id' => 'external_id' ), 'required' => array( 'form_id' => 'form_id', 'email' => 'email', 'mobile' => 'sms' ), 'optional' => array( 'approve_checkbox' => 'approve_checkbox', // Mapped to a CF7 checkbox tag, exactly like approve_checkbox -- // each submitter's own checked/unchecked state (not a fixed // per-form value) determines what gets sent for THEIR contact. 'tracking_consent' => 'tracking_consent', 'subscription_status' => 'subscription_status' ), 'api' => array() ) ); private $at_api_error_stack = array(); /** * Initialize the class and set its properties. * * @since 1.0.0 * @param string $plugin_name The name of this plugin. * @param string $version The version of this plugin. */ public function __construct($plugin_name, $version) { $this->plugin_name = $plugin_name; $this->version = $version; } private function get_metakey($field) { return $this->meta_prefix . $field; } /** * Register the stylesheets for the admin area. * * @since 1.0.0 */ public function enqueue_styles() { wp_enqueue_style( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'css/activetrail-cf7-admin.css', array(), $this->asset_version('css/activetrail-cf7-admin.css'), 'all' ); } /** * Register the JavaScript for the admin area. * * @since 1.0.0 */ public function enqueue_scripts() { wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/activetrail-cf7-admin.js', array( 'jquery' ), $this->asset_version('js/activetrail-cf7-admin.js'), false ); wp_localize_script( $this->plugin_name, 'atCf7Admin', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'at_cf7_test_token' ), ) ); } /** * Cache-busting version for an admin asset, based on the file's own last-modified * time rather than the plugin version. The plugin version is a human-managed, * per-release number -- it isn't meant to bump on every small JS/CSS edit made * between releases, but that also means it can't be trusted to change the "?ver=" * query string WordPress appends to the enqueued file, so a browser (or any CDN/ * proxy in front of it) can go on serving a stale cached copy indefinitely even * after the file changes on disk. filemtime() changes on every edit, guaranteed. */ private function asset_version($relative_path) { $file = plugin_dir_path(__FILE__) . $relative_path; $mtime = file_exists($file) ? filemtime($file) : false; return $mtime ? (string) $mtime : $this->version; } public function at_cf7_editor_panels($panels) { if (!(current_user_can('administrator') || current_user_can('editor'))) { return $panels; } $panels['activetrail-cf7-panel'] = array( 'title' => 'ActiveTrail', 'callback' => array($this, 'at_cf7_callback_panel_init') ); return $panels; } public function at_cf7_save_form($cf7) { if (!(current_user_can('administrator') || current_user_can('editor'))) { return; } if (!isset($_POST['wpcf7-activetrail']) || !isset($_POST['wpcf7-activetrail-meta'])) { // Form duplication (and other programmatic saves) fire this hook without the // ActiveTrail panel payload. When we know this save is a duplication, copy the // source form's ActiveTrail settings onto the new form so it is not left blank. if ($this->copy_source_id && is_object($cf7) && method_exists($cf7, 'id')) { $this->at_cf7_copy_meta($this->copy_source_id, (int) $cf7->id()); $this->copy_source_id = null; } return; } $cf7_id = (int) $cf7->id(); //Both Required and Covered by above condition //$post_fields = $_POST['wpcf7-activetrail']; // $meta_post_fields = $_POST['wpcf7-activetrail-meta']; // Assign to varable: Check and Sanitization done below on a per element basis // (providing below conditions are met $post_fields_optional: is not null, is array and has elements in it //$post_fields_optional = isset($_POST['wpcf7-activetrail-optional']) ? $_POST['wpcf7-activetrail-optional'] : null; /*new code*/ $post_fields = array(); $meta_post_fields = array(); foreach ($this->at_cf7_metafields['activetrail'] as $key => $field) { if (isset($_POST['wpcf7-activetrail'][$field])) { $post_fields[$field] = sanitize_text_field($_POST['wpcf7-activetrail'][$field]); } // wp_nonce_field($field.'_metabox', 'wpcf7-activetrail-meta['. $field .'_metabox_nonce]'); if (isset($_POST['wpcf7-activetrail-meta'][$field . '_metabox_nonce'])) { $meta_post_fields[$field . '_metabox_nonce'] = sanitize_text_field($_POST['wpcf7-activetrail-meta'][$field . '_metabox_nonce']); } } //Add new external_id setting in account_settings foreach ($this->at_cf7_metafields['form']['account_settings'] as $key => $field) { if (isset($_POST['wpcf7-activetrail'][$field])) { $post_fields[$field] = sanitize_text_field($_POST['wpcf7-activetrail'][$field]); } // wp_nonce_field($field.'_metabox', 'wpcf7-activetrail-meta['. $field .'_metabox_nonce]'); if (isset($_POST['wpcf7-activetrail-meta'][$field . '_metabox_nonce'])) { $meta_post_fields[$field . '_metabox_nonce'] = sanitize_text_field($_POST['wpcf7-activetrail-meta'][$field . '_metabox_nonce']); } } foreach ($this->at_cf7_metafields['form']['required'] as $key => $field) { if (isset($_POST['wpcf7-activetrail'][$field])) { $post_fields[$field] = sanitize_text_field($_POST['wpcf7-activetrail'][$field]); } // wp_nonce_field($field.'_metabox', 'wpcf7-activetrail-meta['. $field .'_metabox_nonce]'); if (isset($_POST['wpcf7-activetrail-meta'][$field . '_metabox_nonce'])) { $meta_post_fields[$field . '_metabox_nonce'] = sanitize_text_field($_POST['wpcf7-activetrail-meta'][$field . '_metabox_nonce']); } } foreach ($this->at_cf7_metafields['form']['optional'] as $key => $field) { if (isset($_POST['wpcf7-activetrail'][$field])) { $post_fields[$field] = sanitize_text_field($_POST['wpcf7-activetrail'][$field]); } // wp_nonce_field($field.'_metabox', 'wpcf7-activetrail-meta['. $field .'_metabox_nonce]'); if (isset($_POST['wpcf7-activetrail-meta'][$field . '_metabox_nonce'])) { $meta_post_fields[$field . '_metabox_nonce'] = sanitize_text_field($_POST['wpcf7-activetrail-meta'][$field . '_metabox_nonce']); } } /* new code ends */ //Ensures that all required fields are received from the POST and set foreach ($this->at_cf7_metafields['activetrail'] as $key => $field) { if ($field === 'external_name') { continue; } if (!isset($post_fields[$field]) || !isset($meta_post_fields[$field.'_metabox_nonce'])) { wp_die('POST data violation'); } } foreach ($this->at_cf7_metafields['form']['account_settings'] as $key => $field) { if (!isset($post_fields[$field]) || !isset($meta_post_fields[$field.'_metabox_nonce'])) { wp_die('POST data violation'); } } //Ensures that all required meta fields are received from the POST and set foreach ($this->at_cf7_metafields['form']['required'] as $key => $field) { //Only one of the fields email or mobile is required.if one is missing but the other exits the post should be consider as valid if ($field === 'email' || $field === 'mobile') { if ( (!isset($post_fields['email']) || !isset($meta_post_fields['email_metabox_nonce'])) && (!isset($post_fields['mobile']) || !isset($meta_post_fields['mobile_metabox_nonce'])) ) { wp_die('POST data violation'); } } else { if (!isset($post_fields[$field]) || !isset($meta_post_fields[$field.'_metabox_nonce'])) { wp_die('POST data violation'); } } } $db_post_meta = get_post_meta($cf7_id); // Validate the token that was just SUBMITTED, not whatever is already stored. // Reading from $db_post_meta here checks the stale pre-save value, so entering a // bad token over a previously-valid one passed validation against the OLD token // and then silently overwrote it — the token was never actually re-checked. $app_token_id = isset($post_fields['token_id']) ? $post_fields['token_id'] : null; //Ensure that we have a API token and is set to some string: //(e.g. token: 0XE4EFE865BA48798BBB7595DT394310554DE2AC34FE9F61431F3A78C0FFB20FCFC71149DD23020FF7FD7C43A7BF212901) if (!isset($app_token_id) || preg_replace('/\s+/', '', $app_token_id) == '') { $this->at_api_error_stack[] = 'Invalid API Token'; } //Pull list of ActiveTrail fields from the API — a bad-but-non-empty token surfaces //here via the API's own error message (at_request_fields pushes it onto the stack). $this->at_request_fields($app_token_id); $existing_optional_settings = array(); foreach ($this->at_cf7_metafields['form']['api'] as $key => $field_data) { $field_name = strtolower($field_data['field_name']); $metakey = $this->get_metakey($field_name); if (array_key_exists($metakey, $db_post_meta)) { $existing_optional_settings[] = $field_name; } } if (isset($_POST['wpcf7-activetrail-optional']) && is_array($_POST['wpcf7-activetrail-optional']) && count($_POST['wpcf7-activetrail-optional']) > 0) { foreach ($_POST['wpcf7-activetrail-optional'] as $rfc4id => $data) { if (isset($data['src']) && isset($data['dst']) && (preg_replace('/\s+/', '', $data['src']) != '') && preg_replace('/\s+/', '', $data['dst']) != '') { //Sanitize Value $value = sanitize_text_field($data['src']); $key = $this->get_metakey(sanitize_text_field($data['dst'])); $action = 'replace'; //Make sure received action via POST is a VALID and one of 2 options if (array_key_exists('action', $data) && in_array(sanitize_text_field($data['action']), array('replace','merge'))) { $action = sanitize_text_field($data['action']); } //Update field with sanitized value + action: BOTH ARE CLEANED UP AND VALIDATED AT THIS POINT update_post_meta($cf7_id, $key, $value.'|'.$action); if (($key = array_search(sanitize_text_field($data['dst']), $existing_optional_settings)) !== false) { unset($existing_optional_settings[$key]); } } } } $existing_optional_settings = array_values($existing_optional_settings); //Delete the options that were in the database, but got removed with the interface prior to saving this form. if (count($existing_optional_settings) > 0) { foreach ($existing_optional_settings as $setting_key) { $meta_key = $this->get_metakey($setting_key); delete_post_meta($cf7_id, $meta_key); } } foreach ($post_fields as $field => $value) { $clean_value = null; // if (in_array($field, array('form_id', 'group_id'))) // form_id removed because CF7 now use alpha + number for Form ID if (in_array($field, array('group_id'))) { if (is_numeric((int) sanitize_text_field($value))) { $clean_value = (int) sanitize_text_field($value); } } else { $clean_value = sanitize_text_field($value); } if (in_array($field, $this->at_cf7_metafields['form']['optional']) || $clean_value || $field == 'mailing_list_id') { update_post_meta($cf7_id, $this->get_metakey(sanitize_text_field($field)), $clean_value); } } // The Group/Mailing List lookup dropdowns submit the chosen display name // alongside the id (in a separate hidden field, never the free-text search // box itself, so an unsubmitted in-progress search never overwrites this). // Without persisting it, reopening the panel had nothing to show in the // search box but the raw numeric id -- easy to misread as "the selection // disappeared" even though the id itself saved correctly. foreach (array('group_name', 'mailing_list_name') as $name_field) { $submitted_name = isset($_POST['wpcf7-activetrail'][$name_field]) ? sanitize_text_field($_POST['wpcf7-activetrail'][$name_field]) : ''; if ($submitted_name !== '') { update_post_meta($cf7_id, $this->get_metakey($name_field), $submitted_name); } else { delete_post_meta($cf7_id, $this->get_metakey($name_field)); } } // Surface configuration problems instead of saving silently. The API token was // already validated above (at_request_fields pushes the API's error message onto // the stack, and an empty token is flagged too); here we also catch malformed IDs. $submitted_group = isset($_POST['wpcf7-activetrail']['group_id']) ? sanitize_text_field($_POST['wpcf7-activetrail']['group_id']) : ''; if (preg_replace('/\s+/', '', $submitted_group) !== '' && (int) $submitted_group <= 0) { $this->at_api_error_stack[] = 'Invalid Group ID - it must be a positive number, so the value was not saved.'; } $submitted_list = isset($_POST['wpcf7-activetrail']['mailing_list_id']) ? sanitize_text_field($_POST['wpcf7-activetrail']['mailing_list_id']) : ''; if (preg_replace('/\s+/', '', $submitted_list) !== '' && (int) $submitted_list <= 0) { $this->at_api_error_stack[] = 'Invalid Mailing List ID - it must be a positive number, so the value was not saved.'; } if (!empty($this->at_api_error_stack)) { set_transient('at_cf7_notices_' . get_current_user_id(), array_values(array_unique($this->at_api_error_stack)), 60); } } public function at_cf7_callback_panel_init($post) { if (!(current_user_can('administrator') || current_user_can('editor'))) { wp_die(''); } $settings_values = array(); $optional_settings_values = array(); $db_post_meta = get_post_meta($post->id()); if (!is_array($db_post_meta)) { $db_post_meta = array(); } $app_token_id = null; if (array_key_exists($this->get_metakey('token_id'), $db_post_meta)) { $app_token_id = $db_post_meta[$this->get_metakey('token_id')][0]; } // An empty token means "not configured yet" -- that's the normal state for a // brand-new form, not an error, so only run (and only report a failure from) // the check when a token is actually present. if (preg_replace('/\s+/', '', $app_token_id) != '') { $this->at_request_fields($app_token_id); } // Whether the panel should render already "connected" (the rest of the fields // visible) or gated behind the Connect button — a token that's saved and still // validates successfully is treated as already connected. $token_is_valid = (preg_replace('/\s+/', '', $app_token_id) != '') && empty($this->at_api_error_stack); foreach ($this->at_cf7_metafields['activetrail'] as $key => $field) { wp_nonce_field($field.'_metabox', 'wpcf7-activetrail-meta['. $field .'_metabox_nonce]'); $metakey = $this->get_metakey($field); if (array_key_exists($metakey, $db_post_meta)) { $settings_values[$field] = $db_post_meta[$metakey][0]; } } foreach ($this->at_cf7_metafields['form']['account_settings'] as $key => $field) { wp_nonce_field($field.'_metabox', 'wpcf7-activetrail-meta['. $field .'_metabox_nonce]'); $metakey = $this->get_metakey($field); if (array_key_exists($metakey, $db_post_meta)) { $settings_values[$field] = $db_post_meta[$metakey][0]; } } foreach ($this->at_cf7_metafields['form']['required'] as $key => $field) { wp_nonce_field($field.'_metabox', 'wpcf7-activetrail-meta['. $field .'_metabox_nonce]'); $metakey = $this->get_metakey($field); if (array_key_exists($metakey, $db_post_meta)) { $settings_values[$field] = $db_post_meta[$metakey][0]; } } foreach ($this->at_cf7_metafields['form']['optional'] as $key => $field) { wp_nonce_field($field.'_metabox', 'wpcf7-activetrail-meta['. $field .'_metabox_nonce]'); $metakey = $this->get_metakey($field); if (array_key_exists($metakey, $db_post_meta)) { $settings_values[$field] = $db_post_meta[$metakey][0]; } } // Display names saved alongside the Group/Mailing List lookup selections. foreach (array('group_name', 'mailing_list_name') as $name_field) { $metakey = $this->get_metakey($name_field); if (array_key_exists($metakey, $db_post_meta)) { $settings_values[$name_field] = $db_post_meta[$metakey][0]; } } foreach ($this->at_cf7_metafields['form']['api'] as $key => $field_data) { $field_name = strtolower($field_data['field_name']); $metakey = $this->get_metakey($field_name); if (array_key_exists($metakey, $db_post_meta)) { $optional_settings_values[$field_name] = $db_post_meta[$metakey][0]; } } $plugin_url = plugins_url('', __FILE__); $error_stack = $this->at_api_error_stack; include_once('partials/activetrail-cfs-admin-display.php'); } public function at_cf7_post_form($cf7_form) { $cf7_id = (int) $cf7_form->id(); $db_post_meta = get_post_meta($cf7_id); $app_token_id = null; if (array_key_exists($this->get_metakey('token_id'), $db_post_meta)) { $app_token_id = $db_post_meta[$this->get_metakey('token_id')][0]; } $mailing_list_id = null; if (array_key_exists($this->get_metakey('token_id'), $db_post_meta)) { $mailing_list_id = $db_post_meta[$this->get_metakey('mailing_list_id')][0]; } if (preg_replace('/\s+/', '', $app_token_id) == '') { $this->at_api_error_stack[] = 'Invalid API Token'; } $this->at_request_fields($app_token_id); $cf7_meta = null; if (array_key_exists($this->get_metakey($this->at_cf7_metafields['form']['optional']['approve_checkbox']), $db_post_meta)) { $cf7_meta = $db_post_meta[$this->get_metakey($this->at_cf7_metafields['form']['optional']['approve_checkbox'])]; } $email_metakey = $this->get_metakey($this->at_cf7_metafields['form']['required']['email']); $email_tag = null; if (array_key_exists($email_metakey, $db_post_meta)) { $email_tag = $db_post_meta[$email_metakey][0]; } $lead_email = null; if (array_key_exists($email_tag, $_POST) && isset($_POST[$email_tag]) && !empty($_POST[$email_tag])) { $lead_email = trim($_POST[$email_tag]); $lead_email = sanitize_email($lead_email); } if (!is_email($lead_email)) { $this->at_api_error_stack[] = 'Invalid Email Address'; } $api_optional = array(); foreach ($this->at_cf7_metafields['form']['api'] as $key => $field_data) { $field_name = strtolower($field_data['field_name']); $metakey = $this->get_metakey($field_name); // The import payload keys each value by the field's source column // ("ext1", "first_name", "zip_code", "num1", ...), NOT by its display-oriented // field_name. Keying by field_name produced keys like "custom field 1" that the // API rejects, which caused the whole contact to fail to import. field_source_column // already gives the canonical key, so it replaces the old hardcoded remaps. $payload_key = strtolower($field_data['field_source_column']); if (array_key_exists($metakey, $db_post_meta)) { $parts = explode('|', $db_post_meta[$metakey][0]); if (array_key_exists($parts[0], $_POST)) { $action = isset($parts[1]) ? sanitize_text_field($parts[1]) : 'replace'; $existing_value = ''; if ($action == 'merge') { $at_contact = $this->at_request_contact($app_token_id, $lead_email); if (is_array($at_contact) && array_key_exists($payload_key, $at_contact)) { $existing_value = sanitize_text_field($at_contact[$payload_key]); } } $value = ''; if (array_key_exists($parts[0], $_POST) && isset($_POST[$parts[0]])) { $clean_value = sanitize_text_field($_POST[$parts[0]]); $value = $existing_value != '' ? trim($existing_value . ',' . $clean_value) : $clean_value; } $api_optional[$payload_key] = sanitize_text_field($value); } } } if ($cf7_meta) { $chckbox_id = $cf7_meta[0]; if (!empty($chckbox_id) && (!array_key_exists($chckbox_id, $_POST) || $cf7_id != $_POST['_wpcf7'])) { return; } } $optional = array(); $sms_metakey = $this->get_metakey($this->at_cf7_metafields['form']['required']['mobile']); $sms_key = null; $mobile_data = null; if (array_key_exists($sms_metakey, $db_post_meta)) { $sms_key = $db_post_meta[$sms_metakey][0]; } if (array_key_exists($sms_key, $_POST) && isset($_POST[$sms_key])) { $sms = trim($_POST[$db_post_meta[$this->get_metakey($this->at_cf7_metafields['form']['required']['mobile'])][0]]); if ($sms && !empty($sms)) { $mobile_data = sanitize_text_field($sms); // Preserve an international dialing prefix. A leading "+" or "00" means the // number already carries its own country code, so we keep it in E.164 form // ("+"). Stripping it — as the old digits-only rule did — // made ActiveTrail treat a foreign number as a local Israeli one and prepend // +972. Local numbers (no prefix) are still sent as digits only. if (strpos($mobile_data, '+') === 0) { $mobile_data = '+' . preg_replace('/[^0-9]/', '', $mobile_data); } elseif (strpos($mobile_data, '00') === 0) { $mobile_data = '+' . preg_replace('/[^0-9]/', '', substr($mobile_data, 2)); } else { $mobile_data = preg_replace('/[^0-9]/', '', $mobile_data); } } if (!is_numeric($mobile_data)) { $this->at_api_error_stack[] = 'Invalid phone number'; } } $group_id_metakey = $this->get_metakey($this->at_cf7_metafields['activetrail']['group_id']); $group_id = null; if (array_key_exists($group_id_metakey, $db_post_meta)) { $group_id = $db_post_meta[$group_id_metakey][0]; } $mailing_list_id_metakey = $this->get_metakey($this->at_cf7_metafields['activetrail']['mailing_list_id']); $mailing_list_id = null; if (array_key_exists($mailing_list_id_metakey, $db_post_meta)) { $mailing_list_id = $db_post_meta[$mailing_list_id_metakey][0]; } $external_id_metakey = $this->get_metakey($this->at_cf7_metafields['form']['account_settings']['external_id']); $external_id_key = null; $external_id = null; if (array_key_exists($external_id_metakey, $db_post_meta)) { $external_id_key = $db_post_meta[$external_id_metakey][0]; } if (array_key_exists($external_id_key, $_POST) && isset($_POST[$external_id_key]) && !empty($_POST[$external_id_key])) { $external_id_key = trim($_POST[$external_id_key]); $external_id_key = sanitize_text_field($external_id_key); } if ($external_id_key === 'external') { if ($lead_email && $mobile_data) { $external_id = $this->format_email_external_id($lead_email) . $this->format_mobile_external_id($mobile_data); } elseif ($lead_email) { $external_id = $this->format_email_external_id($lead_email); } elseif ($mobile_data) { $external_id = $this->format_mobile_external_id($mobile_data); } else { $this->at_api_error_stack[] = 'Email or Mobile is required, you will need to fill at least one of them'; } } else { $external_id = $external_id_key; } $external_name_metakey = $this->get_metakey($this->at_cf7_metafields['activetrail']['external_name']); $external_name = null; if (array_key_exists($external_name_metakey, $db_post_meta)) { $external_name = $db_post_meta[$external_name_metakey][0]; } // Tracking Consent and Subscription Status are mapped to a CF7 checkbox tag // (same idea as Approve Checkbox above), not a fixed value chosen once for the // whole form -- each submitter's own checked/unchecked state on THIS submission // determines what's sent for THEIR contact. Unmapped (blank) means omitted // entirely. $tracking_consent_tag = null; if (array_key_exists($this->get_metakey('tracking_consent'), $db_post_meta)) { $tracking_consent_tag = $db_post_meta[$this->get_metakey('tracking_consent')][0]; } $tracking_consent = null; if (!empty($tracking_consent_tag)) { $tracking_consent = array_key_exists($tracking_consent_tag, $_POST) ? 'Approved' : 'Blocked'; } $subscription_status_tag = null; if (array_key_exists($this->get_metakey('subscription_status'), $db_post_meta)) { $subscription_status_tag = $db_post_meta[$this->get_metakey('subscription_status')][0]; } $subscription_status = null; if (!empty($subscription_status_tag)) { $subscription_status = array_key_exists($subscription_status_tag, $_POST) ? 'subscribed' : 'unsubscribed'; } $basic_fields = array( 'email' => $lead_email, 'sms' => $mobile_data ); $combined = array_merge($basic_fields, $optional, $api_optional); $combined['is_do_not_mail'] = false; $combined['is_deleted'] = false; //tracking_consent applies to both regular and external imports (inside the contact object) if ($tracking_consent) { $combined['tracking_consent'] = sanitize_text_field($tracking_consent); } $data = array( //'mailing_list' => $list_id, 'group' => $group_id, ); if (isset($mailing_list_id) && $mailing_list_id) { $data['mailing_list'] = $mailing_list_id; } if ($external_id_key === 'external') { //subscriptionStatus is a boolean, supported on the external import only (inside the //contact object): true = subscribed, false = unsubscribed. Omitted when unmapped //so the account default is preserved. if ($subscription_status === 'subscribed') { $combined['subscriptionStatus'] = true; } elseif ($subscription_status === 'unsubscribed') { $combined['subscriptionStatus'] = false; } $contact =['contact' => $combined, 'externalId' => $external_id]; if (isset($external_name) && $external_name) { $contact['externalName'] = $external_name; } $contact = array( (object) $contact ); } else { $contact = array($combined); } $data['contacts'] = $contact; $activetrail_api = new Activetrail_Api(array('app_token_id' => $app_token_id)); if ($external_id_key === 'external') { $res_json = $activetrail_api->import_contacts_external($data); } else { $res_json = $activetrail_api->import_contacts($data); } return $res_json; } private function at_request_fields($app_token_id) { $activetrail_api = new Activetrail_Api(array('app_token_id' => $app_token_id)); $res_json = $activetrail_api->get_contact_fields(); $code = $activetrail_api->last_response_code; $unfiltered = null; if (!empty($res_json)) { $unfiltered = json_decode($res_json, true); } $filtered = array(); // A bad/expired token can come back as a non-2xx response with an empty or // non-JSON body (e.g. a blank 401), which json_decode turns into null — that // used to be silently treated as "zero custom fields" instead of an error. // The HTTP status code is the reliable signal; a 'Message' body is a bonus. $failed = ($code !== null && ($code < 200 || $code >= 300)) || !is_array($unfiltered); if ($failed || array_key_exists('Message', $unfiltered)) { // This call only ever exists to verify the token / fetch fields with it, so // any failure here means "the token doesn't work." Show a short, consistent // message instead of ActiveTrail's verbose raw API text (this feeds the // top-of-panel banner, the Connect button, and the save-time notice alike). $this->at_api_error_stack[] = 'Invalid API key.'; } else { foreach ($unfiltered as $key => $field_data) { if (!in_array(strtolower($field_data['field_source_column']), array('sms'))) { $filtered[] = $field_data; } } } $this->at_cf7_metafields['form']['api'] = $filtered; } private function at_request_contact($app_token_id, $email) { $activetrail_api = new Activetrail_Api(array('app_token_id' => $app_token_id)); $res_json = $activetrail_api->get_contact(array('SearchTerm' => $email)); if (!empty($res_json)) { $response = json_decode($res_json, true); } if (array_key_exists('Message', $response)) { return false; } else if (isset($response[0])) { return $response[0]; } //return false or return response?? } private function format_email_external_id($email) { return $email ? str_replace(['@', '.'], '', $email) : ''; } private function format_mobile_external_id($mobile_data) { return $mobile_data ? str_replace('+', '', $mobile_data) : ''; } /** * Runs on the `wpcf7_copy` filter when a form is duplicated. CF7 copies the * form's own properties but not our post meta, so we remember the source form * id here; the meta is copied onto the new form in at_cf7_save_form(), which * fires (via wpcf7_after_save) once the duplicate has an id. */ public function at_cf7_copy_form($new_cf7, $source_cf7) { if (is_object($source_cf7) && method_exists($source_cf7, 'id')) { $this->copy_source_id = (int) $source_cf7->id(); } return $new_cf7; } /** * Copy every ActiveTrail setting (our `_at_cf7_key_*` post meta, including the * dynamic custom-field mappings) from one form to another. */ private function at_cf7_copy_meta($source_id, $dest_id) { if (!$source_id || !$dest_id || $source_id === $dest_id) { return; } $source_meta = get_post_meta($source_id); if (!is_array($source_meta)) { return; } foreach ($source_meta as $meta_key => $values) { if (strpos($meta_key, $this->meta_prefix) !== 0) { continue; } delete_post_meta($dest_id, $meta_key); foreach ($values as $value) { add_post_meta($dest_id, $meta_key, maybe_unserialize($value)); } } } /** * Show any configuration warnings collected during the last save (invalid API * token, bad Group/List ID) instead of failing silently. */ public function at_cf7_admin_notices() { $key = 'at_cf7_notices_' . get_current_user_id(); $notices = get_transient($key); if (empty($notices) || !is_array($notices)) { return; } delete_transient($key); foreach ($notices as $notice) { echo '

ActiveTrail: ' . esc_html($notice) . '

'; } } /** * AJAX: test whether a given API token authenticates with ActiveTrail. * * CF7 saves the form editor over AJAX/REST without reloading the page, so a * PHP-rendered notice set at save time may not be visible until the next full * pageload. This endpoint is called directly from the browser (on blur and on * Save) so an invalid token is reported inline immediately. It delegates to * at_request_fields() — the same check used at panel-load and save-time — so * all three surfaces agree on what counts as a valid token. */ public function at_cf7_ajax_test_token() { if (!(current_user_can('administrator') || current_user_can('editor'))) { wp_send_json_error(array('message' => 'Permission denied.'), 403); } check_ajax_referer('at_cf7_test_token', 'nonce'); $token = isset($_POST['token_id']) ? sanitize_text_field(wp_unslash($_POST['token_id'])) : ''; if (preg_replace('/\s+/', '', $token) === '') { wp_send_json_error(array('message' => 'Enter an API token.')); } $this->at_api_error_stack = array(); $this->at_request_fields($token); if (!empty($this->at_api_error_stack)) { wp_send_json_error(array('message' => implode(' ', $this->at_api_error_stack))); } // Also return the Custom Fields list fetched as a side effect of the check // above, so the browser can populate that section from THIS live result // instead of only from whatever was already saved (a brand-new form has // nothing saved yet, so it would otherwise still show as "not configured" // right after a successful Connect). $fields = array(); foreach ($this->at_cf7_metafields['form']['api'] as $field_data) { $fields[] = array( 'value' => strtolower($field_data['field_name']), 'label' => $field_data['field_display_name'], ); } wp_send_json_success(array('message' => 'Token is valid.', 'fields' => $fields)); } /** * AJAX: search ActiveTrail Groups by name, paged. Backs the "Group" lookup * dropdown so the customer picks a group by name; the numeric id (what the * import API actually needs) is what gets stored. */ public function at_cf7_ajax_get_groups() { $this->at_cf7_ajax_list_lookup('groups'); } /** * AJAX: search ActiveTrail Mailing Lists by name, paged. Same shape as * at_cf7_ajax_get_groups(), for the "Mailing List" lookup dropdown. */ public function at_cf7_ajax_get_mailing_lists() { $this->at_cf7_ajax_list_lookup('mailing_lists'); } private function at_cf7_ajax_list_lookup($type) { if (!(current_user_can('administrator') || current_user_can('editor'))) { wp_send_json_error(array('message' => 'Permission denied.'), 403); } check_ajax_referer('at_cf7_test_token', 'nonce'); $token = isset($_POST['token_id']) ? sanitize_text_field(wp_unslash($_POST['token_id'])) : ''; $search = isset($_POST['search']) ? sanitize_text_field(wp_unslash($_POST['search'])) : ''; $page = isset($_POST['page']) ? max(1, (int) $_POST['page']) : 1; $limit = 20; if (preg_replace('/\s+/', '', $token) === '') { wp_send_json_error(array('message' => 'Invalid API key.')); } $activetrail_api = new Activetrail_Api(array('app_token_id' => $token)); $res_json = ($type === 'groups') ? $activetrail_api->get_groups($search, $page, $limit) : $activetrail_api->get_mailing_lists($search, $page, $limit); $code = $activetrail_api->last_response_code; $decoded = !empty($res_json) ? json_decode($res_json, true) : null; if (($code !== null && ($code < 200 || $code >= 300)) || !is_array($decoded)) { wp_send_json_error(array('message' => 'Invalid API key.')); } // The exact response shape hasn't been confirmed against a live account yet, so // this tolerates a few likely variants: a bare array, or a wrapper object with // the list under "Items"/"items"/"Results"/"results", and a few common casings // for the id/name field names. $items = $decoded; foreach (array('Items', 'items', 'Results', 'results') as $wrapper_key) { if (isset($decoded[$wrapper_key]) && is_array($decoded[$wrapper_key])) { $items = $decoded[$wrapper_key]; break; } } $items = is_array($items) ? $items : array(); $results = array(); foreach ($items as $item) { if (!is_array($item)) { continue; } $id = null; foreach (array('Id', 'id', 'ID', 'GroupId', 'group_id', 'MailingListId', 'mailing_list_id') as $id_key) { if (isset($item[$id_key]) && $item[$id_key] !== '') { $id = $item[$id_key]; break; } } $name = null; foreach (array('Name', 'name', 'GroupName', 'group_name', 'Title', 'title') as $name_key) { if (isset($item[$name_key]) && $item[$name_key] !== '') { $name = $item[$name_key]; break; } } if ($id !== null && $name !== null) { $results[] = array('id' => $id, 'name' => sanitize_text_field($name)); } } $has_more = count($items) >= $limit; foreach (array('TotalCount', 'Total', 'totalCount', 'total') as $total_key) { if (isset($decoded[$total_key]) && is_numeric($decoded[$total_key])) { $has_more = ($page * $limit) < (int) $decoded[$total_key]; break; } } wp_send_json_success(array('results' => $results, 'page' => $page, 'hasMore' => $has_more)); } }