prefix . 'aieo_staff_digest'; } public static function register() { static $done = false; if ( $done ) { return; } $done = true; add_action( self::HOOK, array( __CLASS__, 'run' ) ); add_action( 'admin_init', array( __CLASS__, 'install' ), 5 ); } public static function install() { if ( ! function_exists( 'aieo_install_schema_once' ) ) { return; } aieo_install_schema_once( self::SCHEMA_OPTION, self::SCHEMA_VERSION, static function () { global $wpdb; $table = self::table(); $collate = function_exists( 'aieo_get_charset_collate' ) ? aieo_get_charset_collate() : $wpdb->get_charset_collate(); return false !== $wpdb->query( "CREATE TABLE IF NOT EXISTS {$table} ( id bigint(20) unsigned NOT NULL AUTO_INCREMENT, email varchar(190) NOT NULL DEFAULT '', source varchar(20) NOT NULL DEFAULT '', source_id bigint(20) unsigned NOT NULL DEFAULT 0, grp varchar(190) NOT NULL DEFAULT '', title varchar(255) NOT NULL DEFAULT '', summary varchar(500) NOT NULL DEFAULT '', link varchar(2048) NOT NULL DEFAULT '', created_at datetime NOT NULL, batch varchar(32) NOT NULL DEFAULT '', sent_at datetime DEFAULT NULL, PRIMARY KEY (id), UNIQUE KEY item (source, source_id, email), KEY pending (batch, email) ) {$collate}" ); } ); } public static function ready() { return (int) get_option( self::SCHEMA_OPTION, 0 ) >= self::SCHEMA_VERSION; } public static function choices() { $out = array(); foreach ( self::CHOICES as $h ) { if ( 0 === $h ) { $out['0'] = __( 'Each one as it arrives', 'ai-eshop-optimizer' ); } elseif ( 24 === $h ) { $out['24'] = __( 'A list once a day', 'ai-eshop-optimizer' ); } else { $out[ (string) $h ] = sprintf( _n( 'A list every hour', 'A list every %d hours', $h, 'ai-eshop-optimizer' ), $h ); } } return $out; } public static function prefs() { return self::clean( get_option( self::OPTION, array() ) ); } public static function save( array $choices ) { $stored = self::clean( $choices ); update_option( self::OPTION, $stored, false ); self::schedule(); return $stored; } private static function clean( $raw ) { $out = array(); foreach ( is_array( $raw ) ? $raw : array() as $email => $hours ) { $email = strtolower( sanitize_email( (string) $email ) ); $hours = (int) $hours; if ( is_email( $email ) && $hours > 0 && in_array( $hours, self::CHOICES, true ) ) { $out[ $email ] = $hours; } } return $out; } public static function set( $email, $hours ) { $email = strtolower( sanitize_email( (string) $email ) ); if ( ! is_email( $email ) ) { return false; } $prefs = self::prefs(); $prefs[ $email ] = (int) $hours; self::save( $prefs ); return true; } public static function addresses() { $map = array(); $add = static function ( $emails, $what ) use ( &$map ) { foreach ( (array) $emails as $email ) { $email = strtolower( sanitize_email( (string) $email ) ); if ( is_email( $email ) ) { $map[ $email ][ $what ] = $what; } } }; if ( class_exists( 'AIEO_Form_CPT' ) && class_exists( 'AIEO_Form_Submit' ) ) { $forms = get_posts( array( 'post_type' => AIEO_Form_CPT::POST_TYPE, 'post_status' => array( 'publish', 'private', 'draft' ), 'numberposts' => 200, 'meta_key' => AIEO_Form_CPT::META_NOTIFY, 'meta_value' => 'email', 'fields' => 'ids', ) ); foreach ( $forms as $form_id ) { $add( AIEO_Form_Submit::staff_addresses( AIEO_Form_CPT::settings( (int) $form_id ) ), html_entity_decode( get_the_title( $form_id ), ENT_QUOTES, 'UTF-8' ) ); } if ( $forms && class_exists( 'AIEO_Location_Contact' ) ) { foreach ( AIEO_Location_Contact::all() as $loc ) { $add( array( AIEO_Location_Contact::email( $loc ) ), sprintf( __( 'Forms for %s', 'ai-eshop-optimizer' ), (string) $loc['label'] ) ); } } } if ( class_exists( 'AIEO_Product_Request_Settings' ) && class_exists( 'AIEO_Product_Request_Mailer' ) && AIEO_Product_Request_Settings::frontend_is_active() ) { $s = AIEO_Product_Request_Settings::get( true ); foreach ( AIEO_Product_Request_Settings::clean_types( $s['request_types'] ) as $type ) { $add( AIEO_Product_Request_Mailer::recipients( $type, $s )['emails'], __( 'Product requests', 'ai-eshop-optimizer' ) ); } } if ( class_exists( 'AIEO_Contact_Form_Settings' ) && class_exists( 'AIEO_Contact_Form_Mailer' ) && AIEO_Contact_Form_Settings::is_enabled() ) { $add( AIEO_Contact_Form_Mailer::recipients()['emails'], __( 'Contact form', 'ai-eshop-optimizer' ) ); } foreach ( array_keys( self::prefs() + self::waiting() ) as $email ) { if ( ! isset( $map[ $email ] ) ) { $map[ $email ] = array(); } } ksort( $map ); return array_map( 'array_values', $map ); } public static function hours( $email ) { $prefs = self::prefs(); return (int) ( $prefs[ strtolower( (string) $email ) ] ?? 0 ); } public static function split( array $emails ) { $now = array(); $later = array(); $ready = self::ready(); $prefs = $ready ? self::prefs() : array(); foreach ( $emails as $email ) { $email = sanitize_email( (string) $email ); if ( ! is_email( $email ) ) { continue; } if ( isset( $prefs[ strtolower( $email ) ] ) ) { $later[] = $email; } else { $now[] = $email; } } return array( 'now' => array_values( array_unique( $now ) ), 'later' => array_values( array_unique( $later ) ) ); } public static function queue( array $emails, array $item ) { global $wpdb; $failed = array(); foreach ( $emails as $email ) { $ok = $wpdb->query( $wpdb->prepare( 'INSERT IGNORE INTO %i (email, source, source_id, grp, title, summary, link, created_at, batch) VALUES (%s, %s, %d, %s, %s, %s, %s, %s, %s)', self::table(), strtolower( (string) $email ), substr( sanitize_key( (string) ( $item['source'] ?? '' ) ), 0, 20 ), (int) ( $item['source_id'] ?? 0 ), mb_substr( self::line( $item['group'] ?? '' ), 0, 190 ), mb_substr( self::line( $item['title'] ?? '' ), 0, 255 ), mb_substr( self::line( $item['summary'] ?? '' ), 0, 500 ), substr( esc_url_raw( (string) ( $item['link'] ?? '' ) ), 0, 2048 ), gmdate( 'Y-m-d H:i:s' ), '' ) ); if ( false === $ok ) { $failed[] = (string) $email; } } self::schedule(); return $failed; } public static function run() { if ( ! self::ready() ) { return 0; } global $wpdb; $table = self::table(); $waiting = (array) $wpdb->get_results( $wpdb->prepare( 'SELECT email, MIN(created_at) AS oldest FROM %i WHERE batch = %s GROUP BY email', $table, '' ) ); $sent = 0; foreach ( $waiting as $row ) { $hours = self::hours( (string) $row->email ); if ( $hours > 0 && (int) strtotime( $row->oldest . ' UTC' ) > time() - $hours * HOUR_IN_SECONDS ) { continue; } if ( self::send( (string) $row->email, $hours ) ) { ++$sent; } } $wpdb->query( $wpdb->prepare( 'DELETE FROM %i WHERE batch <> %s AND sent_at < %s', $table, '', gmdate( 'Y-m-d H:i:s', time() - self::KEEP_DAYS * DAY_IN_SECONDS ) ) ); self::schedule(); return $sent; } public static function send( $email, $hours ) { global $wpdb; $table = self::table(); $batch = wp_generate_password( 32, false ); $wpdb->query( $wpdb->prepare( 'UPDATE %i SET batch = %s, sent_at = %s WHERE email = %s AND batch = %s ORDER BY id LIMIT %d', $table, $batch, gmdate( 'Y-m-d H:i:s' ), (string) $email, '', self::MAX_ROWS ) ); $items = (array) $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM %i WHERE batch = %s ORDER BY id', $table, $batch ), ARRAY_A ); if ( ! $items ) { return false; } $mail = self::compose( (string) $email, $items, (int) $hours ); if ( ! AIEO_Email_Frame::send_text( (string) $email, $mail['subject'], $mail['body'], array( 'id' => 'aieo_staff_digest', 'customer' => false ), array( 'Content-Type: text/plain; charset=UTF-8' ) ) ) { $wpdb->query( $wpdb->prepare( 'UPDATE %i SET batch = %s, sent_at = NULL WHERE batch = %s', $table, '', $batch ) ); return false; } return true; } public static function compose( $email, array $items, $hours ) { $site = wp_specialchars_decode( (string) get_option( 'blogname' ), ENT_QUOTES ); $count = count( $items ); $format = get_option( 'date_format' ) . ' ' . get_option( 'time_format' ); $when = static function ( $utc ) use ( $format ) { return (string) wp_date( $format, (int) strtotime( $utc . ' UTC' ) ); }; $offers = 0; $findings = 0; foreach ( $items as $item ) { if ( 'offer_event' === (string) ( $item['source'] ?? '' ) ) { ++$offers; } elseif ( 0 === strpos( (string) ( $item['source'] ?? '' ), 'offer_finding' ) ) { ++$findings; } } $submissions = $count - $offers - $findings; if ( 0 === $offers && 0 === $findings ) { $subject = sprintf( _n( '[%1$s] %2$d new submission', '[%1$s] %2$d new submissions', $count, 'ai-eshop-optimizer' ), $site, $count ); $lines = array( sprintf( _n( '%1$d new submission since %2$s.', '%1$d new submissions since %2$s.', $count, 'ai-eshop-optimizer' ), $count, $when( $items[0]['created_at'] ) ) ); } else { $parts = array(); if ( $submissions > 0 ) { $parts[] = sprintf( _n( '%d new submission', '%d new submissions', $submissions, 'ai-eshop-optimizer' ), $submissions ); } if ( $offers > 0 ) { $parts[] = sprintf( _n( '%d offer change', '%d offer changes', $offers, 'ai-eshop-optimizer' ), $offers ); } if ( $findings > 0 ) { $parts[] = sprintf( _n( '%d finding of the offers\' watch', '%d findings of the offers\' watch', $findings, 'ai-eshop-optimizer' ), $findings ); } $what = implode( _x( ', ', 'list separator', 'ai-eshop-optimizer' ), $parts ); $subject = sprintf( __( '[%1$s] %2$s', 'ai-eshop-optimizer' ), $site, $what ); $lines = array( sprintf( __( '%1$s since %2$s.', 'ai-eshop-optimizer' ), $what, $when( $items[0]['created_at'] ) ) ); } $groups = array(); foreach ( $items as $item ) { $groups[ (string) $item['grp'] ][] = $item; } foreach ( $groups as $group => $list ) { $lines[] = ''; $lines[] = ( '' !== $group ? $group : __( 'Submissions', 'ai-eshop-optimizer' ) ) . ' (' . count( $list ) . ')'; foreach ( $list as $item ) { $lines[] = ' - ' . $when( $item['created_at'] ) . ( '' !== (string) $item['title'] ? ' ยท ' . $item['title'] : '' ); if ( '' !== (string) $item['summary'] ) { $lines[] = ' ' . $item['summary']; } if ( '' !== (string) $item['link'] ) { $lines[] = ' ' . $item['link']; } } } $choices = self::choices(); $lines[] = ''; $lines[] = sprintf( __( 'How this address hears of new submissions: %1$s. Change it in Rooster One: %2$s', 'ai-eshop-optimizer' ), $choices[ (string) $hours ] ?? $choices['0'], self::screen_url() ); return array( 'subject' => str_replace( array( "\r", "\n" ), ' ', $subject ), 'body' => implode( "\n", $lines ) . "\n" ); } public static function screen_url() { return add_query_arg( array( 'page' => class_exists( 'AIEO_DMM' ) ? AIEO_DMM::MENU_SLUG : 'ai-eshop-dmm', 'dmm_tab' => 'staff_notifications' ), admin_url( 'admin.php' ) ); } public static function waiting() { if ( ! self::ready() ) { return array(); } global $wpdb; $rows = (array) $wpdb->get_results( $wpdb->prepare( 'SELECT email, COUNT(*) AS n, MIN(created_at) AS oldest FROM %i WHERE batch = %s GROUP BY email', self::table(), '' ) ); $out = array(); foreach ( $rows as $row ) { $out[ (string) $row->email ] = array( 'count' => (int) $row->n, 'oldest' => (string) $row->oldest ); } return $out; } public static function schedule() { $wanted = array() !== self::prefs() || array() !== self::waiting(); if ( function_exists( 'as_has_scheduled_action' ) && function_exists( 'as_schedule_recurring_action' ) ) { $has = as_has_scheduled_action( self::HOOK, array(), 'aieo' ); if ( $wanted && ! $has ) { as_schedule_recurring_action( time() + self::EVERY, self::EVERY, self::HOOK, array(), 'aieo' ); } elseif ( ! $wanted && $has ) { as_unschedule_all_actions( self::HOOK, array(), 'aieo' ); } return; } $next = wp_next_scheduled( self::HOOK ); if ( $wanted && ! $next ) { wp_schedule_event( time() + self::EVERY, 'hourly', self::HOOK ); } elseif ( ! $wanted && $next ) { wp_clear_scheduled_hook( self::HOOK ); } } private static function line( $text ) { return trim( (string) preg_replace( '/[\s\x00-\x1f]+/u', ' ', (string) $text ) ); } } }