namespace, '/campaigns', 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' ), 'search' => array( 'sanitize_callback' => 'sanitize_text_field' ), 'page' => array( 'sanitize_callback' => 'absint' ), 'per_page' => array( 'sanitize_callback' => 'absint' ), 'with_counts' => 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, '/campaigns/(?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, '/campaigns/audience-count', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_audience_count' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'audience_id' => array( 'sanitize_callback' => 'absint' ), ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/send', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'send_campaign' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/stop', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'stop_send' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/resume', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'resume_send' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/cancel', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'cancel_send' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/resend-unopened', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'resend_unopened' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/stats', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_stats' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/progress', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_progress' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); // Who got it and what they did (Mailpuff_Recipients). register_rest_route( $this->namespace, '/campaigns/(?P\d+)/recipients', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'get_recipients' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/recipients/export', array( 'methods' => WP_REST_Server::READABLE, 'callback' => array( $this, 'export_recipients' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); // The web version: on or off, any time (Mailpuff_Web_Version). register_rest_route( $this->namespace, '/campaigns/(?P\d+)/web', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'set_web' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/test', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'send_test' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/schedule', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'schedule_campaign' ), 'permission_callback' => array( $this, 'check_permission' ), 'args' => array( 'scheduled_at' => array( 'required' => true, 'sanitize_callback' => 'sanitize_text_field', ), ), ) ); register_rest_route( $this->namespace, '/campaigns/(?P\d+)/unschedule', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this, 'unschedule_campaign' ), 'permission_callback' => array( $this, 'check_permission' ), ) ); } /** * POST /campaigns/:id/unschedule — cancel a booked launch, back to draft. * * The swap only fires while the campaign is still 'scheduled', so a launch * that already started (or a campaign that is not scheduled) answers 409. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function unschedule_campaign( $request ) { global $wpdb; $id = absint( $request->get_param( 'id' ) ); $table = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGNS ); $exists = $wpdb->get_var( $wpdb->prepare( 'SELECT id FROM %i WHERE id = %d', $table, $id ) ); if ( ! $exists ) { return $this->error( 'not_found', __( 'Campaign not found.', 'mailpuff' ), 404 ); } // Drop the booked launch first, so it can't fire between the swap below // and the unschedule. The launch itself only starts a campaign that is // still 'scheduled', so a cancel that wins the swap always holds. Mailpuff_Campaign_Service::unschedule( $id ); $reverted = $wpdb->query( $wpdb->prepare( 'UPDATE %i SET status = %s, updated_at = %s WHERE id = %d AND status = %s', $table, Mailpuff_Schema::STATUS_DRAFT, current_time( 'mysql' ), $id, Mailpuff_Schema::STATUS_SCHEDULED ) ); if ( 1 !== (int) $reverted ) { return $this->error( 'not_scheduled', __( 'This campaign is not scheduled.', 'mailpuff' ), 409 ); } Mailpuff_Campaign_Service::clear_error( $id ); return $this->success( array( 'unscheduled' => true ) ); } /** * POST /campaigns/:id/schedule — book a future launch. * * `scheduled_at` is a naive site-local datetime ("Y-m-d H:i" or * "Y-m-d H:i:s") — exactly the wall-clock time the user picked. It is read * in the site's timezone ({@see wp_timezone()}), converted to a UTC timestamp * for Action Scheduler, and stored as-is (site-local) for display. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function schedule_campaign( $request ) { $id = absint( $request->get_param( 'id' ) ); $raw = trim( (string) $request->get_param( 'scheduled_at' ) ); // Accept "Y-m-d H:i", "Y-m-d H:i:s" or the HTML "Y-m-dTH:i" form. $normalized = str_replace( 'T', ' ', $raw ); $dt = date_create_immutable( $normalized, wp_timezone() ); if ( ! $dt ) { return $this->error( 'bad_time', __( 'That date/time could not be read.', 'mailpuff' ), 400 ); } $timestamp = $dt->getTimestamp(); if ( $timestamp < time() + 60 ) { return $this->error( 'past_time', __( 'Pick a time at least a minute in the future.', 'mailpuff' ), 422 ); } $local_at = $dt->format( 'Y-m-d H:i:s' ); $service = new Mailpuff_Campaign_Service(); $result = $service->schedule( $id, $timestamp, $local_at ); if ( is_wp_error( $result ) ) { return $result; } return $this->success( array( 'scheduled' => true, 'scheduled_at' => $local_at, ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function get_items( $request ) { global $wpdb; $pagination = $this->get_pagination( $request ); $status = sanitize_text_field( $request->get_param( 'status' ) ); $search = sanitize_text_field( $request->get_param( 'search' ) ); $table = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGNS ); // The system emails (confirmation, welcome, the automatic emails' templates) // are rows of this table, but they are edited in Settings, not listed as campaigns. $where = 'WHERE ' . Mailpuff_System_Emails::not_system_sql(); $params = array( $table ); if ( $status && 'all' !== $status ) { $where .= ' AND status = %s'; $params[] = $status; } if ( $search ) { $like = '%' . $wpdb->esc_like( $search ) . '%'; $where .= ' AND (title LIKE %s OR subject LIKE %s)'; $params[] = $like; $params[] = $like; } $total = $this->count_rows( 'SELECT COUNT(*) FROM %i ' . $where, $params ); $rows = $this->paginated_query( 'SELECT * FROM %i ' . $where . ' ORDER BY created_at DESC', $params, $pagination ); $rows = $this->attach_stats( $rows ); $extra = array(); if ( rest_sanitize_boolean( $request->get_param( 'with_counts' ) ) ) { $extra['counts'] = $this->status_counts( 'SELECT status, COUNT(*) AS c FROM %i WHERE ' . Mailpuff_System_Emails::not_system_sql() . ' GROUP BY status', array( $table ) ); } return $this->paginated_response( $rows, $total, $pagination, $extra ); } /** * Attach per-campaign engagement stats to a page of campaign rows so the list * can show real Recipients / Open / Click figures (not hardcoded dashes). Two * grouped queries for the whole page — no N+1. * * @param array $rows Campaign rows. * @return array Same rows with a ->stats object each. */ private function attach_stats( array $rows ) { global $wpdb; if ( empty( $rows ) ) { return $rows; } $ids = array_map( static function ( $r ) { return (int) $r->id; }, $rows ); $in = implode( ',', array_fill( 0, count( $ids ), '%d' ) ); $sends_table = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGN_SENDS ); $tracking_table = Mailpuff_Schema::table( Mailpuff_Schema::TRACKING ); // Recipients + delivered per campaign. // phpcs:disable 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. $send_rows = $wpdb->get_results( $wpdb->prepare( "SELECT campaign_id, SUM(total_recipients) AS recipients, SUM(sent_count) AS delivered FROM %i WHERE campaign_id IN ($in) GROUP BY campaign_id", $sends_table, ...$ids ) ); // Unique opens + clicks per campaign (tracking joined to its send batch). $eng_rows = $wpdb->get_results( $wpdb->prepare( "SELECT cs.campaign_id AS campaign_id, SUM(CASE WHEN t.opened_at IS NOT NULL THEN 1 ELSE 0 END) AS opened, SUM(CASE WHEN t.click_count > 0 THEN 1 ELSE 0 END) AS clicked FROM %i t JOIN %i cs ON cs.id = t.batch_id WHERE cs.campaign_id IN ($in) GROUP BY cs.campaign_id", $tracking_table, $sends_table, ...$ids ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber $by = array(); foreach ( (array) $send_rows as $r ) { $by[ (int) $r->campaign_id ] = array( 'recipients' => (int) $r->recipients, 'delivered' => (int) $r->delivered, 'opened' => 0, 'clicked' => 0, ); } foreach ( (array) $eng_rows as $r ) { $cid = (int) $r->campaign_id; if ( ! isset( $by[ $cid ] ) ) { $by[ $cid ] = array( 'recipients' => 0, 'delivered' => 0, ); } $by[ $cid ]['opened'] = (int) $r->opened; $by[ $cid ]['clicked'] = (int) $r->clicked; } foreach ( $rows as $row ) { $s = $by[ (int) $row->id ] ?? array( 'recipients' => 0, 'delivered' => 0, 'opened' => 0, 'clicked' => 0, ); $denom = $s['delivered'] > 0 ? $s['delivered'] : 0; $row->stats = array( 'recipients' => $s['recipients'], 'delivered' => $s['delivered'], 'opened' => $s['opened'], 'clicked' => $s['clicked'], 'open_rate' => $denom ? round( $s['opened'] / $denom * 100, 1 ) : null, 'click_rate' => $denom ? round( $s['clicked'] / $denom * 100, 1 ) : null, ); } return $rows; } /** * @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::CAMPAIGNS ); $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ) ); if ( ! $row ) { return $this->error( 'not_found', __( 'Campaign not found.', 'mailpuff' ), 404 ); } $row->web_version = Mailpuff_Web_Version::wanted( (int) $row->id ); $row->web_url = Mailpuff_Web_Version::url( (int) $row->id ); $why = Mailpuff_Send_Guard::why( (int) $row->id ); $row->paused_reason = Mailpuff_Schema::STATUS_PAUSED === (string) $row->status && $why ? $why['message'] : ''; return $this->success( $row ); } /** * GET /campaigns//recipients?filter=&page=&search=: one page of a * list (sent, opened, clicked, not_opened, unsubscribed, bounced) and * every list's size. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function get_recipients( $request ) { $id = absint( $request['id'] ); $filter = (string) $request->get_param( 'filter' ); $filter = in_array( $filter, Mailpuff_Recipients::FILTERS, true ) ? $filter : 'sent'; if ( ! Mailpuff_Campaign::find( $id ) ) { return $this->error( 'not_found', __( 'Campaign not found.', 'mailpuff' ), 404 ); } return $this->success( array( 'counts' => Mailpuff_Recipients::counts( $id ) ) + Mailpuff_Recipients::page( $id, $filter, max( 1, (int) $request->get_param( 'page' ) ), (string) $request->get_param( 'search' ) ) ); } /** * GET /campaigns//recipients/export?filter=: a list as CSV, for the * screen to save. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error { filename, count, csv } */ public function export_recipients( $request ) { $id = absint( $request['id'] ); $campaign = Mailpuff_Campaign::find( $id ); $filter = (string) $request->get_param( 'filter' ); $filter = in_array( $filter, Mailpuff_Recipients::FILTERS, true ) ? $filter : 'sent'; if ( ! $campaign ) { return $this->error( 'not_found', __( 'Campaign not found.', 'mailpuff' ), 404 ); } $out = Mailpuff_Recipients::csv( $id, $filter ); $name = sanitize_title( '' !== (string) $campaign->title ? (string) $campaign->title : (string) $campaign->subject ); return $this->success( array( 'filename' => 'mailpuff-' . ( '' !== $name ? $name : 'campaign-' . $id ) . '-' . str_replace( '_', '-', $filter ) . '.csv', 'count' => $out['count'], 'csv' => $out['csv'], ) ); } /** * POST /campaigns//web { on }: show the campaign on the website, or * stop. A sent one goes up at once; one not sent yet when it goes out. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function set_web( $request ) { $result = Mailpuff_Web_Version::set( absint( $request['id'] ), rest_sanitize_boolean( $request->get_param( 'on' ) ) ); if ( is_wp_error( $result ) ) { return $this->error( $result->get_error_code(), $result->get_error_message(), 400 ); } return $this->success( $result ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function create_item( $request ) { global $wpdb; $table = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGNS ); $now = current_time( 'mysql' ); $title = sanitize_text_field( (string) $request->get_param( 'title' ) ); $subject = sanitize_text_field( (string) $request->get_param( 'subject' ) ); $blocks = $request->get_param( 'content_blocks' ); if ( is_array( $blocks ) ) { $blocks = wp_json_encode( $blocks ); } if ( empty( $blocks ) || ! is_array( json_decode( (string) $blocks, true ) ) ) { $blocks = '[]'; } $sql = $wpdb->prepare( 'INSERT INTO %i (user_id, title, subject, status, content_blocks, email_type, created_at, updated_at) VALUES (%d, %s, %s, %s, %s, %s, %s, %s)', $table, get_current_user_id(), $title, $subject, Mailpuff_Schema::STATUS_DRAFT, $blocks, 'html', $now, $now ); $result = $wpdb->query( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- prepared just above. if ( false === $result ) { return $this->error( 'create_failed', '' !== $wpdb->last_error ? $wpdb->last_error : 'Failed to create campaign.', 500 ); } $id = (int) $wpdb->insert_id; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ) ); return $this->success( $row, 201 ); } /** * @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::CAMPAIGNS ); $existing = $wpdb->get_row( $wpdb->prepare( 'SELECT id, type, status FROM %i WHERE id = %d', $table, $id ) ); if ( ! $existing ) { return $this->error( 'not_found', __( 'Campaign not found.', 'mailpuff' ), 404 ); } if ( Mailpuff_System_Emails::is_system_type( (string) $existing->type ) ) { return $this->error( 'system_email', __( 'The emails Mailpuff sends on its own are edited under Settings.', 'mailpuff' ), 422 ); } // Part of the list has it already: a change now would give the rest a // different email. if ( in_array( (string) $existing->status, array( Mailpuff_Schema::STATUS_SENDING, Mailpuff_Schema::STATUS_PAUSED ), true ) ) { return $this->error( 'locked', __( 'This campaign is going out to its list. Resume it or cancel the rest before you change it.', 'mailpuff' ), 409 ); } // Not 'status': it changes only through send, schedule and stop. $allowed_fields = array( 'title', 'subject', 'preheader', 'audience_id', 'audience_type', 'content_html', 'content_blocks', 'email_type', 'sender_name', 'sender_email', 'reply_to', ); $data = array(); $formats = array(); foreach ( $allowed_fields as $field ) { $value = $request->get_param( $field ); if ( null === $value ) { continue; } switch ( $field ) { case 'content_html': $data[ $field ] = Mailpuff_Email_Renderer::sanitize_html( $value ); $formats[] = '%s'; break; case 'content_blocks': $value = is_array( $value ) ? wp_json_encode( $value ) : (string) $value; if ( '' !== $value && ! is_array( json_decode( $value, true ) ) ) { return $this->error( 'invalid_content', __( 'The email content is not valid.', 'mailpuff' ), 400 ); } $data[ $field ] = $value; $formats[] = '%s'; break; case 'audience_id': $data[ $field ] = absint( $value ); $formats[] = '%d'; break; case 'audience_type': $allowed_types = array( '', 'all', 'group', 'segment', 'unopened', 'post_readers', 'digest_readers' ); $type = in_array( $value, $allowed_types, true ) ? $value : ''; $data[ $field ] = $type; $formats[] = '%s'; break; case 'sender_email': case 'reply_to': $data[ $field ] = sanitize_email( $value ); $formats[] = '%s'; break; default: $data[ $field ] = sanitize_text_field( $value ); $formats[] = '%s'; break; } } if ( empty( $data ) ) { return $this->error( 'no_data', __( 'No fields to update.', 'mailpuff' ) ); } $data['updated_at'] = current_time( 'mysql' ); $formats[] = '%s'; $wpdb->update( $table, $data, array( 'id' => $id ), $formats, array( '%d' ) ); $row = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ) ); return $this->success( $row ); } /** * @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::CAMPAIGNS ); $existing = $wpdb->get_row( $wpdb->prepare( 'SELECT id, type, status FROM %i WHERE id = %d', $table, $id ) ); if ( ! $existing ) { return $this->error( 'not_found', __( 'Campaign not found.', 'mailpuff' ), 404 ); } if ( Mailpuff_System_Emails::is_system_type( (string) $existing->type ) ) { return $this->error( 'system_email', __( 'The emails Mailpuff sends on its own cannot be deleted.', 'mailpuff' ), 422 ); } // Its batches would keep running (or wait for Resume) with no campaign. if ( Mailpuff_Schema::STATUS_SENDING === $existing->status ) { return $this->error( 'sending', __( 'This campaign is sending. Stop it and cancel the rest first, then delete it.', 'mailpuff' ), 409 ); } if ( Mailpuff_Schema::STATUS_PAUSED === $existing->status ) { return $this->error( 'paused', __( 'This campaign is stopped part-way. Resume it or cancel the rest first, then delete it.', 'mailpuff' ), 409 ); } // Drop any pending scheduled launch so it can't fire after deletion. Mailpuff_Campaign_Service::unschedule( $id ); Mailpuff_Campaign_Service::clear_error( $id ); $wpdb->delete( $table, array( 'id' => $id ), array( '%d' ) ); return $this->success( array( 'deleted' => true ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function send_campaign( $request ) { $campaign_id = absint( $request->get_param( 'id' ) ); $service = new Mailpuff_Campaign_Service(); $result = $service->launch( $campaign_id, false, true ); if ( is_wp_error( $result ) ) { return $result; } // Sending now supersedes a pending scheduled launch. Drop it only once // the launch has claimed the campaign, so a refused send keeps its schedule. Mailpuff_Campaign_Service::unschedule( $campaign_id ); return $this->success( array( 'batch_id' => $result ) ); } /** * POST /campaigns/:id/stop: stop a send part-way. Emails already handed to * the mailer still go out (nothing recalls those); everyone else waits for * Resume, or Cancel ends the send for good. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function stop_send( $request ) { $result = ( new Mailpuff_Campaign_Service() )->pause( absint( $request->get_param( 'id' ) ) ); if ( is_wp_error( $result ) ) { return $result; } return $this->success( array_merge( array( 'stopped' => true ), $result ) ); } /** * POST /campaigns/:id/resume: go on with a stopped send from where it * stopped; nobody gets the email twice. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function resume_send( $request ) { $result = ( new Mailpuff_Campaign_Service() )->resume( absint( $request->get_param( 'id' ) ) ); if ( is_wp_error( $result ) ) { return $result; } return $this->success( $result ); } /** * POST /campaigns/:id/cancel: end a sending or stopped send for good. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function cancel_send( $request ) { $result = ( new Mailpuff_Campaign_Service() )->cancel_rest( absint( $request->get_param( 'id' ) ) ); if ( is_wp_error( $result ) ) { return $result; } return $this->success( $result ); } /** * POST /campaigns/:id/resend-unopened: a new draft of this campaign for * exactly the people who were sent it and did not open it. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function resend_unopened( $request ) { $result = ( new Mailpuff_Campaign_Service() )->resend_unopened( absint( $request->get_param( 'id' ) ) ); if ( is_wp_error( $result ) ) { return $result; } return $this->success( $result, 201 ); } /** * GET /campaigns/audience-count — how many contacts a given audience would * receive, using the exact same selection as the real send (so the preview * matches reality). `audience_id` of 0 (or omitted) means all subscribers. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response */ public function get_audience_count( $request ) { $audience_id = absint( $request->get_param( 'audience_id' ) ); $audience_type = sanitize_text_field( (string) $request->get_param( 'audience_type' ) ); $service = new Mailpuff_Campaign_Service(); return $this->success( array( 'audience_id' => $audience_id, 'audience_type' => $audience_type, 'count' => $service->audience_count( $audience_id, $audience_type ), ) ); } /** * GET /campaigns/{id}/progress: counts, speed, finish time and whether the send stalled. * * @param WP_REST_Request $request Request. * @return WP_REST_Response|WP_Error */ public function get_progress( $request ) { $campaign_id = absint( $request->get_param( 'id' ) ); if ( ! Mailpuff_Campaign::find( $campaign_id ) ) { return new WP_Error( 'not_found', __( 'Campaign not found.', 'mailpuff' ), array( 'status' => 404 ) ); } return rest_ensure_response( Mailpuff_Progress::for_campaign( $campaign_id ) ); } /** * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function get_stats( $request ) { global $wpdb; $campaign_id = absint( $request->get_param( 'id' ) ); $sends_table = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGN_SENDS ); $tracking_table = Mailpuff_Schema::table( Mailpuff_Schema::TRACKING ); // Send stats. $send = $wpdb->get_row( $wpdb->prepare( 'SELECT SUM(total_recipients) AS total_recipients, SUM(sent_count) AS sent_count, SUM(failed_count) AS failed_count, MAX(status) AS batch_status FROM %i WHERE campaign_id = %d', $sends_table, $campaign_id ) ); $total = $send && $send->total_recipients ? (int) $send->total_recipients : 0; $sent_count = $send && $send->sent_count ? (int) $send->sent_count : 0; // Tracking stats — opens, clicks, unsubscribes. $batch_ids = $wpdb->get_col( $wpdb->prepare( 'SELECT id FROM %i WHERE campaign_id = %d', $sends_table, $campaign_id ) ); $opens = 0; $unique_opens = 0; $clicks = 0; $unique_clicks = 0; $unsubscribes = 0; $tracked = 0; if ( ! empty( $batch_ids ) ) { $id_placeholders = implode( ',', array_fill( 0, count( $batch_ids ), '%d' ) ); // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber -- $id_placeholders is a list of %d, one per batch id; the table is a %i. $tracking = $wpdb->get_row( $wpdb->prepare( "SELECT COALESCE(SUM(open_count), 0) AS total_opens, COALESCE(SUM(CASE WHEN opened_at IS NOT NULL THEN 1 ELSE 0 END), 0) AS unique_opens, COALESCE(SUM(click_count), 0) AS total_clicks, COALESCE(SUM(CASE WHEN click_count > 0 THEN 1 ELSE 0 END), 0) AS unique_clicks, COALESCE(SUM(CASE WHEN unsubscribed_at IS NOT NULL THEN 1 ELSE 0 END), 0) AS unsubscribes, COALESCE(SUM(tracked), 0) AS tracked FROM %i WHERE batch_id IN ($id_placeholders)", $tracking_table, ...$batch_ids ) ); // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber if ( $tracking ) { $opens = (int) $tracking->total_opens; $unique_opens = (int) $tracking->unique_opens; $clicks = (int) $tracking->total_clicks; $unique_clicks = (int) $tracking->unique_clicks; $unsubscribes = (int) $tracking->unsubscribes; $tracked = (int) $tracking->tracked; } } return $this->success( array( 'campaign_id' => $campaign_id, 'total_recipients' => $total, 'sent_count' => $sent_count, 'failed_count' => $send ? (int) $send->failed_count : 0, 'batch_status' => $send ? $send->batch_status : 'none', 'opens' => $opens, 'unique_opens' => $unique_opens, // Rates are of the people whose email was tracked: with "only // people who agreed", the others' opens are never counted. 'tracked_count' => $tracked, 'open_rate' => $tracked > 0 ? round( ( $unique_opens / $tracked ) * 100, 1 ) : 0, 'clicks' => $clicks, 'unique_clicks' => $unique_clicks, 'click_rate' => $tracked > 0 ? round( ( $unique_clicks / $tracked ) * 100, 1 ) : 0, 'unsubscribes' => $unsubscribes, 'links' => Mailpuff_Tracking::links( $campaign_id ), // Whether opens were tracked for the whole of a send (resend needs it). 'tracked' => (bool) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE campaign_id = %d AND source = %s AND open_tracking = 1', $sends_table, $campaign_id, 'broadcast' ) ), 'unopened' => ( new Mailpuff_Campaign_Service() )->unopened( $campaign_id ), ) ); } /** * Send a test email with the campaign's content. * * @param WP_REST_Request $request Request object. * @return WP_REST_Response|WP_Error */ public function send_test( $request ) { try { global $wpdb; $id = absint( $request->get_param( 'id' ) ); $table = Mailpuff_Schema::table( Mailpuff_Schema::CAMPAIGNS ); $campaign = $wpdb->get_row( $wpdb->prepare( 'SELECT * FROM %i WHERE id = %d', $table, $id ) ); if ( ! $campaign ) { return $this->error( 'not_found', __( 'Campaign not found.', 'mailpuff' ), 404 ); } $to = sanitize_email( $request->get_param( 'email' ) ); if ( empty( $to ) ) { $to = wp_get_current_user()->user_email; } if ( empty( $to ) ) { return $this->error( 'no_email', __( 'No recipient email provided.', 'mailpuff' ), 400 ); } // A single test email may go out on plain PHP mail; the response // carries a warning when it does. $result = Mailpuff_Outbox::send_now( $id, $to, array( 'type' => 'test' ) ); if ( is_wp_error( $result ) ) { return $this->error( $result->get_error_code(), $result->get_error_message(), 'send_failed' === $result->get_error_code() ? 500 : 422 ); } $mailer = Mailpuff_Mailer::get_instance(); $mailer->record_test_sent(); $status = $mailer->status(); return $this->success( array( /* translators: %s: the address the test email went to. */ 'message' => sprintf( __( 'Test sent to %s', 'mailpuff' ), $to ), 'mode' => $status['mode'], 'warning' => $status['warning'], ) ); } catch ( \Exception $e ) { return $this->error( 'test_error', $e->getMessage(), 500 ); } catch ( \Error $e ) { return $this->error( 'test_error', $e->getMessage(), 500 ); } } }