label. */ public static function providers() { return array( 'mailpoet' => 'MailPoet', 'mailchimp' => 'Mailchimp', 'brevo' => 'Brevo', ); } public static function settings() { $s = get_option( self::OPTION, array() ); return array_merge( array( 'provider' => '', 'key' => '', 'list' => '', 'listname' => '', 'pulled' => '', 'error' => '', 'synced' => 0, 'bulk' => 0, ), is_array( $s ) ? $s : array() ); } private static function update( array $changes ) { update_option( self::OPTION, array_merge( self::settings(), $changes ), false ); } /** The connected tool, or ''. */ public static function provider() { $s = self::settings(); if ( ! isset( self::providers()[ $s['provider'] ] ) || '' === (string) $s['list'] ) { return ''; } if ( 'mailpoet' === $s['provider'] && ! self::mailpoet() ) { return ''; } return $s['provider']; } /** MailPoet's API, when MailPoet is active. */ private static function mailpoet() { if ( ! class_exists( '\MailPoet\API\API' ) ) { return null; } try { return \MailPoet\API\API::MP( 'v1' ); } catch ( \Throwable $e ) { return null; } } public static function mailpoet_active() { return class_exists( '\MailPoet\API\API' ); } /* ------------------------------------------------------------------ * * Connecting * ------------------------------------------------------------------ */ /** * Check a tool's key and fetch its lists: id => name, or WP_Error. * * @param string $provider mailpoet|mailchimp|brevo. * @param string $key API key (not for MailPoet). */ public static function lists( $provider, $key = '' ) { if ( 'mailpoet' === $provider ) { $mp = self::mailpoet(); if ( ! $mp ) { return new WP_Error( 'nodebook_sync', __( 'MailPoet is not active on this site.', 'nodebook' ) ); } $out = array(); foreach ( (array) $mp->getLists() as $l ) { $out[ (string) $l['id'] ] = (string) $l['name']; } return $out; } if ( 'mailchimp' === $provider ) { $r = self::mailchimp( $key, 'GET', 'lists?count=100&fields=lists.id,lists.name' ); if ( is_wp_error( $r ) ) { return $r; } return wp_list_pluck( (array) ( $r['lists'] ?? array() ), 'name', 'id' ); } if ( 'brevo' === $provider ) { $r = self::brevo( $key, 'GET', 'contacts/lists?limit=50' ); if ( is_wp_error( $r ) ) { return $r; } $out = array(); foreach ( (array) ( $r['lists'] ?? array() ) as $l ) { $out[ (string) $l['id'] ] = (string) $l['name']; } return $out; } return new WP_Error( 'nodebook_sync', __( 'Unknown email tool.', 'nodebook' ) ); } /** * Connect a tool (or disconnect with provider ''). * * @return true|WP_Error */ public static function connect( $provider, $key, $list ) { if ( '' === $provider ) { self::update( array( 'provider' => '', 'key' => '', 'list' => '', 'error' => '', 'bulk' => 0, ) ); return true; } $lists = self::lists( $provider, $key ); if ( is_wp_error( $lists ) ) { return $lists; } if ( '' !== (string) $list && ! isset( $lists[ (string) $list ] ) ) { return new WP_Error( 'nodebook_sync', __( 'That list was not found in your account.', 'nodebook' ) ); } $was = self::settings(); self::update( array( 'provider' => $provider, 'key' => 'mailpoet' === $provider ? '' : $key, 'list' => (string) $list, 'listname' => (string) ( $lists[ (string) $list ] ?? '' ), 'error' => '', // A new list starts its unsubscribe check from now. 'pulled' => $was['provider'] === $provider && $was['list'] === (string) $list ? $was['pulled'] : gmdate( 'Y-m-d\TH:i:s\Z' ), ) ); return true; } /** Send every current subscriber to the tool, in batches in the background. */ public static function start_bulk() { if ( ! self::provider() ) { return false; } self::update( array( 'bulk' => 1 ) ); wp_clear_scheduled_hook( self::BULK_HOOK ); wp_schedule_single_event( time(), self::BULK_HOOK, array( 0 ) ); return true; } /** One batch of the bulk sync; schedules the next. */ public static function bulk( $after = 0 ) { global $wpdb; if ( ! self::provider() || ! self::settings()['bulk'] ) { return 0; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. $ids = array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT id FROM %i WHERE email_status = 'subscribed' AND email IS NOT NULL AND email <> '' AND id > %d ORDER BY id ASC LIMIT %d", Nodebook_Contacts::table(), (int) $after, self::BATCH ) ) ); $n = 0; foreach ( $ids as $id ) { if ( true === self::push_one( $id ) ) { ++$n; } } if ( count( $ids ) === self::BATCH ) { wp_schedule_single_event( time() + 5, self::BULK_HOOK, array( end( $ids ) ) ); } else { self::update( array( 'bulk' => 0 ) ); } return $n; } /* ------------------------------------------------------------------ * * Nodebook → tool * ------------------------------------------------------------------ */ /** * Consent changed in Nodebook: queue the change for the tool (a moment later, so forms stay fast). * * @param int $contact_id Contact. * @param string $status New status. */ public static function on_status( $contact_id, $status, $old = '' ) { if ( self::$pulling || ! self::provider() || ( class_exists( 'Nodebook_Sample' ) && ( Nodebook_Sample::$running || Nodebook_Sample::is_sample( (int) $contact_id ) ) ) ) { return; } if ( ! in_array( $status, array( 'subscribed', 'unsubscribed', 'bounced', 'complained' ), true ) ) { return; } if ( ! wp_next_scheduled( self::PUSH_HOOK, array( (int) $contact_id ) ) ) { wp_schedule_single_event( time(), self::PUSH_HOOK, array( (int) $contact_id ) ); } } /** * Send one contact's consent to the tool. * * @return true|WP_Error|null Null when there is nothing to send. */ public static function push_one( $contact_id ) { $provider = self::provider(); $c = Nodebook_Contacts::get( (int) $contact_id ); if ( ! $provider || ! $c || ! is_email( (string) $c['email'] ) ) { return null; } $status = (string) $c['email_status']; if ( 'subscribed' !== $status && ! in_array( $status, array( 'unsubscribed', 'bounced', 'complained' ), true ) ) { return null; } $s = self::settings(); $sub = 'subscribed' === $status; $r = null; if ( 'mailpoet' === $provider ) { $r = self::push_mailpoet( $c, $sub, (string) $s['list'] ); } elseif ( 'mailchimp' === $provider ) { $hash = md5( strtolower( (string) $c['email'] ) ); $body = array( 'email_address' => (string) $c['email'], 'status' => $sub ? 'subscribed' : 'unsubscribed', 'status_if_new' => $sub ? 'subscribed' : 'unsubscribed', ); if ( $sub ) { $body['merge_fields'] = array_filter( array( 'FNAME' => (string) $c['first_name'], 'LNAME' => (string) $c['last_name'], ) ); } $r = self::mailchimp( (string) $s['key'], 'PUT', 'lists/' . rawurlencode( (string) $s['list'] ) . '/members/' . $hash, $body ); } elseif ( 'brevo' === $provider ) { if ( $sub ) { $r = self::brevo( (string) $s['key'], 'POST', 'contacts', array( 'email' => (string) $c['email'], 'attributes' => (object) array_filter( array( 'FIRSTNAME' => (string) $c['first_name'], 'LASTNAME' => (string) $c['last_name'], ) ), 'listIds' => array( (int) $s['list'] ), 'emailBlacklisted' => false, 'updateEnabled' => true, ) ); } else { $r = self::brevo( (string) $s['key'], 'PUT', 'contacts/' . rawurlencode( (string) $c['email'] ), array( 'emailBlacklisted' => true ) ); // Never in Brevo: nothing to unsubscribe. if ( is_wp_error( $r ) && 404 === (int) $r->get_error_data() ) { $r = array(); } } } if ( is_wp_error( $r ) ) { self::update( array( 'error' => $r->get_error_message() ) ); return $r; } $was = self::settings(); self::update( array( 'synced' => (int) $was['synced'] + 1, 'error' => '', ) ); return true; } private static function push_mailpoet( array $c, $sub, $list ) { $mp = self::mailpoet(); if ( ! $mp ) { return new WP_Error( 'nodebook_sync', __( 'MailPoet is not active on this site.', 'nodebook' ) ); } try { $found = null; try { $found = $mp->getSubscriber( (string) $c['email'] ); } catch ( \Throwable $e ) { $found = null; } if ( $sub ) { $opts = array( 'send_confirmation_email' => false, 'schedule_welcome_email' => false, ); if ( $found ) { $mp->subscribeToList( $found['id'], $list, $opts + array( 'skip_subscriber_notification' => true ) ); } else { $mp->addSubscriber( array( 'email' => (string) $c['email'], 'first_name' => (string) $c['first_name'], 'last_name' => (string) $c['last_name'], 'status' => 'subscribed', ), array( $list ), $opts ); } } elseif ( $found ) { self::$pulling = true; $mp->unsubscribe( $found['id'] ); self::$pulling = false; } } catch ( \Throwable $e ) { self::$pulling = false; return new WP_Error( 'nodebook_sync', 'MailPoet: ' . $e->getMessage() ); } return true; } /* ------------------------------------------------------------------ * * Tool → Nodebook (unsubscribes only: saying no always wins) * ------------------------------------------------------------------ */ /** Daily: unsubscribes in Mailchimp or Brevo since the last check. */ public static function pull() { $provider = self::provider(); if ( ! in_array( $provider, array( 'mailchimp', 'brevo' ), true ) ) { return 0; } $s = self::settings(); $since = '' !== (string) $s['pulled'] ? (string) $s['pulled'] : gmdate( 'Y-m-d\TH:i:s\Z', time() - DAY_IN_SECONDS ); $now = gmdate( 'Y-m-d\TH:i:s\Z' ); $emails = array(); if ( 'mailchimp' === $provider ) { $r = self::mailchimp( (string) $s['key'], 'GET', 'lists/' . rawurlencode( (string) $s['list'] ) . '/members?status=unsubscribed&count=1000&fields=members.email_address&since_last_changed=' . rawurlencode( $since ) ); if ( is_wp_error( $r ) ) { self::update( array( 'error' => $r->get_error_message() ) ); return 0; } $emails = wp_list_pluck( (array) ( $r['members'] ?? array() ), 'email_address' ); } else { $r = self::brevo( (string) $s['key'], 'GET', 'contacts?limit=1000&modifiedSince=' . rawurlencode( $since ) ); if ( is_wp_error( $r ) ) { self::update( array( 'error' => $r->get_error_message() ) ); return 0; } foreach ( (array) ( $r['contacts'] ?? array() ) as $ct ) { if ( ! empty( $ct['emailBlacklisted'] ) ) { $emails[] = (string) $ct['email']; } } } $n = self::apply_unsubscribes( $emails, self::providers()[ $provider ] ); self::update( array( 'pulled' => $now, 'error' => '', ) ); return $n; } /** * MailPoet changed someone's status. * * @param int $subscriber_id MailPoet subscriber. */ public static function from_mailpoet( $subscriber_id ) { if ( self::$pulling || 'mailpoet' !== self::provider() ) { return; } $mp = self::mailpoet(); if ( ! $mp ) { return; } try { $sub = $mp->getSubscriber( (int) $subscriber_id ); } catch ( \Throwable $e ) { return; } if ( in_array( (string) ( $sub['status'] ?? '' ), array( 'unsubscribed', 'bounced' ), true ) ) { self::apply_unsubscribes( array( (string) $sub['email'] ), 'MailPoet' ); } } /** Mark people unsubscribed in Nodebook (only those subscribed or pending here). */ private static function apply_unsubscribes( array $emails, $label ) { $n = 0; self::$pulling = true; foreach ( array_unique( array_filter( $emails, 'is_email' ) ) as $email ) { $c = Nodebook_Contacts::find_by_email( $email ); if ( ! $c || ! in_array( (string) $c['email_status'], array( 'subscribed', 'pending', '' ), true ) ) { continue; } /* translators: %s: email tool name */ if ( Nodebook_Subscription::set( (int) $c['id'], 'unsubscribed', array( 'source' => sprintf( __( 'Unsubscribed in %s', 'nodebook' ), $label ), 'user_id' => 0 ) ) ) { ++$n; } } self::$pulling = false; return $n; } /* ------------------------------------------------------------------ * * HTTP * ------------------------------------------------------------------ */ /** Mailchimp API call. The data centre is the part of the key after the dash. */ private static function mailchimp( $key, $method, $path, $body = null ) { if ( ! preg_match( '/^[0-9a-f]{32}-([a-z]{2,4}\d{1,3})$/', (string) $key, $m ) ) { return new WP_Error( 'nodebook_sync', __( 'That does not look like a Mailchimp API key (it ends in something like -us21).', 'nodebook' ) ); } return self::request( 'https://' . $m[1] . '.api.mailchimp.com/3.0/' . $path, $method, array( 'Authorization' => 'Basic ' . base64_encode( 'nodebook:' . $key ) ), // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- HTTP Basic auth. $body, 'Mailchimp' ); } private static function brevo( $key, $method, $path, $body = null ) { if ( '' === trim( (string) $key ) ) { return new WP_Error( 'nodebook_sync', __( 'Paste your Brevo API key.', 'nodebook' ) ); } return self::request( 'https://api.brevo.com/v3/' . $path, $method, array( 'api-key' => trim( (string) $key ) ), $body, 'Brevo' ); } private static function request( $url, $method, array $headers, $body, $label ) { $args = array( 'method' => $method, 'timeout' => 15, 'headers' => $headers + array( 'Accept' => 'application/json', 'Content-Type' => 'application/json', ), ); if ( null !== $body ) { $args['body'] = wp_json_encode( $body ); } $res = wp_remote_request( $url, $args ); if ( is_wp_error( $res ) ) { /* translators: 1: email tool name, 2: error */ return new WP_Error( 'nodebook_sync', sprintf( __( '%1$s could not be reached: %2$s', 'nodebook' ), $label, $res->get_error_message() ) ); } $code = (int) wp_remote_retrieve_response_code( $res ); $data = json_decode( (string) wp_remote_retrieve_body( $res ), true ); if ( $code >= 300 ) { $msg = is_array( $data ) ? (string) ( $data['detail'] ?? ( $data['message'] ?? '' ) ) : ''; if ( 401 === $code || 403 === $code ) { /* translators: %s: email tool name */ $msg = sprintf( __( '%s did not accept the API key.', 'nodebook' ), $label ); } /* translators: 1: email tool name, 2: HTTP status, 3: message */ return new WP_Error( 'nodebook_sync', '' !== $msg && false !== strpos( $msg, $label ) ? $msg : sprintf( __( '%1$s answered %2$d: %3$s', 'nodebook' ), $label, $code, '' !== $msg ? $msg : __( 'unknown error', 'nodebook' ) ), $code ); } return is_array( $data ) ? $data : array(); } }