subscribers:read ( a number, or the SHA-256 of the lowercased address) * POST /api/subscribers subscribers:write (email, first_name, last_name, status: pending|subscribed, tag_ids, fields) * PATCH /api/subscribers/ subscribers:write (first_name, last_name, fields, add_tag_ids, remove_tag_ids, status: unsubscribed) * GET /api/tags subscribers:read * GET /api/campaigns campaigns:read (status, page, per_page) * GET /api/campaigns/ campaigns:read * A new address goes through the signup flow: pending sends the * confirmation email; subscribed means the app already has their consent. * Someone who unsubscribed gets a confirmation instead, and bounced, * complained or erased addresses are refused. Nothing here sends a * campaign or deletes anyone. * * Owner routes (manage_options): /api-keys, /outgoing-webhooks. */ class Mailpuff_Api_Controller extends Mailpuff_REST_Controller { /** Requests one key may make a minute. */ const PER_MINUTE = 120; /** The most rows a page holds. */ const MAX_PER_PAGE = 100; /** * Register routes. */ public function register_routes() { $id = '(?P[0-9]+|[a-f0-9]{64})'; register_rest_route( $this->namespace, '/api/subscribers', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'list_subscribers' ), 'permission_callback' => array( $this, 'check_subscribers_read' ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'add_subscriber' ), 'permission_callback' => array( $this, 'check_subscribers_write' ), ), ) ); register_rest_route( $this->namespace, '/api/subscribers/' . $id, array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_subscriber' ), 'permission_callback' => array( $this, 'check_subscribers_read' ), ), array( 'methods' => 'PATCH', 'callback' => array( $this, 'change_subscriber' ), 'permission_callback' => array( $this, 'check_subscribers_write' ), ), ) ); register_rest_route( $this->namespace, '/api/tags', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'list_tags' ), 'permission_callback' => array( $this, 'check_subscribers_read' ), ) ); register_rest_route( $this->namespace, '/api/campaigns', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'list_campaigns' ), 'permission_callback' => array( $this, 'check_campaigns_read' ), ) ); register_rest_route( $this->namespace, '/api/campaigns/(?P\d+)', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_campaign' ), 'permission_callback' => array( $this, 'check_campaigns_read' ), ) ); // The owner's screens. register_rest_route( $this->namespace, '/api-keys', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => fn() => $this->success( array( 'keys' => Mailpuff_Api_Keys::all(), 'scopes' => Mailpuff_Api_Keys::scope_labels(), ) ), 'permission_callback' => array( $this, 'check_permission' ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => fn( $request ) => $this->answer( Mailpuff_Api_Keys::create( (string) $request->get_param( 'name' ), (array) $request->get_param( 'scopes' ) ), 201 ), 'permission_callback' => array( $this, 'check_permission' ), ), ) ); register_rest_route( $this->namespace, '/api-keys/(?P[a-f0-9]{12})', array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => fn( $request ) => Mailpuff_Api_Keys::revoke( (string) $request['id'] ) ? $this->success( array( 'revoked' => true ) ) : $this->error( 'not_found', __( 'No key has that id.', 'mailpuff' ), 404 ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/outgoing-webhooks', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => fn() => $this->success( array( 'webhooks' => Mailpuff_Outgoing_Webhooks::all(), 'events' => Mailpuff_Outgoing_Webhooks::event_labels(), ) ), 'permission_callback' => array( $this, 'check_permission' ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => fn( $request ) => $this->answer( Mailpuff_Outgoing_Webhooks::create( (string) $request->get_param( 'url' ), (array) $request->get_param( 'events' ) ), 201 ), 'permission_callback' => array( $this, 'check_permission' ), ), ) ); register_rest_route( $this->namespace, '/outgoing-webhooks/(?P[a-z0-9]{12})', array( array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => fn( $request ) => $this->answer( Mailpuff_Outgoing_Webhooks::update( (string) $request['id'], array_intersect_key( (array) $request->get_json_params(), array_flip( array( 'active', 'events' ) ) ) ) ), 'permission_callback' => array( $this, 'check_permission' ), ), array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => fn( $request ) => Mailpuff_Outgoing_Webhooks::delete( (string) $request['id'] ) ? $this->success( array( 'deleted' => true ) ) : $this->error( 'not_found', __( 'No webhook has that id.', 'mailpuff' ), 404 ), 'permission_callback' => array( $this, 'check_permission' ), ), ) ); register_rest_route( $this->namespace, '/outgoing-webhooks/(?P[a-z0-9]{12})/test', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => fn( $request ) => $this->answer( Mailpuff_Outgoing_Webhooks::test( (string) $request['id'] ) ), 'permission_callback' => array( $this, 'check_permission' ), ) ); } /** * Permission for a key with the subscribers:read scope. * * @param WP_REST_Request $request Request. * @return true|WP_Error */ public function check_subscribers_read( $request ) { return $this->check_key( $request, 'subscribers:read' ); } /** * Permission for a key with the subscribers:write scope. * * @param WP_REST_Request $request Request. * @return true|WP_Error */ public function check_subscribers_write( $request ) { return $this->check_key( $request, 'subscribers:write' ); } /** * Permission for a key with the campaigns:read scope. * * @param WP_REST_Request $request Request. * @return true|WP_Error */ public function check_campaigns_read( $request ) { return $this->check_key( $request, 'campaigns:read' ); } /** * Permission for a key route: a known key with the scope, within its * requests a minute. A failed check writes nothing. * * @param WP_REST_Request $request Request. * @param string $scope One of Mailpuff_Api_Keys::SCOPES. * @return true|WP_Error */ public function check_key( $request, $scope ) { $sent = (string) $request->get_header( 'x-mailpuff-key' ); if ( '' === $sent && preg_match( '/^Bearer\s+(\S+)$/i', (string) $request->get_header( 'authorization' ), $m ) ) { $sent = $m[1]; } $row = Mailpuff_Api_Keys::find( sanitize_text_field( $sent ) ); if ( ! $row ) { return $this->error( 'invalid_key', __( 'Invalid or missing API key. Send it in the X-Mailpuff-Key header.', 'mailpuff' ), 401 ); } if ( ! in_array( $scope, (array) $row['scopes'], true ) ) { /* translators: %s: a scope, such as subscribers:write. */ return $this->error( 'insufficient_scope', sprintf( __( 'This key may not do that. It needs %s.', 'mailpuff' ), $scope ), 403 ); } if ( ! $this->within_key_limit( (string) $row['id'] ) ) { return $this->error( 'rate_limit', __( 'Too many requests. Try again in a minute.', 'mailpuff' ), 429 ); } Mailpuff_Api_Keys::mark_used( $row ); return true; } /** * GET /api/subscribers. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function list_subscribers( $request ) { list( $page, $per ) = $this->paging( $request ); $out = Mailpuff_Abilities::list_contacts( array( 'status' => '' !== (string) $request->get_param( 'status' ) ? (string) $request->get_param( 'status' ) : 'subscribed', 'search' => (string) $request->get_param( 'search' ), 'tag_id' => (int) $request->get_param( 'tag_id' ), 'limit' => $per, 'offset' => ( $page - 1 ) * $per, ) ); if ( is_wp_error( $out ) ) { return $out; } return $this->success( array( 'items' => array_map( array( $this, 'subscriber_out' ), $out['contacts'] ), 'total' => (int) $out['total'], 'page' => $page, 'pages' => max( 1, (int) ceil( $out['total'] / $per ) ), ) ); } /** * GET /api/subscribers/. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function get_subscriber( $request ) { $id = $this->subscriber_id( (string) $request['id'] ); return $id ? $this->success( $this->subscriber( $id ) ) : $this->no_subscriber(); } /** * POST /api/subscribers: add someone, or update who is already there. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function add_subscriber( $request ) { $email = sanitize_email( (string) $request->get_param( 'email' ) ); if ( ! is_email( $email ) ) { return $this->error( 'invalid_email', __( 'A valid email address is required.', 'mailpuff' ), 400 ); } $status = '' !== (string) $request->get_param( 'status' ) ? (string) $request->get_param( 'status' ) : 'pending'; if ( ! in_array( $status, array( 'pending', 'subscribed' ), true ) ) { return $this->error( 'invalid_status', __( 'status must be pending (a confirmation email first) or subscribed (you already have their consent).', 'mailpuff' ), 400 ); } $tags = $this->tag_ids( $request->get_param( 'tag_ids' ) ); if ( is_wp_error( $tags ) ) { return $tags; } $existed = (bool) Mailpuff_Contact::find_by_email( $email ); $result = Mailpuff_Subscription::signup( $email, array( 'first_name' => (string) $request->get_param( 'first_name' ), 'last_name' => (string) $request->get_param( 'last_name' ), 'double_opt_in' => 'subscribed' !== $status, 'source' => 'api', 'consent_source' => 'api', // Joined before the welcome email, so a tag's own welcome // email goes in its place. The key may give internal tags. 'tag_ids' => $tags, ) ); $contact = Mailpuff_Contact::find_by_email( $email ); if ( 'ignored' === $result || ! $contact ) { return $this->error( 'not_added', __( 'That address cannot be added: it bounced, complained or asked to be erased.', 'mailpuff' ), 422 ); } $changed = $this->apply( (int) $contact->id, $request, $tags, array() ); if ( is_wp_error( $changed ) ) { return $changed; } return $this->success( array( 'result' => $result, 'created' => ! $existed, 'subscriber' => $this->subscriber( (int) $contact->id ), ), $existed ? 200 : 201 ); } /** * PATCH /api/subscribers/. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function change_subscriber( $request ) { $id = $this->subscriber_id( (string) $request['id'] ); if ( ! $id ) { return $this->no_subscriber(); } $status = (string) $request->get_param( 'status' ); if ( '' !== $status && 'unsubscribed' !== $status ) { return $this->error( 'invalid_status', __( 'status can only be unsubscribed here. To subscribe someone, POST /api/subscribers.', 'mailpuff' ), 400 ); } $add = $this->tag_ids( $request->get_param( 'add_tag_ids' ) ); $remove = $this->tag_ids( $request->get_param( 'remove_tag_ids' ) ); foreach ( array( $add, $remove ) as $ids ) { if ( is_wp_error( $ids ) ) { return $ids; } } $changed = $this->apply( $id, $request, $add, $remove ); if ( is_wp_error( $changed ) ) { return $changed; } if ( 'unsubscribed' === $status ) { Mailpuff_Abilities::unsubscribe_contact( array( 'contact_id' => $id ) ); } return $this->success( $this->subscriber( $id ) ); } /** * GET /api/tags. * * @return WP_REST_Response|WP_Error */ public function list_tags() { $out = Mailpuff_Abilities::list_audiences(); if ( is_wp_error( $out ) ) { return $out; } $tags = array(); foreach ( $out['audiences'] as $row ) { if ( 'tag' === $row['type'] ) { $tags[] = array( 'id' => (int) $row['id'], 'name' => (string) $row['name'], 'count' => (int) $row['count'], 'subscribed' => (int) $row['subscribed'], ); } } return $this->success( array( 'items' => $tags ) ); } /** * GET /api/campaigns. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function list_campaigns( $request ) { list( $page, $per ) = $this->paging( $request ); $out = Mailpuff_Abilities::list_campaigns( array( 'status' => (string) $request->get_param( 'status' ), 'limit' => $per, 'offset' => ( $page - 1 ) * $per, ) ); if ( is_wp_error( $out ) ) { return $out; } return $this->success( array( 'items' => $out['campaigns'], 'total' => (int) $out['total'], 'page' => $page, 'pages' => max( 1, (int) ceil( $out['total'] / $per ) ), ) ); } /** * GET /api/campaigns/: the campaign's report. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function get_campaign( $request ) { $out = Mailpuff_Abilities::campaign_stats( array( 'campaign_id' => (int) $request['id'] ) ); return is_wp_error( $out ) ? $out : $this->success( $out ); } /* ------------------------------------------------------------------ */ /* Helpers */ /* ------------------------------------------------------------------ */ /** * Names, fields and tags from a request, checked before anything is stored. * * @param int $id Contact ID. * @param WP_REST_Request $request Request. * @param int[] $add Tags to add. * @param int[] $remove Tags to remove. * @return true|WP_Error */ private function apply( $id, $request, array $add, array $remove ) { $change = array( 'contact_id' => $id ); foreach ( array( 'first_name', 'last_name' ) as $key ) { if ( null !== $request->get_param( $key ) ) { $change[ $key ] = (string) $request->get_param( $key ); } } $fields = $request->get_param( 'fields' ); if ( is_array( $fields ) && $fields ) { $change['fields'] = $fields; } if ( count( $change ) > 1 ) { $out = Mailpuff_Abilities::update_contact( $change ); if ( is_wp_error( $out ) ) { return $out; } } $now = current_time( 'mysql' ); foreach ( $add as $tag ) { Mailpuff_Contact_Service::add_to_group( $id, $tag, $now ); } foreach ( $remove as $tag ) { Mailpuff_Contact_Service::remove_from_group( $id, $tag ); } return true; } /** * Tag ids from a request, each one checked. * * @param mixed $value The parameter. * @return int[]|WP_Error */ private function tag_ids( $value ) { global $wpdb; $ids = array_values( array_unique( array_filter( array_map( 'intval', (array) $value ) ) ) ); if ( ! $ids ) { return array(); } $table = Mailpuff_Schema::table( Mailpuff_Schema::LISTS ); $in = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- $in is a list of %d, one per id; the table is a %i. $found = array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT id FROM %i WHERE id IN ($in)", $table, ...$ids ) ) ); $gone = array_diff( $ids, $found ); if ( $gone ) { /* translators: %s: tag ids. */ return $this->error( 'no_tag', sprintf( __( 'No tag has the id %s. GET /api/tags lists them.', 'mailpuff' ), implode( ', ', $gone ) ), 400 ); } return $ids; } /** * A subscriber id from the path: a number, or the address's SHA-256. * * @param string $id The path part. * @return int 0 when there is nobody. */ private function subscriber_id( $id ) { global $wpdb; $table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); if ( ctype_digit( $id ) ) { return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE id = %s LIMIT 1', $table, $id ) ); } return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE email_hash = %s LIMIT 1', $table, $id ) ); } /** * One subscriber as the API answers. * * @param int $id Contact ID. * @return array */ private function subscriber( $id ) { $row = Mailpuff_Abilities::get_contact( array( 'contact_id' => $id, 'activity_limit' => 0, ) ); $fields = array(); foreach ( (array) ( $row['fields'] ?? array() ) as $field ) { $fields[ $field['key'] ] = $field['value']; } $row['fields'] = $fields; $out = $this->subscriber_out( $row ); $out['confirmed_at'] = $row['confirmed_at'] ?? null; return $out; } /** * The fields a subscriber has in the API. * * @param array $row A list-contacts or get-contact row. * @return array { id, email, first_name, last_name, status, created_at, tags, fields } */ private function subscriber_out( $row ) { return array( 'id' => (int) $row['id'], 'email' => (string) $row['email'], 'first_name' => (string) $row['first_name'], 'last_name' => (string) $row['last_name'], 'status' => (string) $row['status'], 'created_at' => (string) $row['created_at'], 'tags' => array_values( (array) $row['tags'] ), 'fields' => (object) $row['fields'], ); } /** * The page and its size from a request. * * @param WP_REST_Request $request Request. * @return int[] { page, per page } */ private function paging( $request ) { $per = (int) $request->get_param( 'per_page' ); return array( max( 1, (int) $request->get_param( 'page' ) ), $per > 0 ? min( self::MAX_PER_PAGE, $per ) : 50, ); } /** * A key's requests this minute, counted like the site's other limits. * * @param string $id Key id. * @return bool Whether the request may go on. */ private function within_key_limit( $id ) { $name = 'mailpuff_api_rl_' . $id . '_' . (int) floor( time() / 60 ); if ( wp_using_ext_object_cache() ) { wp_cache_add( $name, 0, 'mailpuff_rl', 2 * MINUTE_IN_SECONDS ); return (int) wp_cache_incr( $name, 1, 'mailpuff_rl' ) <= self::PER_MINUTE; } $count = (int) get_transient( $name ); if ( $count >= self::PER_MINUTE ) { return false; } set_transient( $name, $count + 1, 2 * MINUTE_IN_SECONDS ); return true; } /** * A service's answer as a response. * * @param array|WP_Error $out The answer. * @param int $status Status on success. * @return WP_REST_Response|WP_Error */ private function answer( $out, $status = 200 ) { return is_wp_error( $out ) ? $out : $this->success( $out, $status ); } /** * @return WP_Error */ private function no_subscriber() { return $this->error( 'not_found', __( 'No subscriber has that id.', 'mailpuff' ), 404 ); } }