= $from && $hour < $to ) : ( $hour >= $from || $hour < $to ); } /** Hours after leaving for each reminder that is sent. */ function brai_rec_steps() { $s = brai_mail_settings(); $d = array(); for ( $i = 1; $i <= (int) $s['count']; $i++ ) { $d[] = max( 1, (int) $s[ 'r' . $i ]['delay'] ); } return $d; } /** * Signature for links in emails. * * @param string $data Data to sign. * @param string $scheme brai, or wi_ba for links sent by the earlier snippet version. * @return string */ function brai_sign( $data, $scheme = 'brai' ) { return substr( hash_hmac( 'sha256', (string) $data, wp_salt( 'auth' ) . '|' . $scheme ), 0, 20 ); } /** * URL-safe base64. * * @param string $s Text. * @return string */ function brai_b64e( $s ) { return rtrim( strtr( base64_encode( (string) $s ), '+/', '-_' ), '=' ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode -- short URL-safe token, not obfuscation. } /** * Decodes URL-safe base64. * * @param string $s Token. * @return string */ function brai_b64d( $s ) { return (string) base64_decode( strtr( (string) $s, '-_', '+/' ) ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- short URL-safe token, not obfuscation. } /** * Link that puts these items back in the basket (works on any device). * * @param array $items Basket items. * @param string $vid Visitor. * @return string */ function brai_restore_url( $items, $vid = '' ) { $list = array(); foreach ( (array) $items as $i ) { $list[] = array( (int) $i['id'], (int) $i['qty'] ); } $r = brai_b64e( wp_json_encode( $list ) ); return add_query_arg( array( 'brai_restore' => $r, 'bv' => $vid, 'bk' => brai_sign( $r . '|' . $vid ), ), home_url( '/' ) ); } /** * Unsubscribe link. * * @param string $email Email. * @return string */ function brai_unsub_url( $email ) { $e = brai_b64e( strtolower( (string) $email ) ); return add_query_arg( array( 'brai_unsub' => $e, 'bk' => brai_sign( $e ), ), home_url( '/' ) ); } /** * Has this email unsubscribed? * * @param string $email Email. * @return bool */ function brai_unsubscribed( $email ) { return in_array( strtolower( (string) $email ), (array) get_option( 'brai_unsub_list', array() ), true ); } /** * Has this customer ordered since they left the basket (on any device)? * * @param string $email Email. * @param int $since_ts Timestamp. * @return bool */ function brai_has_ordered( $email, $since_ts ) { if ( ! function_exists( 'wc_get_orders' ) ) { return false; } $ids = wc_get_orders( array( 'billing_email' => $email, 'date_created' => '>' . ( (int) $since_ts - HOUR_IN_SECONDS ), 'status' => array( 'wc-processing', 'wc-completed', 'wc-on-hold' ), 'limit' => 1, 'return' => 'ids', ) ); return ! empty( $ids ); } /** * Reads a link from a reminder email: unsubscribe, or put the basket back. * * These links are opened from an inbox, often days later, on any device and by someone who is not logged in, * so a nonce cannot be used. Each link carries a signature instead (HMAC-SHA256 of its contents with this * site's secret key, see brai_sign()), and nothing is returned unless the signature matches. * * @return array|null action (unsub or restore) and its verified values, or null if this is not a genuine link. */ function brai_email_link() { $schemes = array( 'brai' => array( 'brai_unsub', 'brai_restore', 'bv', 'bk', 'brai_coupon' ), 'wi_ba' => array( 'wi_ba_unsub', 'wi_ba_restore', 'wbv', 'wbk', 'wi_ba_coupon' ), // Emails sent by the earlier version. ); // phpcs:disable WordPress.Security.NonceVerification.Recommended -- links from emails cannot carry a nonce; each one is verified with hash_equals() against its signature below. foreach ( $schemes as $scheme => $p ) { $key = isset( $_GET[ $p[3] ] ) ? sanitize_text_field( wp_unslash( $_GET[ $p[3] ] ) ) : ''; if ( '' === $key ) { continue; } if ( isset( $_GET[ $p[0] ] ) ) { $e = sanitize_text_field( wp_unslash( $_GET[ $p[0] ] ) ); return hash_equals( brai_sign( $e, $scheme ), $key ) ? array( 'action' => 'unsub', 'email' => strtolower( sanitize_email( brai_b64d( $e ) ) ), ) : null; } if ( isset( $_GET[ $p[1] ] ) ) { $r = sanitize_text_field( wp_unslash( $_GET[ $p[1] ] ) ); $vid = isset( $_GET[ $p[2] ] ) ? sanitize_key( wp_unslash( $_GET[ $p[2] ] ) ) : ''; return hash_equals( brai_sign( $r . '|' . $vid, $scheme ), $key ) ? array( 'action' => 'restore', 'items' => (array) json_decode( brai_b64d( $r ), true ), 'vid' => $vid, 'coupon' => isset( $_GET[ $p[4] ] ) ? wc_format_coupon_code( sanitize_text_field( wp_unslash( $_GET[ $p[4] ] ) ) ) : '', ) : null; } } // phpcs:enable WordPress.Security.NonceVerification.Recommended return null; } /* Links in reminder emails: unsubscribe, or put the basket back (and add the discount code). */ add_action( 'wp_loaded', function () { $link = brai_email_link(); if ( ! $link ) { return; } if ( 'unsub' === $link['action'] ) { $email = $link['email']; $list = (array) get_option( 'brai_unsub_list', array() ); if ( $email && ! in_array( $email, $list, true ) ) { $list[] = $email; update_option( 'brai_unsub_list', $list, false ); global $wpdb; foreach ( $wpdb->get_col( $wpdb->prepare( 'SELECT vid FROM %i WHERE email = %s', brai_table( 'visitors' ), $email ) ) as $v ) { brai_event( $v, 'unsub' ); } } $site = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); nocache_headers(); wp_die( '
' . /* translators: %s: shop name. */ esc_html( sprintf( __( 'You will not get any more basket reminder emails from %s.', 'basketwise' ), $site ) ) . '
', esc_html__( 'Unsubscribed', 'basketwise' ), array( 'response' => 200 ) ); } if ( ! function_exists( 'WC' ) || ! WC()->cart ) { return; } $vid = $link['vid']; if ( WC()->cart->is_empty() ) { foreach ( $link['items'] as $it ) { $prod = wc_get_product( (int) ( $it[0] ?? 0 ) ); $q = max( 1, (int) ( $it[1] ?? 1 ) ); if ( ! $prod || ! $prod->is_purchasable() || ! $prod->is_in_stock() ) { continue; } if ( $prod->is_type( 'variation' ) ) { WC()->cart->add_to_cart( $prod->get_parent_id(), $q, $prod->get_id(), $prod->get_variation_attributes() ); } else { WC()->cart->add_to_cart( $prod->get_id(), $q ); } } } if ( $vid && 'test' !== $vid ) { global $wpdb; $row = $wpdb->get_row( $wpdb->prepare( 'SELECT email, name FROM %i WHERE vid = %s', brai_table( 'visitors' ), $vid ), ARRAY_A ); if ( $row ) { brai_event( $vid, 'restore' ); if ( $row['email'] && WC()->customer && ! WC()->customer->get_billing_email() ) { WC()->customer->set_billing_email( $row['email'] ); $parts = explode( ' ', trim( (string) $row['name'] ), 2 ); if ( $parts[0] && ! WC()->customer->get_billing_first_name() ) { WC()->customer->set_billing_first_name( $parts[0] ); WC()->customer->set_billing_last_name( $parts[1] ?? '' ); } WC()->customer->save(); } } } if ( $link['coupon'] && ! WC()->cart->is_empty() && ! WC()->cart->has_discount( $link['coupon'] ) ) { WC()->cart->apply_coupon( $link['coupon'] ); } if ( WC()->session ) { WC()->session->set_customer_session_cookie( true ); } nocache_headers(); wp_safe_redirect( WC()->cart->is_empty() ? wc_get_cart_url() : wc_get_checkout_url() ); exit; }, 25 ); /** Email-safe fonts. */ function brai_fonts() { return array( 'Helvetica,Arial,sans-serif' => 'Helvetica / Arial', 'Verdana,Geneva,sans-serif' => 'Verdana', 'Tahoma,Verdana,sans-serif' => 'Tahoma', 'Trebuchet MS,Helvetica,sans-serif' => 'Trebuchet', 'Georgia,Times New Roman,serif' => 'Georgia (serif)', ); } /** * Every email setting, with defaults taken from the website's own logo, colours and store details. * * @return array */ function brai_mail_settings() { $site = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); $map = brai_site_map(); $addr = implode( ', ', array_filter( array( get_option( 'woocommerce_store_address' ), get_option( 'woocommerce_store_address_2' ), get_option( 'woocommerce_store_city' ), get_option( 'woocommerce_store_postcode' ) ) ) ); $b = apply_filters( 'brai_brand_defaults', array( 'name' => $site, 'logo' => brai_site_logo(), 'accent' => ! empty( $map['accent'] ) ? $map['accent'] : '#2271b1', 'footer' => ! empty( $map['footer_bg'] ) ? $map['footer_bg'] : '#1d2327', 'text' => ! empty( $map['text'] ) ? $map['text'] : '#1d2327', 'email' => sanitize_email( (string) get_option( 'woocommerce_email_from_address', get_option( 'admin_email' ) ) ), 'phone' => '', 'address' => (string) $addr, ) ); $dtext = __( 'Here is {discount} off your order to help you decide. Use code {coupon} at checkout, or press the button below and it is added for you. Valid until {coupon_expiry}.', 'basketwise' ); $step = function ( $delay, $subj, $anon, $pre, $body, $btn ) use ( $dtext ) { return array( 'delay' => $delay, 'subject' => $subj, 'subject_anon' => $anon, 'preheader' => $pre, 'heading' => __( 'Hi {first_name},', 'basketwise' ), 'body' => $body, 'button' => $btn, 'disc' => 0, 'disc_type' => 'percent', 'disc_amount' => 10, 'disc_days' => 7, 'disc_min' => 0, 'disc_text' => $dtext, ); }; $d = array( 'logo' => (string) $b['logo'], 'logo_auto' => 1, 'logo_width' => 260, 'accent' => (string) $b['accent'], 'button_bg' => (string) $b['accent'], 'button_text' => '', 'footer_bg' => (string) $b['footer'], 'footer_text' => brai_is_light( $b['footer'] ) ? '#1d2327' : '#ffffff', 'text' => (string) $b['text'], 'link' => (string) $b['text'], 'bg' => '#ffffff', 'font' => 'Helvetica,Arial,sans-serif', 'from_name' => (string) $b['name'], 'reply_to' => (string) $b['email'], 'phone' => (string) $b['phone'], 'address' => (string) $b['address'], 'show_email' => 1, 'show_phone' => 1, 'show_address' => 1, 'footer_note' => '', 'help' => $b['phone'] ? __( 'Got a question before you buy? Just reply to this email or give us a call on {phone}, we are always happy to help.', 'basketwise' ) : __( 'Got a question before you buy? Just reply to this email, we are always happy to help.', 'basketwise' ), 'signoff' => __( "Thanks,\nThe {site_name} team", 'basketwise' ), 'unsub_text' => __( 'Rather not get these reminders?', 'basketwise' ), 'unsub_link' => __( 'Just let us know', 'basketwise' ), 'show_images' => 1, 'show_stock' => 1, 'stock_under' => 10, 'count' => 3, 'digest_to' => (string) get_option( 'admin_email' ), 'digest_hour' => 8, 'digest_weekends' => 0, 'weekly' => 0, 'min_value' => 0, 'quiet' => 0, 'quiet_from' => 21, 'quiet_to' => 8, 'r1' => $step( 1, __( '{first_name}, you left something in your basket', 'basketwise' ), __( 'You left something in your basket', 'basketwise' ), __( 'We have saved your basket so you can pick up where you left off.', 'basketwise' ), __( 'Looks like you got interrupted before finishing your order. No problem at all, we have saved your basket so you can pick up right where you left off.', 'basketwise' ), __( 'Complete my order', 'basketwise' ) ), 'r2' => $step( 24, __( '{first_name}, your basket is still waiting for you', 'basketwise' ), __( 'Your basket is still waiting for you', 'basketwise' ), __( 'The items you picked are still in your basket.', 'basketwise' ), __( 'Just a friendly nudge: the items below are still waiting in your basket. Stock and prices can change, so if you would still like them, now is a great time to complete your order.', 'basketwise' ), __( 'Finish my order', 'basketwise' ) ), 'r3' => $step( 72, __( 'Last call: complete your {site_name} order today', 'basketwise' ), __( 'Last call: complete your {site_name} order today', 'basketwise' ), __( 'Your saved basket will not be held for much longer.', 'basketwise' ), __( 'This is the last time we will remind you about your basket. Popular items can sell out and prices can change, so complete your order today to make sure you get everything you picked.', 'basketwise' ), __( 'Complete my order now', 'basketwise' ) ), ); $s = get_option( 'brai_mail', array() ); $s = is_array( $s ) ? $s : array(); foreach ( array( 'r1', 'r2', 'r3' ) as $k ) { $s[ $k ] = wp_parse_args( (array) ( $s[ $k ] ?? array() ), $d[ $k ] ); } /* Settings saved before 1.1.0 have no "use the website logo" choice: a logo that was picked is kept, and where none was picked the website logo is used. */ if ( $s && ! isset( $s['logo_auto'] ) ) { $s['logo_auto'] = empty( $s['logo'] ) ? 1 : 0; } return brai_mail_logo( wp_parse_args( $s, $d ) ); } /** * Fills in the website logo when the emails are set to follow it, so a new logo on the site reaches the emails by itself. * * @param array $s Email settings. * @return array */ function brai_mail_logo( $s ) { if ( ! empty( $s['logo_auto'] ) ) { $s['logo'] = brai_site_logo(); } return $s; } /** * Replaces {placeholders}. * * @param string $text Text. * @param array $vars Placeholder values. * @return string */ function brai_fill( $text, $vars ) { return strtr( (string) $text, $vars ); } /** * Placeholder values for one customer. * * @param array $r Visitor row. * @param array $s Email settings. * @param array|null $coupon Discount code details. * @return array */ function brai_mail_vars( $r, $s, $coupon = null ) { $items = ! empty( $r['cart'] ) ? (array) json_decode( $r['cart'], true ) : array(); $total = 0; $count = 0; foreach ( $items as $i ) { $total += (float) ( $i['total'] ?? 0 ); $count += (int) ( $i['qty'] ?? 0 ); } $first = trim( (string) strtok( (string) ( $r['name'] ?? '' ), ' ' ) ); return array( '{first_name}' => $first ? $first : __( 'there', 'basketwise' ), '{site_name}' => wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), '{basket_total}' => brai_money( $total ), '{item_count}' => (string) $count, '{phone}' => (string) $s['phone'], '{email}' => (string) $s['reply_to'], '{coupon}' => $coupon ? strtoupper( $coupon['code'] ) : '', '{discount}' => $coupon ? $coupon['label'] : '', '{coupon_expiry}' => $coupon ? $coupon['expiry'] : '', ); } /** * Discount code for one customer: unique, single use, only for their email address. A code already sent to * the same customer for the same offer is reused. Tests and previews get a sample code. * * @param array $r Visitor row. * @param array $c Reminder settings. * @return array|null */ function brai_coupon_for( $r, $c ) { $amount = (float) $c['disc_amount']; $type = 'fixed_cart' === $c['disc_type'] ? 'fixed_cart' : 'percent'; $label = 'percent' === $type ? rtrim( rtrim( number_format( $amount, 2, '.', '' ), '0' ), '.' ) . '%' : brai_money( $amount ); $days = max( 1, (int) $c['disc_days'] ); $exp = time() + $days * DAY_IN_SECONDS; if ( empty( $r['vid'] ) || 'test' === $r['vid'] || empty( $r['email'] ) || ! class_exists( 'WC_Coupon' ) ) { return array( 'code' => 'BACK-SAMPLE', 'label' => $label, 'expiry' => wp_date( 'j F', $exp ), 'sample' => true, ); } global $wpdb; foreach ( $wpdb->get_results( $wpdb->prepare( "SELECT object_id FROM %i WHERE vid = %s AND type = 'coupon' ORDER BY id DESC LIMIT 5", brai_table( 'events' ), $r['vid'] ) ) as $e ) { $old = new WC_Coupon( (int) $e->object_id ); $oe = $old->get_date_expires(); if ( $old->get_id() && $old->get_discount_type() === $type && abs( (float) $old->get_amount() - $amount ) < 0.001 && ! $old->get_usage_count() && ( ! $oe || $oe->getTimestamp() > time() + DAY_IN_SECONDS ) ) { return array( 'code' => $old->get_code(), 'label' => $label, 'expiry' => $oe ? wp_date( 'j F', $oe->getTimestamp() ) : '', ); } } do { $code = 'BACK-' . strtoupper( wp_generate_password( 6, false, false ) ); } while ( wc_get_coupon_id_by_code( $code ) ); $cp = new WC_Coupon(); $cp->set_code( $code ); $cp->set_discount_type( $type ); $cp->set_amount( $amount ); $cp->set_individual_use( true ); $cp->set_usage_limit( 1 ); $cp->set_usage_limit_per_user( 1 ); $cp->set_email_restrictions( array( $r['email'] ) ); if ( (float) $c['disc_min'] > 0 ) { $cp->set_minimum_amount( (float) $c['disc_min'] ); } $cp->set_date_expires( $exp ); /* translators: %s: customer email. */ $cp->set_description( sprintf( __( 'Basket reminder discount for %s', 'basketwise' ), $r['email'] ) ); $id = $cp->save(); if ( ! $id ) { return null; } brai_event( $r['vid'], 'coupon', $id, 0, $amount, $code ); return array( 'code' => $code, 'label' => $label, 'expiry' => wp_date( 'j F', $exp ), ); } /** * The full branded email around the message. * * @param string $inner Message HTML. * @param array $s Email settings. * @param string $title Subject. * @param string $preheader Inbox preview text. * @return string */ function brai_mail_frame( $inner, $s, $title = '', $preheader = '' ) { $font = 'font-family:' . esc_attr( $s['font'] ) . ';'; $name = (string) $s['from_name']; $logo = $s['logo'] ? ''
. '
|
' . esc_html( brai_fill( $c['heading'], $raw ) ) . '
'; foreach ( preg_split( '/\n\s*\n/', trim( (string) $c['body'] ) ) as $para ) { if ( '' !== trim( $para ) ) { $h .= '' . nl2br( wp_kses( brai_fill( trim( $para ), $esc ), $allow ) ) . '
'; } } if ( $coupon ) { $h .= '| '
. ' ' . esc_html( strtoupper( $coupon['code'] ) ) . ' '
. esc_html( brai_fill( $c['disc_text'], $raw ) ) . ' |
| ' . ( $img ? ' | ' : '' )
. '' . esc_html( $i['name'] ) . ' ' . esc_html__( 'Quantity:', 'basketwise' ) . ' ' . (int) $i['qty'] . '' . $stock . ' | '
. '' . esc_html( brai_money( $i['total'] ) ) . ' |
| ' : '' ) . ' | ' . esc_html__( 'Total', 'basketwise' ) . ' | ' . esc_html( brai_money( $total ) ) . ' ' . esc_html__( 'inc VAT, before delivery', 'basketwise' ) . ' |
' . esc_html( brai_fill( $c['button'], $raw ) ) . '
'; if ( '' !== trim( (string) $s['help'] ) ) { $h .= '' . esc_html( brai_fill( $s['help'], $raw ) ) . '
'; } if ( '' !== trim( (string) $s['signoff'] ) ) { $h .= '' . nl2br( esc_html( brai_fill( $s['signoff'], $raw ) ) ) . '
'; } // Every reminder must include an easy way to opt out (for example UK PECR, EU ePrivacy). $h .= '' . esc_html( brai_fill( $s['unsub_text'], $raw ) ) . ' ' . esc_html( $s['unsub_link'] ? $s['unsub_link'] : __( 'Unsubscribe', 'basketwise' ) ) . '.
'; return $h; } /** * Builds the whole reminder email. * * @param array $r Visitor row. * @param int $step 1, 2 or 3. * @param array|null $s Email settings. * @return array subject, html, inbox preview text. */ function brai_reminder_build( $r, $step, $s = null ) { $s = $s ? $s : brai_mail_settings(); $c = $s[ 'r' . (int) $step ] ?? $s['r1']; $coupon = ! empty( $c['disc'] ) ? brai_coupon_for( $r, $c ) : null; $vars = brai_mail_vars( $r, $s, $coupon ); $named = '' !== trim( (string) strtok( (string) ( $r['name'] ?? '' ), ' ' ) ); $subj = brai_fill( $named ? $c['subject'] : $c['subject_anon'], $vars ); $pre = brai_fill( $c['preheader'], $vars ); return array( $subj, brai_mail_frame( brai_reminder_html( $r, $step, $s, $coupon ), $s, $subj, $pre ), $pre ); } /** * Sends an HTML email with the reminder sender name and reply-to address. * * @param string $to Recipient(s). * @param string $subject Subject. * @param string $html Body. * @param array $s Email settings. * @return bool */ function brai_send_mail( $to, $subject, $html, $s ) { $headers = array( 'Content-Type: text/html; charset=UTF-8' ); if ( $s['reply_to'] ) { $headers[] = 'Reply-To: ' . $s['reply_to']; } $from = function () use ( $s ) { return $s['from_name']; }; add_filter( 'wp_mail_from_name', $from, 99 ); $ok = wp_mail( $to, $subject, $html, $headers ); remove_filter( 'wp_mail_from_name', $from, 99 ); return $ok; } /** * Sends reminder $step to the customer, or a test copy to $to. * * @param array $r Visitor row. * @param int $step 1, 2 or 3. * @param string $to Test recipient. * @param array $s Email settings (unsaved ones for tests). * @return bool */ function brai_send_reminder( $r, $step, $to = '', $s = null ) { $s = $s ? $s : brai_mail_settings(); if ( $to ) { $r['vid'] = 'test'; // Tests never create real discount codes. } list( $subj, $html ) = brai_reminder_build( $r, $step, $s ); /* translators: 1: email number, 2: number of emails. */ $prefix = $to ? sprintf( __( '[TEST %1$d of %2$d] ', 'basketwise' ), (int) $step, (int) $s['count'] ) : ''; $ok = brai_send_mail( $to ? $to : $r['email'], $prefix . $subj, $html, $s ); if ( $ok && ! $to ) { brai_log_mail( array( 'vid' => $r['vid'], 'kind' => 'reminder', 'step' => (int) $step, 'from_name' => $s['from_name'], 'from_email' => $s['reply_to'], 'to_email' => $r['email'], 'subject' => $subj, ) ); } return $ok; } /** A basket to show in previews and tests: the latest real one, or two random products. */ function brai_sample_row() { global $wpdb; $r = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM %i WHERE cart IS NOT NULL AND cart <> '' AND cart_value > 0 ORDER BY last_seen DESC LIMIT 1", brai_table( 'visitors' ) ), ARRAY_A ); if ( ! $r ) { $items = array(); foreach ( wc_get_products( array( 'status' => 'publish', 'limit' => 2, 'type' => 'simple', 'orderby' => 'rand', ) ) as $p ) { if ( '' !== $p->get_price() ) { $items[] = array( 'id' => $p->get_id(), 'name' => $p->get_name(), 'qty' => 1, 'total' => round( (float) wc_get_price_including_tax( $p ), 2 ), ); } } $r = array( 'cart' => wp_json_encode( $items ), 'cart_value' => 0, ); } $u = wp_get_current_user(); $r['vid'] = 'test'; $r['name'] = $u->first_name ? $u->first_name : 'Alex'; $r['email'] = $u->user_email; return $r; } /** * Cleans the email settings form. * * @param array $in Raw form values. * @return array */ function brai_mail_sanitize( $in ) { $d = brai_mail_settings(); $in = is_array( $in ) ? $in : array(); $allow = array( 'strong' => array(), 'b' => array(), 'em' => array(), 'i' => array(), 'br' => array(), 'a' => array( 'href' => true ), ); $col = function ( $v, $def ) { $v = sanitize_hex_color( (string) $v ); return $v ? $v : $def; }; $fonts = brai_fonts(); $o = array( 'logo' => esc_url_raw( (string) ( $in['logo'] ?? '' ) ), 'logo_width' => min( 560, max( 60, (int) ( $in['logo_width'] ?? 260 ) ) ), 'button_text' => in_array( $in['button_text'] ?? '', array( '#ffffff', '#1d2327' ), true ) ? $in['button_text'] : '', 'font' => isset( $fonts[ $in['font'] ?? '' ] ) ? $in['font'] : 'Helvetica,Arial,sans-serif', 'reply_to' => sanitize_email( (string) ( $in['reply_to'] ?? '' ) ), 'stock_under' => max( 1, min( 999, (int) ( $in['stock_under'] ?? 10 ) ) ), 'count' => max( 1, min( 3, (int) ( $in['count'] ?? 3 ) ) ), 'digest_to' => implode( ', ', array_filter( array_map( 'sanitize_email', preg_split( '/[\s,;]+/', (string) ( $in['digest_to'] ?? '' ) ) ) ) ), 'digest_hour' => max( 0, min( 23, (int) ( $in['digest_hour'] ?? 8 ) ) ), 'min_value' => max( 0, round( (float) wc_format_decimal( (string) ( $in['min_value'] ?? 0 ) ), 2 ) ), 'quiet_from' => max( 0, min( 23, (int) ( $in['quiet_from'] ?? 21 ) ) ), 'quiet_to' => max( 0, min( 23, (int) ( $in['quiet_to'] ?? 8 ) ) ), ); foreach ( array( 'accent', 'button_bg', 'footer_bg', 'footer_text', 'text', 'link', 'bg' ) as $k ) { $o[ $k ] = $col( $in[ $k ] ?? '', $d[ $k ] ); } foreach ( array( 'from_name', 'phone', 'address', 'unsub_text', 'unsub_link' ) as $k ) { $o[ $k ] = sanitize_text_field( (string) ( $in[ $k ] ?? '' ) ); } foreach ( array( 'help', 'signoff', 'footer_note' ) as $k ) { $o[ $k ] = sanitize_textarea_field( (string) ( $in[ $k ] ?? '' ) ); } foreach ( array( 'show_email', 'show_phone', 'show_address', 'show_images', 'show_stock', 'digest_weekends', 'weekly', 'logo_auto', 'quiet' ) as $k ) { $o[ $k ] = empty( $in[ $k ] ) ? 0 : 1; } if ( $o['logo_auto'] ) { $o['logo'] = ''; } $prev = 0; foreach ( array( 'r1', 'r2', 'r3' ) as $k ) { $x = (array) ( $in[ $k ] ?? array() ); $e = array( 'delay' => max( $prev + 1, min( 720, (int) ( $x['delay'] ?? $d[ $k ]['delay'] ) ) ), 'body' => wp_kses( str_replace( "\r", '', (string) ( $x['body'] ?? '' ) ), $allow ), 'disc_text' => sanitize_textarea_field( (string) ( $x['disc_text'] ?? '' ) ), 'disc' => empty( $x['disc'] ) ? 0 : 1, 'disc_type' => 'fixed_cart' === ( $x['disc_type'] ?? '' ) ? 'fixed_cart' : 'percent', 'disc_days' => max( 1, min( 90, (int) ( $x['disc_days'] ?? 7 ) ) ), 'disc_min' => max( 0, round( (float) ( $x['disc_min'] ?? 0 ), 2 ) ), ); $e['disc_amount'] = max( 0, round( (float) ( $x['disc_amount'] ?? 0 ), 2 ) ); if ( 'percent' === $e['disc_type'] ) { $e['disc_amount'] = min( 100, $e['disc_amount'] ); } foreach ( array( 'subject', 'subject_anon', 'preheader', 'heading', 'button' ) as $f ) { $e[ $f ] = sanitize_text_field( (string) ( $x[ $f ] ?? '' ) ); } $prev = $e['delay']; $o[ $k ] = $e; } return $o; } /* Hourly: send any reminders that are due. */ add_action( 'brai_recovery', function () { $live = brai_rec_live(); if ( ! $live ) { return; } $rules = brai_mail_settings(); if ( brai_quiet_now( $rules ) ) { return; // Quiet hours: anything due is sent by the first run after they end. } global $wpdb; $v = brai_table( 'visitors' ); $steps = brai_rec_steps(); $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE status IN ('basket','checkout') AND cart_value > 0 AND cart_value >= %f AND email <> '' AND reminders < %d AND last_seen >= %s AND last_seen < %s ORDER BY last_seen ASC LIMIT 100", $v, (float) $rules['min_value'], count( $steps ), gmdate( 'Y-m-d H:i:s', max( $live, time() - ( end( $steps ) + 120 ) * HOUR_IN_SECONDS ) ), gmdate( 'Y-m-d H:i:s', time() - $steps[0] * HOUR_IN_SECONDS ) ), ARRAY_A ); $sent = 0; foreach ( $rows as $r ) { $n = (int) $r['reminders']; $left = strtotime( $r['last_seen'] . ' UTC' ); if ( time() - $left < $steps[ $n ] * HOUR_IN_SECONDS ) { continue; } if ( brai_unsubscribed( $r['email'] ) || brai_has_ordered( $r['email'], $left ) ) { $wpdb->update( $v, array( 'reminders' => count( $steps ) ), array( 'vid' => $r['vid'] ) ); continue; } // Never two reminders close together (for example if the site had no visitors to run the schedule for a while). $gap = min( 12, max( 1, ( $steps[ $n ] - ( $n ? $steps[ $n - 1 ] : 0 ) ) / 2 ) ); if ( $r['reminded_at'] && time() - strtotime( $r['reminded_at'] . ' UTC' ) < $gap * HOUR_IN_SECONDS ) { continue; } if ( brai_send_reminder( $r, $n + 1 ) ) { $wpdb->update( $v, array( 'reminders' => $n + 1, 'reminded_at' => current_time( 'mysql', true ), ), array( 'vid' => $r['vid'] ) ); brai_event( $r['vid'], 'reminder', 0, $n + 1, $r['cart_value'] ); if ( ++$sent >= 40 ) { break; } } } } ); /* ---------- Morning summary email to the shop ---------- */ /** Next summary time (site time zone), as a timestamp. */ function brai_digest_next() { $s = brai_mail_settings(); $t = new DateTime( 'now', wp_timezone() ); $t->setTime( (int) $s['digest_hour'], 0, 0 ); if ( $t->getTimestamp() <= time() ) { $t->modify( '+1 day' ); } while ( ! $s['digest_weekends'] && (int) $t->format( 'N' ) > 5 ) { $t->modify( '+1 day' ); } return $t->getTimestamp(); } /** * Baskets that became abandoned between two times. * * @param int $from_ts From. * @param int $to_ts To. * @return array */ function brai_digest_rows( $from_ts, $to_ts ) { global $wpdb; $gap = brai_abandon_mins() * 60; return $wpdb->get_results( $wpdb->prepare( "SELECT * FROM %i WHERE status IN ('basket','checkout') AND cart_value > 0 AND last_seen >= %s AND last_seen < %s ORDER BY ( email <> '' ) DESC, cart_value DESC", brai_table( 'visitors' ), gmdate( 'Y-m-d H:i:s', $from_ts - $gap ), gmdate( 'Y-m-d H:i:s', $to_ts - $gap ) ), ARRAY_A ); } /** The period the next summary covers. */ function brai_digest_window() { $now = time(); $last = (int) get_option( 'brai_digest_last', 0 ); $from = $last ? $last : $now - DAY_IN_SECONDS; return array( max( $from, $now - 4 * DAY_IN_SECONDS ), $now ); } /** * The summary email body. * * @param array $rows Abandoned baskets. * @param int $from_ts From. * @param int $to_ts To. * @return string */ function brai_digest_html( $rows, $from_ts, $to_ts ) { $site = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); $base = brai_admin_url(); $total = 0; $known = 0; foreach ( $rows as $r ) { $total += (float) $r['cart_value']; $known += $r['email'] || $r['phone'] ? 1 : 0; } $fmt = 'D j M H:i'; $cell = 'padding:10px 12px;border-bottom:1px solid #e4e7ec;vertical-align:top;font-size:14px;line-height:1.45'; /* translators: 1: number of baskets, 2: shop name, 3: total value. */ $h = '' . esc_html( sprintf( _n( '%1$d abandoned basket on %2$s', '%1$d abandoned baskets on %2$s', count( $rows ), 'basketwise' ), count( $rows ), $site ) ) . ', ' . esc_html( sprintf( __( 'worth %s inc VAT.', 'basketwise' ), brai_money( $total ) ) ) . '
'; // phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment $h .= '' . esc_html( wp_date( $fmt, $from_ts ) . ' to ' . wp_date( $fmt, $to_ts ) ) . '. ' . esc_html( sprintf( _n( '%d left contact details.', '%d left contact details.', $known, 'basketwise' ), $known ) ) . '
'; // phpcs:ignore WordPress.WP.I18n.MissingTranslatorsComment $h .= '| ' . $who
. '' . esc_html( 'checkout' === $r['status'] ? __( 'Reached checkout', 'basketwise' ) : __( 'Left in basket', 'basketwise' ) ) . ', ' . esc_html( wp_date( $fmt, strtotime( $r['last_seen'] . ' UTC' ) ) ) . ' ' . esc_html__( 'From:', 'basketwise' ) . ' ' . esc_html( brai_source( $r['landing'], $r['referrer'], $r['src'] ?? '' ) ) . ' | '
. '' . implode( ' ', $lines ) . ' ' . esc_html( brai_money( $r['cart_value'] ) ) . '' . ' ' . esc_html__( 'View timeline', 'basketwise' ) . ' |
' . esc_html( sprintf( __( 'Open Basketwise on %s', 'basketwise' ), $site ) ) . '
'; return $h; } add_action( 'brai_digest', function () { list( $from, $to ) = brai_digest_window(); $rows = brai_digest_rows( $from, $to ); $s = brai_mail_settings(); update_option( 'brai_digest_last', $to, false ); if ( $rows && $s['digest_to'] ) { $site = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); wp_mail( $s['digest_to'], /* translators: 1: shop name, 2: number of baskets. */ sprintf( _n( '%1$s: %2$d abandoned basket', '%1$s: %2$d abandoned baskets', count( $rows ), 'basketwise' ), $site, count( $rows ) ), brai_digest_html( $rows, $from, $to ), array( 'Content-Type: text/html; charset=UTF-8' ) ); } wp_clear_scheduled_hook( 'brai_digest' ); wp_schedule_single_event( brai_digest_next(), 'brai_digest' ); } );