[ label, what it does, kind (task|email), defaults ]. * Merge tags in subjects and messages: {first_name}, {name}, {deal}, {site}, {my_name}. */ public static function catalog() { $site = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ); return (array) apply_filters( 'nodebook_recipes', array( 'new_lead' => array( 'label' => __( 'Get back to every new lead', 'nodebook' ), 'does' => __( 'Someone new fills in a form, books or comes in through the webhook: a next step "Get back to them" is on Today, for their owner.', 'nodebook' ), 'kind' => 'task', 'icon' => 'inbox', 'tone' => '#0071E3', 'defaults' => array( 'on' => true, 'days' => 0, ), ), 'stale_deal' => array( 'label' => __( 'Nudge deals that went quiet', 'nodebook' ), 'does' => __( 'An open deal has not moved for a while: a next step to check in, for the deal owner.', 'nodebook' ), 'kind' => 'task', 'icon' => 'clock', 'tone' => '#FF9500', 'days' => __( 'Quiet for (days)', 'nodebook' ), 'defaults' => array( 'on' => true, 'days' => 7, ), ), 'won_thanks' => array( 'label' => __( 'Thank customers when a deal is won', 'nodebook' ), 'does' => __( 'A deal is marked won: the customer gets a short thank-you email from the deal owner, and replies go to them.', 'nodebook' ), 'kind' => 'email', 'icon' => 'heart', 'tone' => '#FF2D55', 'defaults' => array( 'on' => false, 'subject' => __( 'Thank you, {first_name}', 'nodebook' ), 'body' => __( "Hi {first_name},\n\nThank you for choosing us. We're looking forward to it. If anything comes up, just reply to this email.\n\n{my_name}\n{site}", 'nodebook' ), ), ), 'lost_retry' => array( 'label' => __( 'Try again after a lost deal', 'nodebook' ), 'does' => __( 'A deal is lost: a next step to get back in touch later, when timing may be better.', 'nodebook' ), 'kind' => 'task', 'icon' => 'refresh', 'tone' => '#5856D6', 'days' => __( 'Try again after (days)', 'nodebook' ), 'defaults' => array( 'on' => false, 'days' => 90, ), ), 'welcome' => array( 'label' => __( 'Welcome new subscribers', 'nodebook' ), /* translators: %s: site name */ 'does' => sprintf( __( 'Someone subscribes to the %s newsletter: they get a welcome email straight away.', 'nodebook' ), $site ), 'kind' => 'email', 'icon' => 'mail', 'tone' => '#34C759', 'defaults' => array( 'on' => false, 'subject' => __( 'Welcome to {site}', 'nodebook' ), 'body' => __( "Hi {first_name},\n\nThanks for subscribing. You'll hear from us now and then with news and offers, never more than that. You can unsubscribe any time.\n\n{site}", 'nodebook' ), ), ), 'review_ask' => array( 'label' => __( 'Ask happy customers for a review', 'nodebook' ), 'does' => __( 'A few days after a deal is won or an order comes in: a next step to ask for a review, with the message and your review link ready to send by email or WhatsApp.', 'nodebook' ), 'kind' => 'review', 'icon' => 'star', 'tone' => '#FFCC00', 'days' => __( 'Ask after (days)', 'nodebook' ), 'defaults' => array( 'on' => false, 'days' => 3, 'url' => '', 'subject' => __( 'A quick favour, {first_name}?', 'nodebook' ), 'body' => __( "Hi {first_name}, Thank you again for choosing {site}. If you were happy with us, would you leave a short review? It takes a minute and helps others find us: {review_link} Thank you! {my_name}", 'nodebook' ), ), ), 'dates' => array( 'label' => __( 'Remember dates that matter', 'nodebook' ), 'does' => __( 'Birthdays and other yearly dates you keep on contacts: a next step on the day (or a few days before), so a short message never gets forgotten.', 'nodebook' ), 'kind' => 'task', 'icon' => 'calendar', 'tone' => '#AF52DE', 'days' => __( 'Remind me (days before)', 'nodebook' ), 'defaults' => array( 'on' => false, 'days' => 0, 'before' => true, 'fields' => array(), ), ), 'quiet_customer' => array( 'label' => __( 'Stay in touch with customers', 'nodebook' ), 'does' => __( 'A customer has not heard from you in a long time: a next step to catch up, for their owner.', 'nodebook' ), 'kind' => 'task', 'icon' => 'users', 'tone' => '#30B0C7', 'days' => __( 'No contact for (days)', 'nodebook' ), 'defaults' => array( 'on' => false, 'days' => 120, ), ), ) ); } /** Stored settings of every recipe, with defaults filled in. */ public static function all() { $saved = get_option( self::OPTION, array() ); $saved = is_array( $saved ) ? $saved : array(); $out = array(); foreach ( self::catalog() as $key => $r ) { $out[ $key ] = array_merge( $r['defaults'], isset( $saved[ $key ] ) && is_array( $saved[ $key ] ) ? $saved[ $key ] : array() ); } return $out; } public static function get( $key ) { $all = self::all(); return $all[ $key ] ?? array( 'on' => false ); } public static function on( $key ) { return ! empty( self::get( $key )['on'] ); } /** * Save one recipe. Only fields the recipe has are kept. * * @param string $key Recipe. * @param array $in on, days, subject, body. */ public static function save( $key, array $in ) { $catalog = self::catalog(); if ( ! isset( $catalog[ $key ] ) ) { return false; } $def = $catalog[ $key ]['defaults']; $row = array( 'on' => ! empty( $in['on'] ) ); if ( array_key_exists( 'days', $def ) ) { $days = isset( $in['days'] ) ? absint( $in['days'] ) : (int) $def['days']; if ( ! empty( $def['before'] ) ) { $row['days'] = min( 30, $days ); } else { $row['days'] = 0 === (int) $def['days'] ? 0 : min( 730, max( 1, $days ) ); } } if ( array_key_exists( 'url', $def ) ) { $url = isset( $in['url'] ) ? esc_url_raw( trim( (string) $in['url'] ), array( 'https', 'http' ) ) : ''; $row['url'] = mb_substr( $url, 0, 500 ); } if ( array_key_exists( 'fields', $def ) ) { $dates = array_keys( self::date_fields() ); $row['fields'] = array_values( array_intersect( array_map( 'sanitize_key', (array) ( $in['fields'] ?? array() ) ), $dates ) ); } if ( array_key_exists( 'subject', $def ) ) { $subject = isset( $in['subject'] ) ? trim( sanitize_text_field( (string) $in['subject'] ) ) : ''; $body = isset( $in['body'] ) ? trim( sanitize_textarea_field( (string) $in['body'] ) ) : ''; $row['subject'] = '' !== $subject ? mb_substr( $subject, 0, 190 ) : $def['subject']; $row['body'] = '' !== $body ? mb_substr( $body, 0, 5000 ) : $def['body']; } $saved = get_option( self::OPTION, array() ); $saved = is_array( $saved ) ? $saved : array(); $saved[ $key ] = $row; update_option( self::OPTION, $saved, false ); return true; } /* ------------------------------------------------------------------ * * Triggers * ------------------------------------------------------------------ */ /** Not for sample data, imports or contacts the visitor cannot reach. */ private static function quiet() { return ( class_exists( 'Nodebook_Sample' ) && Nodebook_Sample::$running ) || (bool) apply_filters( 'nodebook_recipes_paused', false ); } private static function skip_contact( $contact_id ) { return ! $contact_id || ( class_exists( 'Nodebook_Sample' ) && Nodebook_Sample::is_sample( (int) $contact_id ) ); } /** * A new person came in through a form, booking or the webhook. * * @param int $id Contact. * @param array $data Captured fields. * @param string $source Source label. * @param bool $created Whether the contact is new. */ public static function on_captured( $id, $data, $source, $created ) { if ( ! $created || self::quiet() || self::skip_contact( $id ) || ! self::on( 'new_lead' ) ) { return; } $c = Nodebook_Contacts::get( (int) $id ); if ( ! $c ) { return; } $name = Nodebook_Contacts::display_name( $c ); /* translators: %s: contact name */ $title = sprintf( __( 'Get back to %s', 'nodebook' ), $name ) . ( '' !== (string) $source ? ' · ' . $source : '' ); self::task( 'new_lead', (int) $id, $title, Nodebook_Tasks::end_of_today(), self::owner_of( $c ) ); } /** * A deal was won or lost. * * @param int $deal_id Deal. * @param string $outcome won|lost|''. * @param string $reason Lost reason. */ public static function on_deal_closed( $deal_id, $outcome, $reason ) { if ( self::quiet() ) { return; } $d = Nodebook_Deals::get( (int) $deal_id ); if ( ! $d || self::skip_contact( (int) $d['contact_id'] ) ) { return; } $c = Nodebook_Contacts::get( (int) $d['contact_id'] ); if ( ! $c ) { return; } if ( 'won' === $outcome ) { self::plan_review( $c, (int) $d['owner_id'] ); } if ( 'won' === $outcome && self::on( 'won_thanks' ) && ! self::did( 'won_thanks', (int) $c['id'], (int) $deal_id ) ) { $sender = (int) $d['owner_id'] ? (int) $d['owner_id'] : self::owner_of( $c ); self::email( 'won_thanks', $c, $sender, array( 'deal' => $d['title'] ), (int) $deal_id ); } elseif ( 'lost' === $outcome && self::on( 'lost_retry' ) && ! self::did( 'lost_retry', (int) $c['id'], (int) $deal_id ) ) { $days = max( 1, (int) self::get( 'lost_retry' )['days'] ); /* translators: %s: contact name */ $title = sprintf( __( 'Try again with %s', 'nodebook' ), Nodebook_Contacts::display_name( $c ) ) . ' · ' . $d['title']; $due = gmdate( 'Y-m-d H:i:s', strtotime( Nodebook_Tasks::end_of_today() . ' UTC' ) + $days * DAY_IN_SECONDS ); self::task( 'lost_retry', (int) $c['id'], $title, $due, (int) $d['owner_id'] ? (int) $d['owner_id'] : self::owner_of( $c ), (int) $deal_id ); } } /** * Email consent changed: welcome someone who just subscribed. * * @param int $contact_id Contact. * @param string $status New status. * @param string $old Old status. */ public static function on_email_status( $contact_id, $status, $old ) { if ( 'subscribed' !== $status || 'subscribed' === $old || self::quiet() || self::skip_contact( $contact_id ) || ! self::on( 'welcome' ) ) { return; } if ( self::did( 'welcome', (int) $contact_id, 0 ) ) { return; // Once per person, also when they unsubscribe and come back. } $c = Nodebook_Contacts::get( (int) $contact_id ); if ( $c ) { self::email( 'welcome', $c, 0 ); } } /** Daily: deals that went quiet, customers nobody talked to in a long time. */ public static function daily() { if ( self::quiet() ) { return array(); } $made = array( 'stale_deal' => self::stale_deals(), 'quiet_customer' => self::quiet_customers(), 'dates' => self::dates(), ); return $made; } private static function stale_deals() { global $wpdb; if ( ! self::on( 'stale_deal' ) || ! Nodebook_Deals::on() ) { return 0; } $days = max( 1, (int) self::get( 'stale_deal' )['days'] ); $cut = gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ); // Open deals untouched since the cut, without an open next step of their own. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own tables. $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT d.* FROM %i d WHERE d.outcome = '' AND d.contact_id > 0 AND d.updated_at < %s AND COALESCE(d.stage_at, d.created_at) < %s AND NOT EXISTS ( SELECT 1 FROM %i t WHERE t.deal_id = d.id AND t.done_at IS NULL ) ORDER BY d.updated_at ASC LIMIT %d", Nodebook_Deals::table(), $cut, $cut, Nodebook_Tasks::table(), self::DAILY_LIMIT * 2 ), ARRAY_A ); $n = 0; foreach ( $rows as $d ) { if ( $n >= self::DAILY_LIMIT || self::skip_contact( (int) $d['contact_id'] ) ) { continue; } // Nudged already and still quiet since: wait another period before nudging again. $last = self::last( 'stale_deal', (int) $d['contact_id'], (int) $d['id'] ); if ( $last && strtotime( $last . ' UTC' ) > time() - $days * DAY_IN_SECONDS ) { continue; } $c = Nodebook_Contacts::get( (int) $d['contact_id'] ); if ( ! $c ) { continue; } /* translators: %s: deal title */ $title = sprintf( __( 'Check in: %s', 'nodebook' ), $d['title'] ); if ( self::task( 'stale_deal', (int) $c['id'], $title, Nodebook_Tasks::end_of_today(), (int) $d['owner_id'] ? (int) $d['owner_id'] : self::owner_of( $c ), (int) $d['id'] ) ) { ++$n; } } return $n; } private static function quiet_customers() { global $wpdb; if ( ! self::on( 'quiet_customer' ) ) { return 0; } $days = max( 1, (int) self::get( 'quiet_customer' )['days'] ); $cut = gmdate( 'Y-m-d H:i:s', time() - $days * DAY_IN_SECONDS ); // Customers with no follow-up since the cut (or ever, if they became a customer before it) and no open next step. // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own tables. $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT c.* FROM %i c WHERE c.status = 'customer' AND COALESCE(c.followed_up_at, c.created_at) < %s AND NOT EXISTS ( SELECT 1 FROM %i t WHERE t.contact_id = c.id AND t.done_at IS NULL ) ORDER BY COALESCE(c.followed_up_at, c.created_at) ASC LIMIT %d", Nodebook_Contacts::table(), $cut, Nodebook_Tasks::table(), self::DAILY_LIMIT * 2 ), ARRAY_A ); $n = 0; foreach ( $rows as $c ) { if ( $n >= self::DAILY_LIMIT || self::skip_contact( (int) $c['id'] ) ) { continue; } $last = self::last( 'quiet_customer', (int) $c['id'], 0 ); if ( $last && strtotime( $last . ' UTC' ) > time() - $days * DAY_IN_SECONDS ) { continue; } /* translators: %s: contact name */ $title = sprintf( __( 'Catch up with %s', 'nodebook' ), Nodebook_Contacts::display_name( $c ) ); if ( self::task( 'quiet_customer', (int) $c['id'], $title, Nodebook_Tasks::end_of_today(), self::owner_of( $c ) ) ) { ++$n; } } return $n; } /** * An order (or paid booking) came in: plan the review request. * * @param int $contact_id Contact. * @param string $type Conversion type. */ public static function on_conversion( $contact_id, $type, $title = '', $data = array() ) { if ( ! in_array( $type, array( 'order', 'booking' ), true ) || self::quiet() || self::skip_contact( $contact_id ) ) { return; } $c = Nodebook_Contacts::get( (int) $contact_id ); if ( $c ) { self::plan_review( $c, 0 ); } } /** Review requests: on, with a link, and not asked (or planned) in the last half year. */ private static function plan_review( array $c, $owner ) { if ( ! self::on( 'review_ask' ) || '' === Nodebook_Reviews::url() || ! Nodebook_Reviews::can_ask( $c ) ) { return; } $cut = time() - Nodebook_Reviews::AGAIN_DAYS * DAY_IN_SECONDS; foreach ( array( self::last( 'review_ask', (int) $c['id'], 0 ), Nodebook_Reviews::asked_at( (int) $c['id'] ) ) as $when ) { if ( $when && strtotime( $when . ' UTC' ) > $cut ) { return; // Planned or asked recently. } } $days = max( 1, (int) self::get( 'review_ask' )['days'] ); $due = gmdate( 'Y-m-d H:i:s', strtotime( Nodebook_Tasks::end_of_today() . ' UTC' ) + $days * DAY_IN_SECONDS ); /* translators: %s: contact name */ $title = sprintf( __( 'Ask %s for a review', 'nodebook' ), Nodebook_Contacts::display_name( $c ) ); self::task( 'review_ask', (int) $c['id'], $title, $due, $owner ? (int) $owner : self::owner_of( $c ) ); } /** Contact date fields: key => label. */ public static function date_fields() { $out = array(); foreach ( Nodebook_Props::defs( 'contact' ) as $key => $d ) { if ( 'date' === ( $d['type'] ?? '' ) ) { $out[ $key ] = (string) $d['label']; } } return $out; } /** Date fields the dates recipe watches: the ones picked, or all of them when none are picked. */ public static function watched_dates() { $all = self::date_fields(); $pick = (array) ( self::get( 'dates' )['fields'] ?? array() ); $pick = array_values( array_intersect( $pick, array_keys( $all ) ) ); return $pick ? array_intersect_key( $all, array_flip( $pick ) ) : $all; } /** Daily: yearly dates (birthdays, anniversaries) coming up today or in N days. */ private static function dates() { global $wpdb; $fields = self::watched_dates(); if ( ! self::on( 'dates' ) || ! $fields ) { return 0; } $ahead = (int) self::get( 'dates' )['days']; $target = ( new DateTimeImmutable( 'now', wp_timezone() ) )->setTime( 12, 0 )->modify( '+' . $ahead . ' days' ); $md = $target->format( 'm-d' ); $also = array( $md ); // 29 February is remembered on 28 February in other years. if ( '02-28' === $md && ! (int) $target->format( 'L' ) ) { $also[] = '02-29'; } $ph = implode( ',', array_fill( 0, count( $fields ), '%s' ) ); $args = array_merge( array( Nodebook_Props::table() ), array_keys( $fields ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- the plugin's own table; $ph is a list of %s. $rows = (array) $wpdb->get_results( $wpdb->prepare( "SELECT object_id, field_key, value_date FROM %i WHERE object_type = 'contact' AND field_key IN ($ph) AND value_date IS NOT NULL", $args ), ARRAY_A ); $n = 0; $year = $target->format( 'Y' ); $due = get_gmt_from_date( $target->format( 'Y-m-d 09:00:00' ) ); foreach ( $rows as $r ) { if ( $n >= self::DAILY_LIMIT * 2 || ! in_array( substr( (string) $r['value_date'], 5, 5 ), $also, true ) ) { continue; } $cid = (int) $r['object_id']; if ( self::skip_contact( $cid ) || self::did_date( $cid, (string) $r['field_key'], $year ) ) { continue; } $c = Nodebook_Contacts::get( $cid ); if ( ! $c || in_array( (string) $c['status'], array( 'lost', 'archived' ), true ) ) { continue; } $label = $fields[ $r['field_key'] ]; $born = (int) substr( (string) $r['value_date'], 0, 4 ); $turns = $born > 1900 && $born < (int) $year ? (int) $year - $born : 0; /* translators: 1: date name (Birthday), 2: contact name */ $title = sprintf( __( '%1$s: %2$s', 'nodebook' ), $label, Nodebook_Contacts::display_name( $c ) ); if ( $turns && preg_match( '/birth|cumple|verjaar|geburt|nacim/i', $label . ' ' . $r['field_key'] ) ) { /* translators: %s: age */ $title .= ' · ' . sprintf( __( 'turns %s', 'nodebook' ), number_format_i18n( $turns ) ); } elseif ( $turns && preg_match( '/anniv|aniver|jubil|since|sinds|desde/i', $label . ' ' . $r['field_key'] ) ) { /* translators: %s: number of years */ $title .= ' · ' . sprintf( _n( '%s year', '%s years', $turns, 'nodebook' ), number_format_i18n( $turns ) ); } if ( $ahead ) { $title .= ' · ' . date_i18n( get_option( 'date_format' ), $target->getTimestamp() ); } $id = Nodebook_Tasks::add( $cid, $title, array( 'due_at' => $due, 'assignee_id' => self::owner_of( $c ), 'created_by' => 0, ) ); if ( $id ) { self::log( 'dates', $cid, 0, array( 'task' => $id, 'field' => (string) $r['field_key'], 'year' => $year, ) ); ++$n; } } return $n; } private static function did_date( $contact_id, $field, $year ) { global $wpdb; $like = '%' . $wpdb->esc_like( '"recipe":"dates"' ) . '%' . $wpdb->esc_like( '"field":' . wp_json_encode( (string) $field ) . ',"year":' . wp_json_encode( (string) $year ) ) . '%'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. return (bool) $wpdb->get_var( $wpdb->prepare( "SELECT 1 FROM %i WHERE contact_id = %d AND type = 'auto' AND data LIKE %s LIMIT 1", Nodebook_Activities::table(), $contact_id, $like ) ); } /* ------------------------------------------------------------------ * * Doing things * ------------------------------------------------------------------ */ /** * Who gets a contact's next steps: their owner, else the default owner from Settings, else the site's * administrator (an unassigned step would show on nobody's "Mine" in a team). */ private static function owner_of( array $c ) { $owner = (int) ( $c['owner_id'] ?? 0 ); $owner = $owner ? $owner : (int) Nodebook_Settings::get( 'default_owner' ); if ( $owner ) { return $owner; } $admin = get_user_by( 'email', (string) get_option( 'admin_email' ) ); if ( $admin && user_can( $admin, Nodebook_Admin::cap() ) ) { return (int) $admin->ID; } $first = get_users( array( 'role' => 'administrator', 'number' => 1, 'orderby' => 'ID', 'fields' => 'ID', ) ); return $first ? (int) $first[0] : 0; } /** * Create a task and log it. * * @return int Task ID. */ private static function task( $key, $contact_id, $title, $due, $assignee, $deal_id = 0 ) { $id = Nodebook_Tasks::add( $contact_id, $title, array( 'due_at' => $due, 'assignee_id' => (int) $assignee, 'created_by' => 0, 'deal_id' => (int) $deal_id, ) ); if ( $id ) { self::log( $key, $contact_id, $deal_id, array( 'task' => $id ) ); } return $id; } /** * Send a recipe's email and log it. Never to someone who bounced or marked email as spam. * * @param string $key Recipe. * @param array $c Contact. * @param int $sender User whose inbox gets replies (0: the site). * @param array $tags Extra merge tags. * @param int $object_id Deal, if any. */ private static function email( $key, array $c, $sender, array $tags = array(), $object_id = 0 ) { if ( ! is_email( (string) $c['email'] ) || in_array( (string) ( $c['email_status'] ?? '' ), array( 'bounced', 'complained' ), true ) ) { return false; } $r = self::get( $key ); $user = $sender ? get_userdata( (int) $sender ) : null; $tags = array_merge( array( 'first_name' => trim( (string) $c['first_name'] ), 'name' => Nodebook_Contacts::display_name( $c ), 'site' => wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), 'my_name' => $user ? ( $user->first_name ? $user->first_name : $user->display_name ) : wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ), 'deal' => '', ), $tags ); $subject = self::fill( (string) $r['subject'], $tags ); $body = self::fill( (string) $r['body'], $tags ); $sent = Nodebook_Email::send( (int) $c['id'], $subject, $body, (int) $sender, array( 'auto' => self::catalog()[ $key ]['label'], 'unsubscribe' => 'welcome' === $key, ) ); if ( true === $sent ) { self::log( $key, (int) $c['id'], (int) $object_id, array( 'subject' => $subject, 'text' => mb_substr( $body, 0, 5000 ) ) ); return true; } return false; } /** Replace merge tags; "Hi {first_name}," without a name becomes "Hi,". */ public static function fill( $text, array $tags ) { foreach ( $tags as $k => $v ) { $text = str_replace( '{' . $k . '}', (string) $v, $text ); } $text = preg_replace( '/ +([,.!?])/', '$1', $text ); return trim( preg_replace( '/[ \t]{2,}/', ' ', $text ) ); } /** Remember that a recipe ran for a contact (and deal), so it never does the same thing twice. */ private static function log( $key, $contact_id, $object_id, array $data = array() ) { $catalog = self::catalog(); Nodebook_Activities::add( (int) $contact_id, 'auto', /* translators: %s: automation name */ sprintf( __( 'Automation: %s', 'nodebook' ), $catalog[ $key ]['label'] ), array( 'object_id' => (int) $object_id, 'data' => array( 'recipe' => $key ) + $data, ) ); } /** When a recipe last ran for a contact (and deal), as GMT, or ''. */ private static function last( $key, $contact_id, $object_id ) { global $wpdb; $like = '%' . $wpdb->esc_like( '"recipe":"' . $key . '"' ) . '%'; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. return (string) $wpdb->get_var( $wpdb->prepare( "SELECT MAX(created_at) FROM %i WHERE contact_id = %d AND type = 'auto' AND object_id = %d AND data LIKE %s", Nodebook_Activities::table(), $contact_id, $object_id, $like ) ); } private static function did( $key, $contact_id, $object_id ) { return '' !== self::last( $key, $contact_id, $object_id ); } /** What the recipes did in the last 30 days: key => count. */ public static function counts() { global $wpdb; $since = gmdate( 'Y-m-d H:i:s', time() - 30 * DAY_IN_SECONDS ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the plugin's own table. $rows = (array) $wpdb->get_col( $wpdb->prepare( "SELECT data FROM %i WHERE type = 'auto' AND created_at >= %s", Nodebook_Activities::table(), $since ) ); $out = array(); foreach ( $rows as $json ) { $d = json_decode( (string) $json, true ); if ( isset( $d['recipe'] ) ) { $out[ $d['recipe'] ] = ( $out[ $d['recipe'] ] ?? 0 ) + 1; } } return $out; } }