namespace, '/contacts', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_items' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'status' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'group_id' => array( 'sanitize_callback' => 'absint' ), 'group_ids' => array(), 'source' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'customer_type' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'search' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'engagement' => array( 'sanitize_callback' => 'sanitize_key' ), 'page' => array( 'sanitize_callback' => 'absint' ), 'per_page' => array( 'sanitize_callback' => 'absint' ), 'with_counts' => array( 'sanitize_callback' => 'rest_sanitize_boolean' ), 'with_reach' => array( 'sanitize_callback' => 'rest_sanitize_boolean' ), ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'create_item' ), 'permission_callback' => array( $this, 'check_permission' ), ), ) ); register_rest_route( $this->namespace, '/contacts/bulk', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'bulk_action' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/contacts/stats', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_dashboard_stats' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/contacts/facets', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_facets' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/contacts/export', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'export_items' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'status' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'group_id' => array( 'sanitize_callback' => 'absint' ), 'group_ids' => array(), 'source' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'customer_type' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'search' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'engagement' => array( 'sanitize_callback' => 'sanitize_key' ), 'segment_id' => array( 'sanitize_callback' => 'absint' ), 'ids' => array(), ), ) ); register_rest_route( $this->namespace, '/contacts/(?P\d+)', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_item' ), 'permission_callback' => array( $this, 'check_permission' ), ), array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update_item' ), 'permission_callback' => array( $this, 'check_permission' ), ), array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'delete_item' ), 'permission_callback' => array( $this, 'check_permission' ), ), ) ); register_rest_route( $this->namespace, '/contacts/(?P\d+)/activity', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_activity' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'limit' => array( 'sanitize_callback' => 'absint' ), ), ) ); // The owner withdraws a reader's consent to count opens and clicks // (when the reader asks); nobody but the reader gives it. register_rest_route( $this->namespace, '/contacts/(?P\d+)/tracking-consent', array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'withdraw_tracking' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/contacts/import', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'import_contacts' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); // Other newsletter plugins on this site, with a dry run, and importing one. register_rest_route( $this->namespace, '/contacts/import/sources', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_import_sources' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/contacts/import/sources/(?P[a-z0-9_-]+)', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'import_from_source' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); // Mailchimp's audience export (a zip) as one CSV for the Import page. register_rest_route( $this->namespace, '/contacts/import/mailchimp', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'unpack_mailchimp' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); // The import preview: which of these addresses are already contacts. register_rest_route( $this->namespace, '/contacts/import/check', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'check_import' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'emails' => array( 'type' => 'array', 'required' => true, 'items' => array( 'type' => 'string' ), 'maxItems' => Mailpuff_Import_Sync::LOOKUP_MAX, ), ), ) ); register_rest_route( $this->namespace, '/contacts/import/(?P\d+)', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_import_status' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); // Custom fields (Mailpuff_Fields): Settings › Fields, the subscriber // page, segments and the importer's mapping targets. register_rest_route( $this->namespace, '/custom-fields', array( array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_custom_fields' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'described' => array( 'sanitize_callback' => 'rest_sanitize_boolean' ), ), ), array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'create_custom_field' ), 'permission_callback' => array( $this, 'check_permission' ), ), ) ); register_rest_route( $this->namespace, '/custom-fields/(?P[a-z0-9_-]+)', array( array( 'methods' => WP_REST_Server::EDITABLE, 'callback' => array( $this, 'update_custom_field' ), 'permission_callback' => array( $this, 'check_permission' ), ), array( 'methods' => WP_REST_Server::DELETABLE, 'callback' => array( $this, 'delete_custom_field' ), 'permission_callback' => array( $this, 'check_permission' ), ), ) ); // Site users as subscribers: where it stands (Settings › Emails). register_rest_route( $this->namespace, '/site-users', array( 'methods' => WP_REST_Server::READABLE, 'callback' => static fn() => rest_ensure_response( Mailpuff_Site_Users::status() ), 'permission_callback' => array( $this, 'check_permission' ), ) ); // Cross-plugin contact cards (read-only federation by email). register_rest_route( $this->namespace, '/contact-cards', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_contact_cards' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'email' => array( 'required' => true, 'sanitize_callback' => 'sanitize_email', ), ), ) ); } /** * Cards contributed by sibling PlugPress products for this email (e.g. * Bridle support history). Returns [] when no other product answers. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public function get_contact_cards( $request ) { $email = sanitize_email( (string) $request->get_param( 'email' ) ); if ( ! $email || ! is_email( $email ) ) { return $this->success( array() ); } /** This filter is the shared cross-plugin convention. */ // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- the cross-plugin card filter is shared by name. $cards = apply_filters( 'plugpress_contact_cards', array(), $email, 'mailpuff' ); return $this->success( is_array( $cards ) ? array_values( $cards ) : array() ); } /** * GET /contacts/stats — headline numbers for the Contacts dashboard cards: * new contacts today, and emails sent / opened / clicked over the last 90 days * (engagement windowed by each batch's send date). * * @return WP_REST_Response */ public function get_dashboard_stats() { global $wpdb; $subs = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $sends = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGN_SENDS ); $tracking = Mailpuff_Schema::table( Mailpuff_Schema::TRACKING ); $today = wp_date( 'Y-m-d 00:00:00' ); $cutoff = wp_date( 'Y-m-d H:i:s', time() - 90 * DAY_IN_SECONDS ); $new_today = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE created_at >= %s', $subs, $today ) ); $sent_90d = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COALESCE(SUM(sent_count),0) FROM %i WHERE created_at >= %s', $sends, $cutoff ) ); $opened = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i t JOIN %i cs ON cs.id = t.batch_id WHERE t.open_count > 0 AND cs.created_at >= %s', $tracking, $sends, $cutoff ) ); $clicked = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i t JOIN %i cs ON cs.id = t.batch_id WHERE t.click_count > 0 AND cs.created_at >= %s', $tracking, $sends, $cutoff ) ); // All-time averages (unique opens/clicks ÷ delivered) for the Home cards. $delivered_all = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COALESCE(SUM(sent_count),0) FROM %i', $sends ) ); $opened_all = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE open_count > 0', $tracking ) ); $clicked_all = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE click_count > 0', $tracking ) ); return $this->success( array( 'new_today' => $new_today, 'emails_sent_90d' => $sent_90d, 'opened_90d' => $opened, 'clicked_90d' => $clicked, 'avg_open_rate' => $delivered_all ? round( $opened_all / $delivered_all * 100, 1 ) : 0, 'avg_click_rate' => $delivered_all ? round( $clicked_all / $delivered_all * 100, 1 ) : 0, ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function get_items( $request ) { $subscribers_table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $pagination = $this->get_pagination( $request ); list( $from, $where, $params ) = $this->build_filter( $request ); $params = array_merge( array( $subscribers_table ), $params ); $total = $this->count_rows( 'SELECT COUNT(*)' . $from . $where, $params ); // Imports stamp many rows with the same second; the id keeps pages stable. $rows = $this->paginated_query( 'SELECT c.*' . $from . $where . ' ORDER BY c.created_at DESC, c.id DESC', $params, $pagination ); $rows = $this->without_secrets( $this->attach_avatars( $this->attach_groups( $rows ) ) ); $extra = array(); if ( rest_sanitize_boolean( $request->get_param( 'with_counts' ) ) ) { // The Status menu counts the list it filters: every other filter applies. $others = $this->request_filter( $request ); $others['status'] = ''; list( $clauses, $c_params ) = Mailpuff_Contact_Filter::build( $others ); $extra['counts'] = $this->status_counts( 'SELECT c.status AS status, COUNT(*) AS c FROM %i c WHERE 1=1' . $clauses . ' GROUP BY c.status', array_merge( array( $subscribers_table ), $c_params ) ); } if ( rest_sanitize_boolean( $request->get_param( 'with_reach' ) ) ) { // What a campaign to this filter reaches now, as Review counts it. $extra['reach'] = Mailpuff_Audience::count( array( 'type' => 'filter', 'filter' => $this->request_filter( $request ), ) ); } return $this->paginated_response( $rows, $total, $pagination, $extra ); } /** * Distinct filterable attribute values, for the Contacts list filter menus. * * @return WP_REST_Response { sources: string[], customer_types: string[] } */ public function get_facets( $request ) { global $wpdb; $table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $sources = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT source FROM %i WHERE source IS NOT NULL AND source != '' ORDER BY source ASC", $table ) ); $types = $wpdb->get_col( $wpdb->prepare( "SELECT DISTINCT customer_type FROM %i WHERE customer_type IS NOT NULL AND customer_type != '' ORDER BY customer_type ASC", $table ) ); return $this->success( array( 'sources' => array_values( array_filter( (array) $sources ) ), 'customer_types' => array_values( array_filter( (array) $types ) ), ) ); } /** * Build the shared FROM/WHERE for the contacts list from the request's * status / group_ids / source / customer_type / search params. * * Delegates the clause assembly to {@see Mailpuff_Contact_Filter::build()} — * the single filter→SQL translator shared with saved segments and campaign * recipient selection — so the list, a segment's count, and the actual send * all stay consistent. * * @param WP_REST_Request $request Request object. * @return array { string $from, string $where, array $params } */ private function build_filter( $request ) { list( $clauses, $params ) = Mailpuff_Contact_Filter::build( $this->request_filter( $request ) ); $from = ' FROM %i c'; $where = ' WHERE 1=1' . $clauses; return array( $from, $where, $params ); } /** * The contact filter a list request names, in Mailpuff_Contact_Filter's shape. * * @param WP_REST_Request $request Request object. * @return array */ private function request_filter( $request ) { return array( 'status' => $request->get_param( 'status' ), 'group_ids' => Mailpuff_Contact_Service::parse_group_ids( $request ), 'source' => $request->get_param( 'source' ), 'customer_type' => $request->get_param( 'customer_type' ), 'search' => $request->get_param( 'search' ), 'engagement' => $request->get_param( 'engagement' ), // Custom field conditions, as JSON in an address. 'fields' => Mailpuff_Fields::normalize_conditions( $request->get_param( 'fields' ) ), ); } /** * The filter a segment saved, its status included, or null when there is * no such segment. * * @param int $segment_id Segment id. * @return array|null */ private function segment_filter( $segment_id ) { global $wpdb; $table = Mailpuff_Schema::table( Mailpuff_Schema::SEGMENTS ); $json = $wpdb->get_var( $wpdb->prepare( 'SELECT filter FROM %i WHERE id = %d', $table, (int) $segment_id ) ); if ( null === $json ) { return null; } $filter = json_decode( (string) $json, true ); return Mailpuff_Contact_Filter::normalize( is_array( $filter ) ? $filter : array() ); } /** * The ids of every contact a filter matches, newest first. * * @param array $filter Contact filter. * @return int[] */ private function matching_ids( array $filter ) { global $wpdb; list( $clauses, $params ) = Mailpuff_Contact_Filter::build( $filter ); $table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $sql = 'SELECT c.id FROM %i c WHERE 1=1' . $clauses . ' ORDER BY c.created_at DESC, c.id DESC'; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- clauses from Mailpuff_Contact_Filter::build() are literal, values and tables bound. $ids = $wpdb->get_col( $wpdb->prepare( $sql, array_merge( array( $table ), $params ) ) ); return array_map( 'intval', (array) $ids ); } /** * The ids, of those given, that are contacts, newest first. * * @param int[] $ids Contact ids. * @return int[] */ private function existing_ids( array $ids ) { global $wpdb; $table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $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. return array_map( 'intval', (array) $wpdb->get_col( $wpdb->prepare( "SELECT id FROM %i WHERE id IN ($in) ORDER BY created_at DESC, id DESC", $table, ...$ids ) ) ); } /** * Attach each row's group memberships ({id,name}[]) and group_ids (int[]) so * the list can render group chips. One extra round-trip for the whole page. * * @param array $rows Subscriber rows (each with an ->id). * @return array The same rows, with ->groups and ->group_ids populated. */ private function attach_groups( $rows ) { if ( empty( $rows ) ) { return $rows; } global $wpdb; $lists_table = Mailpuff_Schema::table( Mailpuff_Schema::LISTS ); $subscriber_lists_table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBER_LISTS ); $ids = array_map( static fn( $r ) => (int) $r->id, $rows ); $placeholders = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); // Table names are class constants (not user input); the contact IDs are // bound via prepare() through the %d placeholders in $placeholders. // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $memberships = $wpdb->get_results( $wpdb->prepare( "SELECT sl.contact_id, g.id, g.name FROM %i sl INNER JOIN %i g ON g.id = sl.group_id WHERE sl.contact_id IN ($placeholders) ORDER BY g.name ASC", $subscriber_lists_table, $lists_table, ...$ids ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $by_contact = array(); foreach ( (array) $memberships as $m ) { $by_contact[ (int) $m->contact_id ][] = array( 'id' => (int) $m->id, 'name' => $m->name, ); } foreach ( $rows as $row ) { $groups = $by_contact[ (int) $row->id ] ?? array(); $row->groups = $groups; $row->group_ids = array_map( static fn( $g ) => $g['id'], $groups ); } return $rows; } /** * Give each row an avatar_url from WordPress's own avatar function, so the * site's "Show Avatars" setting and avatar plugins apply and the browser * never hashes an address. Empty when avatars are off; the screen then * shows initials. The 404 default makes a missing picture fall back too. * * @param array $rows Subscriber rows (each with an ->email). * @return array The same rows, each with ->avatar_url. */ private function attach_avatars( $rows ) { $show = (bool) get_option( 'show_avatars' ); foreach ( $rows as $row ) { $url = $show ? get_avatar_url( (string) $row->email, array( 'size' => 64, // A transparent image when there is no picture, so a page of // subscribers never fills the console with 404s; the screen // draws the initials behind it. 'default' => 'blank', ) ) : ''; $row->avatar_url = $url ? $url : ''; } return $rows; } /** * Drop the columns a response never needs: the unsubscribe token acts on * the contact's behalf, and the confirm hash belongs to the confirm link. * * @param array $rows Subscriber rows. * @return array The same rows. */ private function without_secrets( $rows ) { foreach ( $rows as $row ) { unset( $row->unsubscribe_token, $row->confirm_hash ); } return $rows; } /** * POST /contacts/bulk — apply one action to a set of contacts. * * Body: action (delete|add_to_group|remove_from_group|set_status), and * either ids (int[]) or all_matching true with filter (the list's filter: * status, group_ids, source, customer_type, search, engagement) or * segment_id. group_id/group_ids name the groups to add to or remove * from; status the status to set. Each action fires the same hooks as its * single-item endpoint, and `updated` counts the contacts that changed. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function bulk_action( $request ) { // Many people at once: no tag welcome emails while this runs. $hush = Mailpuff_Tag_Emails::hush(); global $wpdb; $action = sanitize_key( (string) $request->get_param( 'action' ) ); if ( ! in_array( $action, array( 'delete', 'add_to_group', 'remove_from_group', 'set_status' ), true ) ) { return $this->error( 'invalid_action', __( 'Unknown bulk action.', 'mailpuff' ), 400 ); } $gids = array(); if ( 'add_to_group' === $action || 'remove_from_group' === $action ) { $gids = Mailpuff_Group::existing_ids( Mailpuff_Contact_Service::parse_group_ids( $request ) ); if ( empty( $gids ) ) { return $this->error( 'no_group', __( 'Choose a tag first.', 'mailpuff' ), 400 ); } } $status = ''; if ( 'set_status' === $action ) { $status = sanitize_text_field( (string) $request->get_param( 'status' ) ); if ( ! in_array( $status, Mailpuff_Schema::statuses(), true ) ) { return $this->error( 'invalid_status', __( 'Invalid status.', 'mailpuff' ), 400 ); } } if ( rest_sanitize_boolean( $request->get_param( 'all_matching' ) ) ) { $segment_id = absint( $request->get_param( 'segment_id' ) ); if ( $segment_id ) { $filter = $this->segment_filter( $segment_id ); if ( null === $filter ) { return $this->error( 'not_found', __( 'Segment not found.', 'mailpuff' ), 404 ); } } else { $raw = $request->get_param( 'filter' ); $filter = Mailpuff_Contact_Filter::normalize( is_array( $raw ) ? $raw : array() ); } $ids = $this->matching_ids( $filter ); } else { $ids = array_values( array_unique( array_filter( array_map( 'absint', (array) $request->get_param( 'ids' ) ) ) ) ); } if ( empty( $ids ) ) { return $this->error( 'no_ids', __( 'No contacts were selected.', 'mailpuff' ), 400 ); } $table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $updated = 0; $now = current_time( 'mysql' ); foreach ( $ids as $id ) { $changed = false; switch ( $action ) { case 'delete': $email = $wpdb->get_var( $wpdb->prepare( 'SELECT email FROM %i WHERE id = %d', $table, $id ) ); if ( null !== $email ) { Mailpuff_Contact::purge( $id ); /** This action is documented in includes/api/class-contacts-controller.php */ do_action( 'mailpuff_contact_deleted', $id, $email ); $changed = true; } break; case 'add_to_group': foreach ( $gids as $gid ) { $changed = Mailpuff_Contact_Service::add_to_group( $id, $gid, $now ) || $changed; } break; case 'remove_from_group': foreach ( $gids as $gid ) { $changed = Mailpuff_Contact_Service::remove_from_group( $id, $gid ) || $changed; } break; case 'set_status': if ( Mailpuff_Contact::set_status( $id, $status ) ) { do_action( 'mailpuff_contact_updated', $id, array( 'status' => $status ) ); $changed = true; } break; } if ( $changed ) { ++$updated; } } return $this->success( array( 'updated' => $updated, 'action' => $action, ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function get_item( $request ) { global $wpdb; $id = absint( $request->get_param( 'id' ) ); $table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ) ); if ( ! $row ) { return $this->error( 'not_found', __( 'Contact not found.', 'mailpuff' ), 404 ); } // The subscriber's page shows their groups, as the list does. $rows = $this->without_secrets( $this->attach_avatars( $this->attach_groups( array( $row ) ) ) ); // How they get new posts, and whether their opens and clicks count. $contact = $rows[0]; $contact->new_posts = count( Mailpuff_Post_Emails::offered() ) > 1 ? Mailpuff_Post_Emails::choice_of( $id ) : null; $contact->tracking_mode = Mailpuff_Tracking_Consent::mode(); $contact->tracking_consent = Mailpuff_Tracking_Consent::given_at( $id ); $contact->tracking_consent_source = (string) Mailpuff_Schema::get_meta( $id, Mailpuff_Tracking_Consent::SOURCE_META ); // Their custom fields, and their account on this site when they have one. $contact->fields = (object) Mailpuff_Fields::values_of( $id ); $contact->site_user = Mailpuff_Site_Users::account( (string) $contact->email ); return $this->success( $contact ); } /** * DELETE /contacts/:id/tracking-consent. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function withdraw_tracking( $request ) { $id = absint( $request->get_param( 'id' ) ); if ( ! Mailpuff_Contact::find( $id ) ) { return $this->error( 'not_found', __( 'Contact not found.', 'mailpuff' ), 404 ); } return $this->success( array( 'withdrawn' => Mailpuff_Tracking_Consent::withdraw( $id ) ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function create_item( $request ) { global $wpdb; $email = sanitize_email( $request->get_param( 'email' ) ); if ( ! is_email( $email ) ) { return $this->error( 'invalid_email', __( 'A valid email address is required.', 'mailpuff' ) ); } $table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $exists = $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE email = %s', $table, $email ) ); if ( $exists ) { return $this->error( 'duplicate_email', __( 'A contact with this email already exists.', 'mailpuff' ), 409 ); } $now = current_time( 'mysql' ); $status = sanitize_text_field( (string) $request->get_param( 'status' ) ); if ( '' !== $status && ! in_array( $status, Mailpuff_Schema::statuses(), true ) ) { return $this->error( 'invalid_status', __( 'That contact status is not valid.', 'mailpuff' ), 400 ); } $data = array( 'email' => $email, 'first_name' => sanitize_text_field( $request->get_param( 'first_name' ) ), 'last_name' => sanitize_text_field( $request->get_param( 'last_name' ) ), 'status' => $status ? $status : Mailpuff_Schema::SUBSCRIBER_SUBSCRIBED, 'customer_type' => sanitize_text_field( $request->get_param( 'customer_type' ) ), 'gross_revenue' => floatval( $request->get_param( 'gross_revenue' ) ), 'source' => sanitize_text_field( $request->get_param( 'source' ) ), 'unsubscribe_token' => wp_generate_password( 32, false ), 'email_hash' => Mailpuff_Schema::email_hash( $email ), 'created_at' => $now, 'updated_at' => $now, ); $formats = array( '%s', // email '%s', // first_name '%s', // last_name '%s', // status '%s', // customer_type '%f', // gross_revenue '%s', // source '%s', // unsubscribe_token '%s', // email_hash '%s', // created_at '%s', // updated_at ); $wpdb->insert( $table, $data, $formats ); if ( ! $wpdb->insert_id ) { return $this->error( 'create_failed', __( 'Failed to create contact.', 'mailpuff' ), 500 ); } $id = (int) $wpdb->insert_id; do_action( 'mailpuff_contact_created', $id, 'admin' ); foreach ( Mailpuff_Group::existing_ids( Mailpuff_Contact_Service::parse_group_ids( $request ) ) as $gid ) { Mailpuff_Contact_Service::add_to_group( $id, $gid, $now ); } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ) ); $rows = $this->without_secrets( $this->attach_groups( array( $row ) ) ); return $this->success( $rows[0], 201 ); } /** * GET /contacts/export — the contacts a list filter (or a saved segment, * segment_id, or the rows ticked, ids) matches, as CSV: one row per * contact with their groups, consent and custom fields. The screen saves * `csv` as a file. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error { filename, count, csv } */ public function export_items( $request ) { $picked = array_values( array_unique( array_filter( array_map( 'absint', wp_parse_list( $request->get_param( 'ids' ) ) ) ) ) ); if ( $picked ) { $ids = $this->existing_ids( $picked ); return $this->success( array( 'filename' => 'mailpuff-subscribers-' . wp_date( 'Y-m-d' ) . '.csv', 'count' => count( $ids ), 'csv' => Mailpuff_Export_Service::contacts_csv( $ids ), ) ); } $name = 'subscribers'; $segment_id = absint( $request->get_param( 'segment_id' ) ); if ( $segment_id ) { $filter = $this->segment_filter( $segment_id ); if ( null === $filter ) { return $this->error( 'not_found', __( 'Segment not found.', 'mailpuff' ), 404 ); } $name = (string) $this->segment_name( $segment_id ); } else { $filter = $this->request_filter( $request ); $gids = $filter['group_ids']; if ( 1 === count( $gids ) && ! array_filter( array( $filter['status'], $filter['source'], $filter['customer_type'], $filter['search'], $filter['engagement'], $filter['fields'] ) ) ) { $group = Mailpuff_Group::find( $gids[0] ); $name = $group ? (string) $group->name : $name; } } $ids = $this->matching_ids( $filter ); $csv = Mailpuff_Export_Service::contacts_csv( $ids ); return $this->success( array( 'filename' => 'mailpuff-' . sanitize_title( $name ) . '-' . wp_date( 'Y-m-d' ) . '.csv', 'count' => count( $ids ), 'csv' => $csv, ) ); } /** * A segment's name. * * @param int $segment_id Segment id. * @return string|null */ private function segment_name( $segment_id ) { global $wpdb; $table = Mailpuff_Schema::table( Mailpuff_Schema::SEGMENTS ); return $wpdb->get_var( $wpdb->prepare( 'SELECT name FROM %i WHERE id = %d', $table, (int) $segment_id ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function update_item( $request ) { global $wpdb; $id = absint( $request->get_param( 'id' ) ); $table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $existing = $wpdb->get_row( $wpdb->prepare( 'SELECT id, status FROM %i WHERE id = %d', $table, $id ) ); if ( ! $existing ) { return $this->error( 'not_found', __( 'Contact not found.', 'mailpuff' ), 404 ); } $allowed_fields = array( 'email', 'first_name', 'last_name', 'status', 'customer_type', 'gross_revenue', 'source', ); $data = array(); $formats = array(); foreach ( $allowed_fields as $field ) { $value = $request->get_param( $field ); if ( null === $value ) { continue; } switch ( $field ) { case 'email': $sanitized = sanitize_email( $value ); if ( ! is_email( $sanitized ) ) { return $this->error( 'invalid_email', __( 'A valid email address is required.', 'mailpuff' ) ); } // Check duplicate if email changed. $dup = $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE email = %s AND id != %d', $table, $sanitized, $id ) ); if ( $dup ) { return $this->error( 'duplicate_email', __( 'A contact with this email already exists.', 'mailpuff' ), 409 ); } $data[ $field ] = $sanitized; $formats[] = '%s'; $data['email_hash'] = Mailpuff_Schema::email_hash( $sanitized ); $formats[] = '%s'; break; case 'gross_revenue': $data[ $field ] = floatval( $value ); $formats[] = '%f'; break; case 'status': $status = sanitize_text_field( $value ); if ( ! in_array( $status, Mailpuff_Schema::statuses(), true ) ) { return $this->error( 'invalid_status', __( 'That contact status is not valid.', 'mailpuff' ), 400 ); } $data[ $field ] = $status; $formats[] = '%s'; break; default: $data[ $field ] = sanitize_text_field( $value ); $formats[] = '%s'; break; } } // Custom field values: key => value, '' clears one. Checked before // anything is stored, so a bad value changes nothing. $values = $request->get_param( 'fields' ); if ( null !== $values && ! is_array( $values ) ) { return $this->error( 'invalid_fields', __( 'Send fields as key and value pairs.', 'mailpuff' ) ); } foreach ( (array) $values as $key => $value ) { $field = Mailpuff_Fields::find( (string) $key ); $clean = $field ? Mailpuff_Fields::clean( $field, $value ) : null; if ( ! $field || is_wp_error( $clean ) ) { return $field ? $this->error( 'invalid_value', $clean->get_error_message(), 400 ) /* translators: %s: a field key. */ : $this->error( 'unknown_field', sprintf( __( 'There is no field "%s".', 'mailpuff' ), (string) $key ), 400 ); } } if ( empty( $data ) && empty( $values ) ) { return $this->error( 'no_data', __( 'No fields to update.', 'mailpuff' ) ); } if ( $data ) { $data['updated_at'] = current_time( 'mysql' ); $formats[] = '%s'; $wpdb->update( $table, $data, array( 'id' => $id ), $formats, array( '%d' ) ); do_action( 'mailpuff_contact_updated', $id, $data ); if ( isset( $data['status'] ) ) { Mailpuff_Contact::status_changed( $id, (string) $existing->status, (string) $data['status'] ); } } if ( $values ) { Mailpuff_Fields::set_values( $id, $values ); } $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ) ); $this->without_secrets( $this->attach_avatars( array( $row ) ) ); $row->fields = (object) Mailpuff_Fields::values_of( $id ); return $this->success( $row ); } /** * GET /contacts/:id/activity — what happened with this subscriber, newest * first ({@see Mailpuff_Timeline}). * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function get_activity( $request ) { $id = absint( $request->get_param( 'id' ) ); if ( ! Mailpuff_Contact::find( $id ) ) { return $this->error( 'not_found', __( 'Contact not found.', 'mailpuff' ), 404 ); } $limit = absint( $request->get_param( 'limit' ) ); return $this->success( Mailpuff_Timeline::events( $id, $limit ? $limit : Mailpuff_Timeline::LIMIT ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function delete_item( $request ) { global $wpdb; $id = absint( $request->get_param( 'id' ) ); $table = Mailpuff_Schema::table( Mailpuff_Schema::SUBSCRIBERS ); $existing = $wpdb->get_row( $wpdb->prepare( 'SELECT id, email FROM %i WHERE id = %d', $table, $id ) ); if ( ! $existing ) { return $this->error( 'not_found', __( 'Contact not found.', 'mailpuff' ), 404 ); } Mailpuff_Contact::purge( $id ); /** * A contact was deleted, with its groups, fields, tracking and queue rows. * * @param int $id Contact ID (no longer in the table). * @param string $email The address it had. */ do_action( 'mailpuff_contact_deleted', $id, $existing->email ); return $this->success( array( 'deleted' => true ) ); } /** * POST /contacts/import — accept the uploaded CSV plus the chosen mapping, * options, rules and any newly defined custom fields, create an import job, * and kick off async (Action Scheduler) chunked processing. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function import_contacts( $request ) { global $wpdb; try { $files = $request->get_file_params(); if ( empty( $files['file'] ) || empty( $files['file']['tmp_name'] ) ) { return $this->error( 'no_file', __( 'No CSV file was uploaded.', 'mailpuff' ), 400 ); } $file = $files['file']; if ( ! empty( $file['error'] ) ) { return $this->error( 'upload_error', __( 'File upload failed.', 'mailpuff' ), 400 ); } // The name and the content: WordPress's own check, as the media // library makes for a CSV. $check = wp_check_filetype_and_ext( $file['tmp_name'], (string) $file['name'], array( 'csv' => 'text/csv' ) ); if ( 'csv' !== strtolower( pathinfo( $file['name'], PATHINFO_EXTENSION ) ) || 'csv' !== $check['ext'] ) { return $this->error( 'invalid_file', __( 'Only CSV files are supported.', 'mailpuff' ), 400 ); } // Decode the JSON sidecars sent alongside the file. $mapping = $this->decode_json_param( $request->get_param( 'mapping' ) ); $options = $this->decode_json_param( $request->get_param( 'options' ) ); $rules = $this->decode_json_param( $request->get_param( 'rules' ) ); $fields = $this->decode_json_param( $request->get_param( 'custom_fields' ) ); if ( ! in_array( 'email', array_values( (array) $mapping ), true ) ) { return $this->error( 'no_email_mapping', __( 'Map one column to "Email" before importing.', 'mailpuff' ), 400 ); } if ( is_array( $fields ) && ! empty( $fields ) ) { $this->register_custom_fields( $fields ); } // Move the upload into a private spot the job can read across requests. $stored = $this->store_upload( $file ); if ( is_wp_error( $stored ) ) { return $stored; } $started = $this->start_job( $stored, $mapping, $options, $rules ); return is_wp_error( $started ) ? $started : $this->success( $started, 201 ); } catch ( \Throwable $e ) { return $this->error( 'import_error', $e->getMessage(), 500 ); } } /** * Clean a stored CSV, make the import job and start it: the one way an * import begins, for an uploaded file and for another plugin's people. * * @param string $stored The CSV in the private imports folder (deleted here). * @param array $mapping Raw mapping. * @param array $options Raw options. * @param array $rules Raw rules. * @return array|WP_Error { job_id, total, duplicates, invalid }. */ private function start_job( $stored, $mapping, $options, $rules ) { global $wpdb; $mapping = $this->sanitize_mapping( $mapping ); $options = $this->sanitize_options( $options ); $rules = $this->sanitize_rules( $rules ); // Each address once (the strictest row wins), rows without a usable // address dropped; the job reads the cleaned copy. $ready = preg_replace( '/\.csv$/', '-ready.csv', $stored ); $prepared = Mailpuff_Import_Sync::prepare_file( $stored, $ready, $mapping, $options, $rules ); wp_delete_file( $stored ); if ( is_wp_error( $prepared ) ) { wp_delete_file( $ready ); return $this->error( $prepared->get_error_code(), $prepared->get_error_message(), 400 ); } $total = (int) $prepared['rows']; // Kept with the job so its progress can report them. $options['prepared'] = array( 'duplicates' => (int) $prepared['duplicates'], 'invalid' => (int) $prepared['invalid'], ); $table = Mailpuff_Schema::table( Mailpuff_Schema::IMPORT_JOBS ); $now = current_time( 'mysql' ); $wpdb->insert( $table, array( 'file_path' => $ready, 'mapping' => wp_json_encode( $mapping ), 'options' => wp_json_encode( $options ), 'rules' => wp_json_encode( $rules ), 'total' => $total, 'status' => 'pending', 'created_at' => $now, 'updated_at' => $now, ), array( '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s' ) ); $job_id = (int) $wpdb->insert_id; if ( ! $job_id ) { wp_delete_file( $ready ); return $this->error( 'job_error', __( 'Could not start the import.', 'mailpuff' ), 500 ); } Mailpuff_Import_Job::start( $job_id ); return array( 'job_id' => $job_id, 'total' => $total, 'duplicates' => $options['prepared']['duplicates'], 'invalid' => $options['prepared']['invalid'], ); } /** * GET /contacts/import/sources — the other newsletter plugins on this * site Mailpuff can import from, each with its dry run. * * @return WP_REST_Response */ public function get_import_sources() { return $this->success( Mailpuff_Import_Sources::available() ); } /** * POST /contacts/import/sources/{source} — import another plugin's * people: its tables are read (never changed) into a CSV the import job * takes, like an upload. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error { job_id, total, duplicates, invalid }. */ public function import_from_source( $request ) { $dir = self::imports_dir(); if ( is_wp_error( $dir ) ) { return $dir; } $path = trailingslashit( $dir ) . 'import-' . wp_generate_password( 32, false ) . '.csv'; $exported = Mailpuff_Import_Sources::export( sanitize_key( (string) $request->get_param( 'source' ) ), $path ); if ( is_wp_error( $exported ) ) { wp_delete_file( $path ); return $exported; } $started = $this->start_job( $path, $exported['mapping'], $exported['options'], array() ); return is_wp_error( $started ) ? $started : $this->success( $started, 201 ); } /** * POST /contacts/import/mailchimp — Mailchimp's audience export (a zip) * as one CSV, a status column first, for the Import page to read like * any other file. Nothing is imported or stored. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error { csv, files, rows }. */ public function unpack_mailchimp( $request ) { $files = $request->get_file_params(); $file = $files['file'] ?? array(); if ( empty( $file['tmp_name'] ) || ! empty( $file['error'] ) || ! is_uploaded_file( $file['tmp_name'] ) ) { return $this->error( 'no_file', __( 'No zip file was uploaded.', 'mailpuff' ), 400 ); } $check = wp_check_filetype_and_ext( $file['tmp_name'], (string) $file['name'], array( 'zip' => 'application/zip' ) ); if ( 'zip' !== strtolower( pathinfo( (string) $file['name'], PATHINFO_EXTENSION ) ) || 'zip' !== $check['ext'] ) { return $this->error( 'invalid_file', __( 'Choose the zip file Mailchimp sent you.', 'mailpuff' ), 400 ); } $out = Mailpuff_Import_Sources::mailchimp_zip( $file['tmp_name'] ); return is_wp_error( $out ) ? $out : $this->success( $out ); } /** * The private folder imports wait in, made and closed to the web. * * @return string|WP_Error */ private static function imports_dir() { $uploads = wp_upload_dir(); if ( ! empty( $uploads['error'] ) ) { return new WP_Error( 'upload_dir', __( 'Uploads directory is not writable.', 'mailpuff' ), array( 'status' => 500 ) ); } $dir = trailingslashit( $uploads['basedir'] ) . 'mailpuff-imports'; if ( ! wp_mkdir_p( $dir ) ) { return new WP_Error( 'upload_dir', __( 'Could not create the import directory.', 'mailpuff' ), array( 'status' => 500 ) ); } self::close_to_the_web( $dir ); return $dir; } /** * GET /contacts/import/{id} — live progress for an import job. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function get_import_status( $request ) { global $wpdb; $id = absint( $request->get_param( 'id' ) ); $table = Mailpuff_Schema::table( Mailpuff_Schema::IMPORT_JOBS ); $job = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ) ); if ( ! $job ) { return $this->error( 'not_found', __( 'Import job not found.', 'mailpuff' ), 404 ); } // Self-heal a stalled job: if it's still processing but nothing is queued // (e.g. a chunk fatalled), polling reschedules the next chunk. if ( in_array( $job->status, array( 'pending', 'processing' ), true ) ) { Mailpuff_Import_Job::maybe_resume( $id ); } $errors = json_decode( (string) $job->errors, true ); $options = json_decode( (string) $job->options, true ); $prepared = is_array( $options ) && isset( $options['prepared'] ) ? (array) $options['prepared'] : array(); return $this->success( array( 'status' => $job->status, 'total' => (int) $job->total, 'processed' => (int) $job->processed, 'imported' => (int) $job->imported, 'updated' => (int) $job->updated, 'skipped' => (int) $job->skipped, 'failed' => (int) $job->failed, 'duplicates' => (int) ( $prepared['duplicates'] ?? 0 ), 'invalid' => (int) ( $prepared['invalid'] ?? 0 ), 'errors' => is_array( $errors ) ? $errors : array(), ) ); } /** * POST /contacts/import/check — which of these addresses are already * contacts (with their status) and which are suppressed, for the import * preview. The import itself decides again on the server. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public function check_import( $request ) { $result = Mailpuff_Import_Sync::lookup( (array) $request->get_param( 'emails' ) ); return $this->success( array( 'contacts' => (object) $result['contacts'], 'suppressed' => $result['suppressed'], ) ); } /** * GET /custom-fields — the fields; with `described`, each with its merge * tag, conditions, how many have a value and what uses it (Settings › * Fields). * * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public function get_custom_fields( $request ) { return $this->success( rest_sanitize_boolean( $request->get_param( 'described' ) ) ? Mailpuff_Fields::described() : Mailpuff_Fields::all() ); } /** * POST /custom-fields — make a field: `label`, `type`, optional `key`. * Answers with every field, as GET does. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function create_custom_field( $request ) { $field = Mailpuff_Fields::create( (string) $request->get_param( 'label' ), '' !== (string) $request->get_param( 'type' ) ? (string) $request->get_param( 'type' ) : 'text', (string) $request->get_param( 'key' ) ); if ( is_wp_error( $field ) ) { return $field; } return $this->success( Mailpuff_Fields::all(), 201 ); } /** * PUT /custom-fields/:key — rename a field (its key and type stay). * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function update_custom_field( $request ) { $field = Mailpuff_Fields::rename( (string) $request->get_param( 'key' ), (string) $request->get_param( 'label' ) ); return is_wp_error( $field ) ? $field : $this->success( $field ); } /** * DELETE /custom-fields/:key — delete a field and its values; refused * (409, with what uses it) while a segment or an unsent email uses it. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function delete_custom_field( $request ) { $out = Mailpuff_Fields::delete( (string) $request->get_param( 'key' ) ); return is_wp_error( $out ) ? $out : $this->success( $out ); } /** * Make the fields an import maps to that do not exist yet. One that * cannot be made (a reserved key) is skipped; its column is not imported. * * @param array $incoming List of {key,label,type}. */ private function register_custom_fields( $incoming ) { foreach ( (array) $incoming as $f ) { $key = is_array( $f ) ? sanitize_key( (string) ( $f['key'] ?? '' ) ) : ''; if ( '' === $key || '_' === $key[0] || Mailpuff_Fields::find( $key ) ) { continue; } Mailpuff_Fields::create( (string) ( $f['label'] ?? $key ), (string) ( $f['type'] ?? 'text' ), $key ); } } /** * Decode a possibly-JSON request param into an array. * * @param mixed $param Raw param (JSON string or already-decoded array). * @return array */ private function decode_json_param( $param ) { if ( is_array( $param ) ) { return $param; } if ( is_string( $param ) && '' !== $param ) { $decoded = json_decode( $param, true ); return is_array( $decoded ) ? $decoded : array(); } return array(); } /** * Sanitize the column mapping: header => ('email'|core field|'meta:'|''). * * @param array $mapping Raw mapping. * @return array */ private function sanitize_mapping( $mapping ) { $clean = array(); foreach ( (array) $mapping as $header => $target ) { $header = sanitize_text_field( (string) $header ); $target = (string) $target; if ( 0 === strpos( $target, 'meta:' ) ) { $target = 'meta:' . sanitize_key( substr( $target, 5 ) ); } else { $target = in_array( $target, Mailpuff_Import_Sync::CORE_FIELDS, true ) ? $target : ''; } $clean[ $header ] = $target; } return $clean; } /** * Sanitize import options. * * @param array $options Raw options. * @return array */ private function sanitize_options( $options ) { return array( 'skip_duplicates' => ! empty( $options['skip_duplicates'] ), 'skip_suspicious' => ! empty( $options['skip_suspicious'] ), 'default_status' => Mailpuff_Schema::normalize_status( $options['default_status'] ?? '' ), 'default_source' => sanitize_text_field( $options['default_source'] ?? 'csv_import' ), // The tags everyone in the file gets (each also gets the tags of // a column matched to Tags, and of the rules). 'group_ids' => self::id_list( $options['group_ids'] ?? array() ), // A detected export's own status words (Mailpuff statuses only), // the stop status a whole file gives, and which preset it was. 'status_map' => Mailpuff_Import_Sync::sanitize_status_map( $options['status_map'] ?? array() ), 'file_status' => Mailpuff_Import_Sync::sanitize_file_status( $options['file_status'] ?? '' ), 'preset' => substr( sanitize_key( (string) ( $options['preset'] ?? '' ) ), 0, 40 ), // The separator the browser's parser found (the job reads commas). 'delimiter' => Mailpuff_Import_Sync::sanitize_delimiter( $options['delimiter'] ?? ',' ), ); } /** * Positive ids, each once, at most 50. * * @param mixed $ids Raw ids. * @return int[] */ private static function id_list( $ids ) { return array_slice( array_values( array_unique( array_filter( array_map( 'absint', (array) $ids ) ) ) ), 0, 50 ); } /** * Sanitize conditional rules. * * @param array $rules Raw rules. * @return array */ private function sanitize_rules( $rules ) { $clean = array(); $operators = array( 'equals', 'not_equals', 'contains', 'is_empty', 'is_not_empty', 'greater_than' ); $actions = array( 'add_to_group', 'set_status', 'set_source' ); foreach ( (array) $rules as $rule ) { $operator = isset( $rule['operator'] ) ? (string) $rule['operator'] : ''; $action = isset( $rule['action'] ) ? (string) $rule['action'] : ''; if ( ! in_array( $operator, $operators, true ) || ! in_array( $action, $actions, true ) ) { continue; } $clean[] = array( 'column' => sanitize_text_field( $rule['column'] ?? '' ), 'operator' => $operator, 'value' => sanitize_text_field( $rule['value'] ?? '' ), 'action' => $action, 'action_value' => sanitize_text_field( $rule['action_value'] ?? '' ), ); } return $clean; } /** * Move the uploaded CSV into a private uploads subdir keyed by a random name. * * @param array $file One entry from get_file_params(). * @return string|WP_Error Stored absolute path, or error. */ private function store_upload( $file ) { $dir = self::imports_dir(); if ( is_wp_error( $dir ) ) { return $dir; } // Only a file PHP received in this request, never a path from elsewhere. if ( empty( $file['tmp_name'] ) || ! is_uploaded_file( $file['tmp_name'] ) ) { return $this->error( 'not_uploaded', __( 'The file was not uploaded. Choose the CSV file again.', 'mailpuff' ), 400 ); } // A name nobody can guess: nginx ignores the .htaccess guard, so on nginx // the file is only as private as its name (about 190 random bits). $dest = trailingslashit( $dir ) . 'import-' . wp_generate_password( 32, false ) . '.csv'; // PHP removes the temporary upload when the request ends, so a copy is enough. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged, WordPress.WP.AlternativeFunctions.file_system_operations_copy if ( ! @copy( $file['tmp_name'], $dest ) ) { return $this->error( 'store_failed', __( 'Could not store the uploaded file.', 'mailpuff' ), 500 ); } return $dest; } /** * Keep the imports folder out of reach from the web while a CSV waits in * it: an index stops a listing of the file names, and Apache refuses * every read. Written once. * * @param string $dir Absolute path of the folder. * @return void */ public static function close_to_the_web( $dir ) { $guards = array( 'index.html' => '', '.htaccess' => "\nRequire all denied\n\n\nDeny from all\n\n", ); foreach ( $guards as $name => $body ) { $path = trailingslashit( $dir ) . $name; if ( ! file_exists( $path ) ) { // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_file_put_contents -- a fixed guard file in the plugin's own uploads folder. file_put_contents( $path, $body ); } } } }