plugin = $plugin; } /** Register only while the feature is enabled. */ public function register() { if ( ! $this->plugin->is_power_enabled( 'mailchimp_tags' ) ) { return; } add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_frontend_script' ), 35 ); add_action( 'wp_enqueue_scripts', array( $this, 'print_builder_config' ), 5 ); add_action( 'admin_enqueue_scripts', array( $this, 'print_builder_config' ), 5 ); add_action( 'wp_ajax_' . self::DIVI_SUBSCRIBE_ACTION, array( $this, 'capture_native_submission' ), 1 ); add_action( 'wp_ajax_nopriv_' . self::DIVI_SUBSCRIBE_ACTION, array( $this, 'capture_native_submission' ), 1 ); } /** Add the tiny request bridge that preserves Divi's normal submission flow. */ public function enqueue_frontend_script() { if ( is_admin() || ( function_exists( 'et_core_is_fb_enabled' ) && et_core_is_fb_enabled() ) ) { return; } wp_enqueue_script( 'divi-powers-mailchimp-tags', DIVI_POWERS_URL . 'assets/js/mailchimp-tags.js', array( 'jquery', 'wp-i18n' ), DIVI_POWERS_VERSION, array( 'in_footer' => true, 'strategy' => 'defer', ) ); wp_set_script_translations( 'divi-powers-mailchimp-tags', '5d-powers-for-divi' ); } /** * Give the Divi 5 builder a credential-free map of connected Mailchimp * audiences and the currently available tags in each audience. */ public function print_builder_config() { if ( ! current_user_can( 'edit_theme_options' ) || ! function_exists( 'et_core_is_fb_enabled' ) || ! et_core_is_fb_enabled() ) { return; } $config = array( 'audiences' => self::builder_audience_catalog() ); wp_register_script( 'fivedp-mailchimp-config', false, array(), DIVI_POWERS_VERSION, false ); wp_enqueue_script( 'fivedp-mailchimp-config' ); wp_add_inline_script( 'fivedp-mailchimp-config', 'window.DiviPowersMailchimpTagsConfig=' . wp_json_encode( $config, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ) . ';' ); } /** * Return all connected Mailchimp audiences and their tags for builder UI. * No API credentials are included in the returned data. * * @return array> */ public static function builder_audience_catalog() { $options = get_option( 'et_core_api_email_options', array() ); $accounts = is_array( $options['accounts']['mailchimp'] ?? null ) ? $options['accounts']['mailchimp'] : array(); $catalog = array(); foreach ( $accounts as $account_name => $account ) { $lists = is_array( $account['lists'] ?? null ) ? $account['lists'] : array(); foreach ( $lists as $list_id => $list ) { $account_name = sanitize_text_field( (string) $account_name ); $list_id = sanitize_text_field( (string) $list_id ); if ( '' === $account_name || '' === $list_id ) { continue; } $tags = self::available_tags( $account_name, $list_id ); $catalog[ $account_name . '|' . $list_id ] = array( 'account' => $account_name, 'listId' => $list_id, 'listName' => sanitize_text_field( (string) ( $list['name'] ?? $list_id ) ), 'tags' => array_map( static function ( $tag ) { return array( 'id' => (string) ( $tag['id'] ?? '' ), 'name' => (string) ( $tag['name'] ?? '' ), ); }, $tags ), ); } } return $catalog; } /** * Fetch all saved tags for a connected Mailchimp audience, with caching. * * @return array */ public static function available_tags( $account, $list_id ) { $credentials = self::mailchimp_credentials( $account, $list_id ); if ( empty( $credentials ) ) { return array(); } $cache_key = 'divi_powers_mc_tags_' . md5( $account . '|' . $list_id . '|' . $credentials['api_key'] ); $cached = get_transient( $cache_key ); if ( is_array( $cached ) ) { return $cached; } $tags = array(); $offset = 0; $total = 1; do { $url = add_query_arg( array( 'count' => 1000, 'offset' => $offset, ), sprintf( 'https://%1$s.api.mailchimp.com/3.0/lists/%2$s/tag-search', rawurlencode( $credentials['dc'] ), rawurlencode( $list_id ) ) ); $response = wp_remote_get( $url, array( 'timeout' => 8, 'redirection' => 0, 'limit_response_size' => self::MAX_API_RESPONSE_BYTES, 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( 'divi-powers:' . $credentials['api_key'] ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode ), ) ); if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { break; } $body = json_decode( wp_remote_retrieve_body( $response ), true ); $rows = is_array( $body['tags'] ?? null ) ? $body['tags'] : array(); foreach ( $rows as $row ) { $id = isset( $row['id'] ) ? sanitize_text_field( (string) $row['id'] ) : ''; $name = isset( $row['name'] ) ? sanitize_text_field( (string) $row['name'] ) : ''; if ( '' === $name ) { continue; } $tags[ strtolower( $name ) ] = array( 'id' => $id, 'name' => $name ); } $total = isset( $body['total_items'] ) ? absint( $body['total_items'] ) : count( $rows ); $offset += 1000; } while ( $offset < $total && $offset < 5000 ); $tags = array_values( $tags ); usort( $tags, static function ( $a, $b ) { return strcasecmp( (string) $a['name'], (string) $b['name'] ); } ); set_transient( $cache_key, $tags, self::TAG_CACHE_TTL ); return $tags; } /** * Keep dropdown selections restricted to tags that actually exist in the * module's currently selected audience. Manual fallback entries remain * separate and may intentionally create a new Mailchimp tag. */ public static function filter_existing_tag_names( $account, $list_id, $tags ) { $tags = self::normalize_tag_tokens( $tags ); if ( empty( $tags ) ) { return array(); } $available = self::available_tags( $account, $list_id ); $names = array(); foreach ( $available as $tag ) { $name = sanitize_text_field( (string) ( $tag['name'] ?? '' ) ); if ( '' !== $name ) { $names[ strtolower( $name ) ] = $name; } } $valid = array(); foreach ( $tags as $tag ) { $key = strtolower( $tag ); if ( isset( $names[ $key ] ) ) { $valid[ $key ] = $names[ $key ]; } } return array_values( $valid ); } /** * Capture signed tag metadata before Divi handles the native subscription. * Existing Mailchimp members are updated here so Divi's duplicate-member * limitation does not block the form. Their subscription status is preserved. * New contacts continue through Divi's native handler and receive their tags * during shutdown. */ public function capture_native_submission() { $frontend_nonce = isset( $_POST['et_frontend_nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['et_frontend_nonce'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing if ( '' === $frontend_nonce || ! wp_verify_nonce( $frontend_nonce, 'et_frontend_nonce' ) ) { return; } $account = isset( $_POST['divi_powers_mailchimp_account'] ) ? sanitize_text_field( wp_unslash( $_POST['divi_powers_mailchimp_account'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing $list_id = isset( $_POST['divi_powers_mailchimp_list'] ) ? sanitize_text_field( wp_unslash( $_POST['divi_powers_mailchimp_list'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing $signature = isset( $_POST['divi_powers_mailchimp_signature'] ) ? sanitize_text_field( wp_unslash( $_POST['divi_powers_mailchimp_signature'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing $raw_tags = isset( $_POST['divi_powers_mailchimp_tags'] ) ? wp_unslash( $_POST['divi_powers_mailchimp_tags'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- normalize_tag_tokens() sanitizes and bounds every tag before the signed configuration is verified. $email = isset( $_POST['et_email'] ) ? sanitize_email( wp_unslash( $_POST['et_email'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing $tags = self::normalize_tag_tokens( $raw_tags ); if ( '' === $account || '' === $list_id || '' === $signature || ! is_email( $email ) || empty( $tags ) ) { return; } if ( ! self::is_mailchimp_account( $account, $list_id ) || ! hash_equals( self::sign_config( $account, $list_id, $tags ), $signature ) ) { return; } // If Divi supplies provider/account/list values, require them to agree with // the signed module configuration. This retains compatibility with builds // that omit one or more of these legacy AJAX fields. if ( isset( $_POST['et_provider'] ) && 'mailchimp' !== sanitize_key( wp_unslash( $_POST['et_provider'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing return; } if ( isset( $_POST['et_account'] ) && $account !== sanitize_text_field( wp_unslash( $_POST['et_account'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing return; } if ( isset( $_POST['et_list_id'] ) && $list_id !== sanitize_text_field( wp_unslash( $_POST['et_list_id'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing return; } $credentials = self::mailchimp_credentials( $account, $list_id ); $member = $this->get_member( $credentials, $list_id, $email ); if ( is_wp_error( $member ) ) { wp_send_json_error( array( 'error' => $member->get_error_message() ) ); } if ( null === $member ) { register_shutdown_function( array( $this, 'apply_tags' ), $account, $list_id, $email, $tags ); return; } $profile_result = $this->update_existing_member_profile( $credentials, $list_id, $email, $member ); if ( is_wp_error( $profile_result ) ) { do_action( 'divi_powers_mailchimp_existing_member_profile_failed', $profile_result, $account, $list_id, $email ); } $tag_result = $this->apply_tags( $account, $list_id, $email, $tags ); if ( is_wp_error( $tag_result ) ) { wp_send_json_error( array( 'error' => $tag_result->get_error_message() ) ); } $member_status = sanitize_key( (string) ( $member['status'] ?? '' ) ); do_action( 'divi_powers_mailchimp_existing_member_updated', $account, $list_id, $email, $tags, $member_status ); wp_send_json_success( array( 'divi_powers_mailchimp' => 'existing_member_tagged', 'member_status' => $member_status, ) ); } /** * Apply tags to a Mailchimp member without changing Divi's response. * * @return true|WP_Error */ public function apply_tags( $account, $list_id, $email, $tokens ) { $credentials = self::mailchimp_credentials( $account, $list_id ); if ( empty( $credentials ) ) { return new WP_Error( 'divi_powers_mailchimp_credentials', __( 'The connected Mailchimp account could not be verified.', '5d-powers-for-divi' ) ); } $tag_names = $this->resolve_tag_names( $credentials['api_key'], $credentials['dc'], $list_id, $tokens ); if ( empty( $tag_names ) ) { return new WP_Error( 'divi_powers_mailchimp_tags', __( 'The selected Mailchimp tags could not be resolved.', '5d-powers-for-divi' ) ); } $subscriber_hash = md5( strtolower( trim( $email ) ) ); $url = sprintf( 'https://%1$s.api.mailchimp.com/3.0/lists/%2$s/members/%3$s/tags', rawurlencode( $credentials['dc'] ), rawurlencode( $list_id ), rawurlencode( $subscriber_hash ) ); $payload = array(); foreach ( $tag_names as $name ) { $payload[] = array( 'name' => $name, 'status' => 'active', ); } $response = wp_remote_post( $url, array( 'timeout' => 8, 'redirection' => 0, 'limit_response_size' => self::MAX_API_RESPONSE_BYTES, 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( 'divi-powers:' . $credentials['api_key'] ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( array( 'tags' => $payload ) ), ) ); if ( is_wp_error( $response ) ) { do_action( 'divi_powers_mailchimp_tags_failed', $response, $account, $list_id, $email, $tag_names ); return $response; } $status = (int) wp_remote_retrieve_response_code( $response ); if ( $status >= 200 && $status < 300 ) { do_action( 'divi_powers_mailchimp_tags_applied', $account, $list_id, $email, $tag_names ); return true; } $error = new WP_Error( 'divi_powers_mailchimp_tags', __( 'Mailchimp could not apply the selected tags. Please try again.', '5d-powers-for-divi' ) ); do_action( 'divi_powers_mailchimp_tags_failed', $error, $account, $list_id, $email, $tag_names ); return $error; } /** Return an existing Mailchimp member, null when absent, or an API error. */ private function get_member( $credentials, $list_id, $email ) { $subscriber_hash = md5( strtolower( trim( $email ) ) ); $url = add_query_arg( 'fields', 'status,merge_fields', sprintf( 'https://%1$s.api.mailchimp.com/3.0/lists/%2$s/members/%3$s', rawurlencode( $credentials['dc'] ), rawurlencode( $list_id ), rawurlencode( $subscriber_hash ) ) ); $response = wp_remote_get( $url, array( 'timeout' => 8, 'redirection' => 0, 'limit_response_size' => self::MAX_API_RESPONSE_BYTES, 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( 'divi-powers:' . $credentials['api_key'] ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode ), ) ); if ( is_wp_error( $response ) ) { return $response; } $status = (int) wp_remote_retrieve_response_code( $response ); if ( 404 === $status ) { return null; } if ( 200 !== $status ) { return new WP_Error( 'divi_powers_mailchimp_member_lookup', __( 'Mailchimp could not verify this subscriber.', '5d-powers-for-divi' ) ); } $member = json_decode( wp_remote_retrieve_body( $response ), true ); if ( ! is_array( $member ) ) { return new WP_Error( 'divi_powers_mailchimp_member_lookup', __( 'Mailchimp returned an invalid subscriber response.', '5d-powers-for-divi' ) ); } return $member; } /** Refresh standard name fields for an existing subscriber when available. */ private function update_existing_member_profile( $credentials, $list_id, $email, $member ) { $current_merge_fields = is_array( $member['merge_fields'] ?? null ) ? $member['merge_fields'] : array(); $first_name = isset( $_POST['et_firstname'] ) ? sanitize_text_field( wp_unslash( $_POST['et_firstname'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing $last_name = isset( $_POST['et_lastname'] ) ? sanitize_text_field( wp_unslash( $_POST['et_lastname'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing $merge_fields = array(); if ( '' !== $first_name && array_key_exists( 'FNAME', $current_merge_fields ) ) { $merge_fields['FNAME'] = $first_name; } if ( '' !== $last_name && array_key_exists( 'LNAME', $current_merge_fields ) ) { $merge_fields['LNAME'] = $last_name; } if ( empty( $merge_fields ) ) { return true; } $subscriber_hash = md5( strtolower( trim( $email ) ) ); $url = sprintf( 'https://%1$s.api.mailchimp.com/3.0/lists/%2$s/members/%3$s', rawurlencode( $credentials['dc'] ), rawurlencode( $list_id ), rawurlencode( $subscriber_hash ) ); $response = wp_remote_request( $url, array( 'method' => 'PATCH', 'timeout' => 8, 'redirection' => 0, 'limit_response_size' => self::MAX_API_RESPONSE_BYTES, 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( 'divi-powers:' . $credentials['api_key'] ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode 'Content-Type' => 'application/json', ), 'body' => wp_json_encode( array( 'merge_fields' => $merge_fields ) ), ) ); if ( is_wp_error( $response ) ) { return $response; } $status = (int) wp_remote_retrieve_response_code( $response ); if ( $status >= 200 && $status < 300 ) { return true; } return new WP_Error( 'divi_powers_mailchimp_member_update', __( 'Mailchimp could not update this subscriber. Please try again.', '5d-powers-for-divi' ) ); } /** Confirm the selected Divi account/list pair belongs to Mailchimp. */ public static function is_mailchimp_account( $account, $list_id ) { return ! empty( self::mailchimp_credentials( $account, $list_id ) ); } /** Sign module configuration so arbitrary public POST values are rejected. */ public static function sign_config( $account, $list_id, $tags ) { $tags = self::normalize_tag_tokens( $tags ); $payload = $account . "\n" . $list_id . "\n" . implode( "\n", $tags ); return hash_hmac( 'sha256', $payload, wp_salt( 'auth' ) ); } /** Normalize comma/newline-delimited tag names or a JSON array. */ public static function normalize_tag_tokens( $raw ) { if ( is_string( $raw ) ) { $decoded = json_decode( $raw, true ); if ( is_array( $decoded ) ) { $raw = $decoded; } else { $raw = preg_split( '/[,\r\n]+/', $raw ); } } if ( ! is_array( $raw ) ) { return array(); } $tags = array(); foreach ( $raw as $tag ) { $tag = trim( sanitize_text_field( (string) $tag ) ); if ( '' === $tag ) { continue; } $tag = substr( $tag, 0, 100 ); $tags[ strtolower( $tag ) ] = $tag; if ( count( $tags ) >= 20 ) { break; } } return array_values( $tags ); } /** Read the existing Divi Mailchimp credential without exposing it to the browser. */ private static function mailchimp_credentials( $account, $list_id ) { $options = get_option( 'et_core_api_email_options', array() ); if ( ! is_array( $options ) ) { return array(); } $mailchimp = $options['accounts']['mailchimp'][ $account ] ?? array(); $list = $mailchimp['lists'][ $list_id ] ?? array(); $api_key = isset( $mailchimp['api_key'] ) ? trim( (string) $mailchimp['api_key'] ) : ''; if ( '' === $api_key || empty( $list ) || false === strpos( $api_key, '-' ) ) { return array(); } $dc = substr( $api_key, strrpos( $api_key, '-' ) + 1 ); if ( ! preg_match( '/^[a-z]{2}[0-9]+$/i', $dc ) ) { return array(); } return array( 'api_key' => $api_key, 'dc' => strtolower( $dc ), ); } /** Resolve numeric embed-form tag IDs to their saved Mailchimp tag names. */ private function resolve_tag_names( $api_key, $dc, $list_id, $tokens ) { $tokens = self::normalize_tag_tokens( $tokens ); $names = array(); $numeric = array(); foreach ( $tokens as $token ) { $id_candidate = ltrim( $token, '#' ); if ( ctype_digit( $id_candidate ) ) { $numeric[ $id_candidate ] = true; } else { $names[ strtolower( $token ) ] = $token; } } if ( ! empty( $numeric ) ) { $offset = 0; do { $url = add_query_arg( array( 'count' => 1000, 'offset' => $offset, ), sprintf( 'https://%1$s.api.mailchimp.com/3.0/lists/%2$s/tag-search', rawurlencode( $dc ), rawurlencode( $list_id ) ) ); $response = wp_remote_get( $url, array( 'timeout' => 8, 'redirection' => 0, 'limit_response_size' => self::MAX_API_RESPONSE_BYTES, 'headers' => array( 'Authorization' => 'Basic ' . base64_encode( 'divi-powers:' . $api_key ) ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode ) ); if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) { break; } $body = json_decode( wp_remote_retrieve_body( $response ), true ); $rows = is_array( $body['tags'] ?? null ) ? $body['tags'] : array(); foreach ( $rows as $row ) { $id = isset( $row['id'] ) ? (string) $row['id'] : ''; $name = isset( $row['name'] ) ? sanitize_text_field( (string) $row['name'] ) : ''; if ( '' !== $id && '' !== $name && isset( $numeric[ $id ] ) ) { $names[ strtolower( $name ) ] = $name; unset( $numeric[ $id ] ); } } $total = isset( $body['total_items'] ) ? absint( $body['total_items'] ) : count( $rows ); $offset += 1000; } while ( ! empty( $numeric ) && $offset < $total ); } return array_values( $names ); } }