MINUTE_IN_SECONDS, 'display' => __( 'Every minute (New Post Alerts)', 'afojet-new-post-alerts' ), ); return $schedules; } public static function post_types() { return (array) apply_filters( 'afpp_post_types', array( 'post' ) ); } /* ------------------------------------------------------------------ * * Read helpers * ------------------------------------------------------------------ */ public static function get( $id ) { global $wpdb; $t = AFPP_DB::broadcasts(); $row = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE id = %d", $t, $id ) ); // phpcs:ignore WordPress.DB if ( $row ) { $row->payload = json_decode( (string) $row->payload, true ); if ( ! is_array( $row->payload ) ) { $row->payload = array(); } } return $row; } public static function for_post( $post_id ) { global $wpdb; $t = AFPP_DB::broadcasts(); return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE post_id = %d ORDER BY id DESC LIMIT 10", $t, $post_id ) ); // phpcs:ignore WordPress.DB } public static function recent( $page = 1, $per_page = 20 ) { global $wpdb; $t = AFPP_DB::broadcasts(); $offset = ( max( 1, (int) $page ) - 1 ) * $per_page; return array( 'rows' => $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i ORDER BY id DESC LIMIT %d OFFSET %d", $t, $per_page, $offset ) ), // phpcs:ignore WordPress.DB 'total' => (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i', $t ) ), // phpcs:ignore WordPress.DB ); } public static function has_open() { global $wpdb; $t = AFPP_DB::broadcasts(); return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT id FROM %i WHERE status IN ('queued','sending') LIMIT 1", $t ) ); // phpcs:ignore WordPress.DB } /** Subscribers a broadcast of this kind would reach right now. */ public static function recipient_count( $kind, array $payload ) { global $wpdb; $s = AFPP_DB::subscribers(); $where = self::recipient_where( $kind, $payload ); // $where is built from fixed SQL by this plugin and its add-on (see recipient_where()). return (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i s WHERE {$where}", $s ) ); // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB.UnescapedDBParameter } /** * SQL condition on the subscribers table (alias "s"). * Pro narrows it with categories and send frequency. */ private static function recipient_where( $kind, array $payload ) { $where = "s.status = 'active'"; $extra = (string) apply_filters( 'afpp_recipient_where', '', $kind, $payload ); return $extra ? $where . ' AND ( ' . $extra . ' )' : $where; } /* ------------------------------------------------------------------ * * Create * ------------------------------------------------------------------ */ public static function payload_for_post( $post ) { $post = get_post( $post ); $image = get_the_post_thumbnail_url( $post, 'large' ); return array( 'title' => get_the_title( $post ), 'link' => get_permalink( $post ), 'image' => $image ? $image : '', 'post_ids' => array( (int) $post->ID ), ); } /** * Queue a broadcast. * * @param int $post_id Post to send (0 for digests). * @param string $kind manual | auto | digest_daily | digest_weekly … * @param array $payload Optional payload (defaults to the post's title / link / image). * @return int|WP_Error Broadcast id. */ public static function create( $post_id, $kind = 'manual', array $payload = array() ) { global $wpdb; if ( ! AFPP_Settings::api_configured() ) { return new WP_Error( 'not_configured', __( 'Set up the WhatsApp API in New Post Alerts → Settings first.', 'afojet-new-post-alerts' ) ); } if ( $post_id ) { $post = get_post( $post_id ); if ( ! $post || 'publish' !== $post->post_status ) { return new WP_Error( 'not_published', __( 'Only published posts can be sent.', 'afojet-new-post-alerts' ) ); } $payload = array_merge( self::payload_for_post( $post ), $payload ); } $payload = apply_filters( 'afpp_broadcast_payload', $payload, $post_id, $kind ); $now = current_time( 'mysql', true ); $wpdb->insert( // phpcs:ignore WordPress.DB AFPP_DB::broadcasts(), array( 'post_id' => (int) $post_id, 'kind' => $kind, 'status' => 'queued', 'payload' => wp_json_encode( $payload ), 'created_by' => get_current_user_id(), 'created_at' => $now, ) ); $id = (int) $wpdb->insert_id; if ( ! $id ) { return new WP_Error( 'db', __( 'Could not save the broadcast.', 'afojet-new-post-alerts' ) ); } $s = AFPP_DB::subscribers(); $q = AFPP_DB::queue(); $where = self::recipient_where( $kind, $payload ); // $where is fixed SQL from recipient_where(); table names go through %i. // phpcs:ignore WordPress.DB, PluginCheck.Security.DirectDB.UnescapedDBParameter $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO %i (broadcast_id, subscriber_id, status) SELECT %d, s.id, 'pending' FROM %i s WHERE {$where}", $q, $id, $s ) ); $total = (int) $wpdb->rows_affected; if ( ! $total ) { $wpdb->update( AFPP_DB::broadcasts(), array( 'status' => 'done', 'finished_at' => $now ), array( 'id' => $id ) ); // phpcs:ignore WordPress.DB return new WP_Error( 'no_recipients', __( 'There are no active subscribers to send to.', 'afojet-new-post-alerts' ) ); } $wpdb->update( AFPP_DB::broadcasts(), array( 'total' => $total ), array( 'id' => $id ) ); // phpcs:ignore WordPress.DB if ( $post_id ) { update_post_meta( $post_id, '_afpp_last_broadcast', $id ); } self::ensure_cron(); do_action( 'afpp_broadcast_created', $id, $kind, $payload ); return $id; } public static function cancel( $id ) { global $wpdb; $wpdb->update( AFPP_DB::broadcasts(), array( 'status' => 'cancelled', 'finished_at' => current_time( 'mysql', true ) ), array( 'id' => (int) $id ) ); // phpcs:ignore WordPress.DB $wpdb->update( AFPP_DB::queue(), array( 'status' => 'cancelled' ), array( 'broadcast_id' => (int) $id, 'status' => 'pending' ) ); // phpcs:ignore WordPress.DB self::recount( $id ); } /* ------------------------------------------------------------------ * * Send * ------------------------------------------------------------------ */ public static function ensure_cron() { if ( ! wp_next_scheduled( self::CRON ) ) { wp_schedule_event( time() + 5, self::SCHEDULE, self::CRON ); } } public static function cron() { self::process( 40 ); if ( ! self::has_open() ) { wp_clear_scheduled_hook( self::CRON ); } } /** * Send the next batch of pending messages. * * @param int $seconds Stop after about this many seconds. * @return int Messages handled. */ public static function process( $seconds = 20 ) { global $wpdb; if ( get_transient( self::LOCK ) ) { return 0; } set_transient( self::LOCK, 1, $seconds + 30 ); $started = time(); $handled = 0; $batch = (int) AFPP_Settings::get( 'afpp_batch_size' ); $b_table = AFPP_DB::broadcasts(); $q_table = AFPP_DB::queue(); $open = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM %i WHERE status IN ('queued','sending') ORDER BY id ASC LIMIT 5", $b_table ) ); // phpcs:ignore WordPress.DB foreach ( $open as $bid ) { $broadcast = self::get( $bid ); if ( 'queued' === $broadcast->status ) { $wpdb->update( $b_table, array( 'status' => 'sending', 'started_at' => current_time( 'mysql', true ) ), array( 'id' => $bid ) ); // phpcs:ignore WordPress.DB } $items = $wpdb->get_results( $wpdb->prepare( "SELECT id, subscriber_id FROM %i WHERE broadcast_id = %d AND status = 'pending' ORDER BY id ASC LIMIT %d", $q_table, $bid, $batch ) ); // phpcs:ignore WordPress.DB foreach ( $items as $item ) { if ( time() - $started >= $seconds ) { break 2; } self::send_item( $broadcast, $item ); ++$handled; } $left = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE broadcast_id = %d AND status = 'pending'", $q_table, $bid ) ); // phpcs:ignore WordPress.DB self::recount( $bid ); if ( ! $left ) { $wpdb->update( $b_table, array( 'status' => 'done', 'finished_at' => current_time( 'mysql', true ) ), array( 'id' => $bid ) ); // phpcs:ignore WordPress.DB do_action( 'afpp_broadcast_done', (int) $bid ); } } delete_transient( self::LOCK ); return $handled; } private static function send_item( $broadcast, $item ) { global $wpdb; $q = AFPP_DB::queue(); $subscriber = AFPP_Subscribers::get( $item->subscriber_id ); if ( ! $subscriber || 'active' !== $subscriber->status ) { $wpdb->update( $q, array( 'status' => 'skipped', 'error' => 'not active' ), array( 'id' => $item->id ) ); // phpcs:ignore WordPress.DB return; } $message = self::message_for( $broadcast, $subscriber ); if ( is_wp_error( $message ) || ! $message ) { $wpdb->update( $q, array( 'status' => 'skipped', 'error' => is_wp_error( $message ) ? substr( $message->get_error_message(), 0, 250 ) : 'nothing to send' ), array( 'id' => $item->id ) ); // phpcs:ignore WordPress.DB return; } $result = AFPP_WhatsApp::send_template( $subscriber->phone, $message['template'], $message['lang'], $message['components'] ); if ( is_wp_error( $result ) ) { $wpdb->update( $q, array( 'status' => 'failed', 'error' => substr( $result->get_error_message(), 0, 250 ), 'sent_at' => current_time( 'mysql', true ) ), array( 'id' => $item->id ) ); // phpcs:ignore WordPress.DB if ( AFPP_WhatsApp::is_recipient_error( $result ) ) { AFPP_Subscribers::set_status( $subscriber->id, 'bounced' ); } return; } $wpdb->update( $q, array( 'status' => 'sent', 'wamid' => $result, 'error' => '', 'sent_at' => current_time( 'mysql', true ) ), array( 'id' => $item->id ) ); // phpcs:ignore WordPress.DB do_action( 'afpp_message_sent', $broadcast, $subscriber, $result ); } /** * The template and variables for one subscriber. * * @return array{template:string,lang:string,components:array}|WP_Error|false False = skip this subscriber. */ public static function message_for( $broadcast, $subscriber ) { $default = null; if ( in_array( $broadcast->kind, array( 'manual', 'auto', 'test' ), true ) ) { $default = self::post_message( $broadcast, $subscriber ); } return apply_filters( 'afpp_message', $default, $broadcast, $subscriber ); } /** Link a subscriber taps. Pro swaps it for a click-tracking link. */ public static function link_for( $link, $broadcast, $subscriber ) { return (string) apply_filters( 'afpp_message_link', $link, $broadcast, $subscriber ); } /** Header image for templates with an IMAGE header. */ public static function header_image( $url ) { if ( ! $url ) { $url = get_site_icon_url( 512 ); } return (string) apply_filters( 'afpp_header_image', $url ); } /** Components for the main "new post" template, following the settings. */ public static function post_message( $broadcast, $subscriber ) { $p = $broadcast->payload; $link = self::link_for( isset( $p['link'] ) ? $p['link'] : home_url( '/' ), $broadcast, $subscriber ); $components = array(); if ( AFPP_Settings::enabled( 'afpp_header_image' ) ) { $image = self::header_image( isset( $p['image'] ) ? $p['image'] : '' ); if ( ! $image ) { return new WP_Error( 'no_image', __( 'The template needs a header image but the post has no featured image and the site has no icon.', 'afojet-new-post-alerts' ) ); } $components[] = array( 'type' => 'header', 'parameters' => array( array( 'type' => 'image', 'image' => array( 'link' => $image ), ), ), ); } $body = array( AFPP_WhatsApp::text_param( isset( $p['title'] ) ? $p['title'] : '' ) ); if ( 'body' === AFPP_Settings::get( 'afpp_link_mode' ) ) { $body[] = AFPP_WhatsApp::text_param( $link ); } if ( AFPP_Settings::enabled( 'afpp_unsub_var' ) ) { $body[] = AFPP_WhatsApp::text_param( AFPP_Subscribers::unsubscribe_url( $subscriber ) ); } $components[] = array( 'type' => 'body', 'parameters' => $body, ); if ( 'button' === AFPP_Settings::get( 'afpp_link_mode' ) ) { $components[] = array( 'type' => 'button', 'sub_type' => 'url', 'index' => '0', 'parameters' => array( array( 'type' => 'text', 'text' => self::button_suffix( $link ), ), ), ); } return array( 'template' => AFPP_Settings::get( 'afpp_template_name' ), 'lang' => AFPP_Settings::get( 'afpp_template_lang' ), 'components' => $components, ); } /** * A URL button in a template has a fixed start (your site address) and a * dynamic end. We send the part of the link after the site address. */ public static function button_suffix( $link ) { $home = trailingslashit( home_url() ); if ( 0 === strpos( $link, $home ) ) { return substr( $link, strlen( $home ) ); } return ltrim( (string) wp_parse_url( $link, PHP_URL_PATH ) . ( wp_parse_url( $link, PHP_URL_QUERY ) ? '?' . wp_parse_url( $link, PHP_URL_QUERY ) : '' ), '/' ); } public static function recount( $id ) { global $wpdb; $q = AFPP_DB::queue(); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT status, COUNT(*) AS n FROM %i WHERE broadcast_id = %d GROUP BY status", $q, $id ), OBJECT_K ); // phpcs:ignore WordPress.DB $wpdb->update( // phpcs:ignore WordPress.DB AFPP_DB::broadcasts(), array( 'sent' => isset( $rows['sent'] ) ? (int) $rows['sent']->n : 0, 'failed' => isset( $rows['failed'] ) ? (int) $rows['failed']->n : 0, 'skipped' => ( isset( $rows['skipped'] ) ? (int) $rows['skipped']->n : 0 ) + ( isset( $rows['cancelled'] ) ? (int) $rows['cancelled']->n : 0 ), ), array( 'id' => (int) $id ) ); } public static function progress( $id ) { $b = self::get( $id ); if ( ! $b ) { return null; } $done = (int) $b->sent + (int) $b->failed + (int) $b->skipped; return array( 'id' => (int) $b->id, 'status' => $b->status, 'total' => (int) $b->total, 'sent' => (int) $b->sent, 'failed' => (int) $b->failed, 'skipped' => (int) $b->skipped, 'percent' => $b->total ? min( 100, (int) round( $done * 100 / $b->total ) ) : 100, ); } /** Most common errors of a broadcast, for the broadcast list. */ public static function top_errors( $id ) { global $wpdb; $q = AFPP_DB::queue(); return $wpdb->get_results( $wpdb->prepare( "SELECT error, COUNT(*) AS n FROM %i WHERE broadcast_id = %d AND status = 'failed' GROUP BY error ORDER BY n DESC LIMIT 3", $q, $id ) ); // phpcs:ignore WordPress.DB } /* ------------------------------------------------------------------ * * Post editor: meta box + posts list action * ------------------------------------------------------------------ */ public function meta_box() { foreach ( self::post_types() as $type ) { add_meta_box( 'afpp-broadcast', __( 'WhatsApp subscribers', 'afojet-new-post-alerts' ), array( $this, 'render_meta_box' ), $type, 'side', 'default' ); } } public function render_meta_box( $post ) { $count = self::recipient_count( 'manual', self::payload_for_post( $post ) ); $past = self::for_post( $post->ID ); echo '
'; } public function row_action( $actions, $post ) { if ( in_array( $post->post_type, self::post_types(), true ) && 'publish' === $post->post_status && current_user_can( 'publish_posts' ) ) { $actions['afpp_send'] = '' . esc_html__( 'Send on WhatsApp', 'afojet-new-post-alerts' ) . ''; } return $actions; } public function editor_assets( $hook ) { if ( ! in_array( $hook, array( 'post.php', 'post-new.php' ), true ) ) { return; } $screen = get_current_screen(); if ( ! $screen || ! in_array( $screen->post_type, self::post_types(), true ) ) { return; } AFPP_Admin::enqueue_admin_assets(); } /* ------------------------------------------------------------------ * * AJAX * ------------------------------------------------------------------ */ private static function check_capability() { if ( ! current_user_can( 'publish_posts' ) ) { wp_send_json_error( array( 'message' => __( 'You are not allowed to do this.', 'afojet-new-post-alerts' ) ), 403 ); } } public function ajax_create() { check_ajax_referer( 'afpp_admin', 'nonce' ); self::check_capability(); $post_id = isset( $_POST['post_id'] ) ? absint( $_POST['post_id'] ) : 0; if ( ! current_user_can( 'edit_post', $post_id ) ) { wp_send_json_error( array( 'message' => __( 'You are not allowed to send this post.', 'afojet-new-post-alerts' ) ), 403 ); } // "everyone" = ignore subscriber topic/frequency choices (Pro shows this option). $id = self::create( $post_id, 'manual', array( 'everyone' => isset( $_POST['everyone'] ) && '1' === sanitize_text_field( wp_unslash( $_POST['everyone'] ) ) ) ); if ( is_wp_error( $id ) ) { wp_send_json_error( array( 'message' => $id->get_error_message() ) ); } self::process( 8 ); wp_send_json_success( self::progress( $id ) ); } public function ajax_process() { check_ajax_referer( 'afpp_admin', 'nonce' ); self::check_capability(); $id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0; self::process( 12 ); $progress = self::progress( $id ); if ( ! $progress ) { wp_send_json_error( array( 'message' => __( 'Broadcast not found.', 'afojet-new-post-alerts' ) ) ); } wp_send_json_success( $progress ); } public function ajax_cancel() { check_ajax_referer( 'afpp_admin', 'nonce' ); self::check_capability(); $id = isset( $_POST['id'] ) ? absint( $_POST['id'] ) : 0; self::cancel( $id ); wp_send_json_success( self::progress( $id ) ); } }