get_row( $wpdb->prepare( 'SELECT COUNT(*) AS leads, SUM(CASE WHEN orders_count > 0 THEN 1 ELSE 0 END) AS customers, SUM(total_spent) AS revenue FROM %i WHERE created_at >= %s', $ct, $since ), ARRAY_A ); // Known contacts seen in the period (indexed on the contacts table, not a scan of visits). $ret = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM %i WHERE last_seen >= %s AND visits_count > 0', $ct, $since ) ); return array( 'leads' => (int) ( $row['leads'] ?? 0 ), 'customers' => (int) ( $row['customers'] ?? 0 ), 'revenue' => (float) ( $row['revenue'] ?? 0 ), 'returning' => $ret, ); } /** Leads, customers and revenue per first-touch source/medium. */ public static function by_source( $since, $limit = 25 ) { global $wpdb; // phpcs:ignore PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.NotPrepared -- IDs are integers and type lists are fixed placeholders; values go through prepare(). $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT first_source AS source, first_medium AS medium, COUNT(*) AS leads, SUM(CASE WHEN orders_count > 0 THEN 1 ELSE 0 END) AS customers, SUM(total_spent) AS revenue FROM %i WHERE created_at >= %s GROUP BY first_source, first_medium ORDER BY leads DESC, revenue DESC LIMIT %d', Nodebook_Contacts::table(), $since, $limit ), ARRAY_A ); return array_map( array( __CLASS__, 'rate' ), (array) $rows ); } public static function by_campaign( $since, $limit = 15 ) { global $wpdb; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT first_campaign AS campaign, first_source AS source, first_medium AS medium, COUNT(*) AS leads, SUM(CASE WHEN orders_count > 0 THEN 1 ELSE 0 END) AS customers, SUM(total_spent) AS revenue FROM %i WHERE created_at >= %s AND first_campaign <> '' GROUP BY first_campaign, first_source, first_medium ORDER BY leads DESC LIMIT %d", Nodebook_Contacts::table(), $since, $limit ), ARRAY_A ); return array_map( array( __CLASS__, 'rate' ), (array) $rows ); } private static function rate( array $r ) { $r['leads'] = (int) $r['leads']; $r['customers'] = (int) $r['customers']; $r['revenue'] = (float) $r['revenue']; $r['rate'] = $r['leads'] ? round( $r['customers'] / $r['leads'] * 100, 1 ) : 0; return $r; } /** First conversion (form, order, booking, appointment) per contact in the window: contact_id => GMT datetime. */ private static function conversions( $since ) { global $wpdb; static $cache = array(); if ( isset( $cache[ $since ] ) ) { return $cache[ $since ]; } $types = Nodebook_Conversions::type_list(); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- one %s placeholder per conversion type. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT contact_id, MIN(created_at) AS conv FROM %i USE INDEX (type_created) WHERE type IN (' . Nodebook_Sql::list_of( count( $types ), '%s' ) . ') AND contact_id > 0 AND created_at >= %s GROUP BY contact_id', array_merge( array( Nodebook_Activities::table() ), $types, array( $since ) ) ), ARRAY_A ); $out = array(); foreach ( (array) $rows as $r ) { $out[ (int) $r['contact_id'] ] = $r['conv']; } arsort( $out ); // Newest conversions first (samples below take the most recent). $cache[ $since ] = $out; return $out; } public static function path( $url ) { $p = (string) wp_parse_url( (string) $url, PHP_URL_PATH ); $p = '/' . trim( $p, '/' ); return '/' === $p ? '/' : $p . '/'; } /** * Pages that say nothing about interest: cart, checkout, thank-you and account pages (they come after the * decision), plus login and admin. */ public static function is_utility( $path ) { static $own = null; if ( null === $own ) { $own = array(); if ( function_exists( 'wc_get_page_id' ) ) { foreach ( array( 'cart', 'checkout', 'myaccount' ) as $page ) { $id = (int) wc_get_page_id( $page ); if ( $id > 0 ) { $own[] = self::path( (string) get_permalink( $id ) ); } } } $own = array_diff( $own, array( '/' ) ); } foreach ( $own as $p ) { if ( 0 === strpos( $path, $p ) ) { return true; } } return (bool) preg_match( '#/(cart|checkout|my-account|order-received|order-pay|thank-?you|thanks|gracias|bedankt|danke|merci|carrito|finalizar-compra|mi-cuenta|wp-login\.php|wp-admin)(/|$)#i', $path ); } /** Rows analysed per report; beyond this the report describes the most recent activity. */ const SAMPLE_VIEWS = 30000; const SAMPLE_CONVERSIONS = 2000; /** * Pages known contacts read, and how many of those readers converted afterwards. * Large sites: based on the latest 30,000 page views in the period and the latest 2,000 conversions. */ public static function pages( $since, $limit = 20 ) { global $wpdb; $a = Nodebook_Activities::table(); $conv = self::conversions( $since ); $from = gmdate( 'Y-m-d H:i:s', strtotime( $since . ' UTC' ) - 180 * DAY_IN_SECONDS ); $views = $wpdb->get_results( $wpdb->prepare( "SELECT contact_id, url FROM %i WHERE type = 'pageview' AND created_at >= %s AND contact_id > 0 ORDER BY created_at DESC LIMIT %d", $a, $since, self::SAMPLE_VIEWS ), ARRAY_A ); $sample = array_slice( $conv, 0, self::SAMPLE_CONVERSIONS, true ); $readers = array(); $before = array(); foreach ( (array) $views as $r ) { $p = self::path( $r['url'] ); if ( ! self::is_utility( $p ) ) { $readers[ $p ][ (int) $r['contact_id'] ] = true; } } foreach ( array_chunk( array_keys( $sample ), 500 ) as $ids ) { $rows = $wpdb->get_results( $wpdb->prepare( "SELECT contact_id, url, MIN(created_at) AS first_at FROM %i WHERE type = 'pageview' AND contact_id IN (" . implode( ',', array_fill( 0, count( $ids ), '%d' ) ) . ') AND created_at >= %s GROUP BY contact_id, url', array_merge( array( $a ), $ids, array( $from ) ) ), ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.PreparedSQL.NotPrepared -- placeholders generated per ID. foreach ( (array) $rows as $r ) { $cid = (int) $r['contact_id']; $p = self::path( $r['url'] ); if ( $r['first_at'] <= $sample[ $cid ] && ! self::is_utility( $p ) ) { $before[ $p ][ $cid ] = true; $readers[ $p ][ $cid ] = true; } } } $total = count( $sample ); $out = array(); foreach ( $readers as $p => $set ) { $n = count( $set ); $b = isset( $before[ $p ] ) ? count( $before[ $p ] ) : 0; if ( ! $b ) { continue; // Only pages that came before a conversion. } $out[] = array( 'path' => $p, 'readers' => $n, 'converted' => $b, 'rate' => $n ? round( $b / $n * 100, 1 ) : 0, 'share' => $total ? round( $b / $total * 100, 1 ) : 0, 'who' => array_slice( array_keys( $before[ $p ] ), 0, 8 ), ); } usort( $out, static function ( $x, $y ) { return array( $y['converted'], $y['readers'] ) <=> array( $x['converted'], $x['readers'] ); } ); return array( 'rows' => array_slice( $out, 0, $limit ), 'conversions' => count( $conv ), 'sampled' => count( (array) $views ) >= self::SAMPLE_VIEWS || count( $conv ) > self::SAMPLE_CONVERSIONS, ); } const REBUILD_HOOK = 'nodebook_build_report'; /** * Report data for a period. Served from a stored copy; a copy older than 3 hours is still shown * while a fresh one is built in the background, so the Journeys screen never waits on a busy site. */ public static function cached( $days, $fresh = false ) { $days = (int) $days; $key = 'nodebook_report_' . $days; $data = $fresh ? false : get_option( $key ); // built = 1: marked out of date after contacts changed; rebuild now, on this visit. if ( ! is_array( $data ) || empty( $data['built'] ) || (int) $data['built'] < 1000000 ) { return self::build( $days ); } if ( time() - (int) $data['built'] > 3 * HOUR_IN_SECONDS && ! wp_next_scheduled( self::REBUILD_HOOK, array( $days ) ) ) { wp_schedule_single_event( time(), self::REBUILD_HOOK, array( $days ) ); } return $data; } /** Build and store a period's report. Also the background (cron) callback. */ public static function build( $days ) { $days = (int) $days; $since = self::since( $days ); // Behaviour analysis (pages, timing, interests) looks at most 12 months back, also for "All time". $recent = 0 === $days || $days > 365 ? self::since( 365 ) : $since; $data = array( 'built' => time(), 'capped' => $recent !== $since, 'totals' => self::totals( $since ), 'sources' => self::by_source( $since ), 'campaign' => self::by_campaign( $since ), 'pages' => self::pages( $recent ), 'ttc' => self::time_to_convert( $recent ), 'demand' => Nodebook_Interests::in_demand( $recent, 12 ), 'accounts' => Nodebook_Interests::companies_active( $recent, 12 ), ); update_option( 'nodebook_report_' . $days, $data, false ); return $data; } private static function median( array $values ) { if ( ! $values ) { return null; } sort( $values ); $n = count( $values ); $m = intdiv( $n, 2 ); return $n % 2 ? $values[ $m ] : ( $values[ $m - 1 ] + $values[ $m ] ) / 2; } /** Median days and visits from first touch to first conversion. One grouped query, any size. */ public static function time_to_convert( $since ) { global $wpdb; $a = Nodebook_Activities::table(); $types = Nodebook_Conversions::type_list(); $sql = "SELECT x.contact_id, x.conv, c.first_touch_at, c.created_at AS added, MIN(v.created_at) AS first_visit, SUM(CASE WHEN v.type = 'visit' AND v.created_at <= x.conv THEN 1 ELSE 0 END) AS visits FROM ( SELECT contact_id, MIN(created_at) AS conv FROM %i USE INDEX (type_created) WHERE type IN (" . Nodebook_Sql::list_of( count( $types ), '%s' ) . ") AND contact_id > 0 AND created_at >= %s GROUP BY contact_id ORDER BY conv DESC LIMIT %d ) x INNER JOIN %i c ON c.id = x.contact_id LEFT JOIN %i v ON v.contact_id = x.contact_id AND v.type IN ('visit','pageview') GROUP BY x.contact_id, x.conv, c.first_touch_at, c.created_at"; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- $sql is fixed SQL with one %s placeholder per conversion type. $rows = $wpdb->get_results( $wpdb->prepare( $sql, array_merge( array( $a ), $types, array( $since, self::SAMPLE_CONVERSIONS, Nodebook_Contacts::table(), $a ) ) ), ARRAY_A ); $days = array(); $visits = array(); foreach ( (array) $rows as $r ) { // Imported history (past orders brought in later) says nothing about how long people take: skip it. if ( strtotime( $r['conv'] . ' UTC' ) < strtotime( $r['added'] . ' UTC' ) - DAY_IN_SECONDS ) { continue; } $start = min( array_filter( array( $r['first_touch_at'], $r['first_visit'], $r['conv'] ) ) ); $days[] = max( 0, ( strtotime( $r['conv'] . ' UTC' ) - strtotime( $start . ' UTC' ) ) / DAY_IN_SECONDS ); $visits[] = (int) $r['visits']; } return array( 'conversions' => count( self::conversions( $since ) ), 'measured' => count( $days ), 'days' => null === self::median( $days ) ? null : round( self::median( $days ), 1 ), 'visits' => self::median( $visits ), ); } /** Journey summary for one contact (profile card). */ public static function journey( array $c ) { global $wpdb; $a = Nodebook_Activities::table(); $types = Nodebook_Conversions::type_list(); $sql = 'SELECT type, title, created_at FROM %i WHERE contact_id = %d AND type IN (' . Nodebook_Sql::list_of( count( $types ), '%s' ) . ') ORDER BY created_at ASC, id ASC LIMIT 1'; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- $sql is fixed SQL with one %s placeholder per conversion type. $conv = $wpdb->get_row( $wpdb->prepare( $sql, array_merge( array( $a, (int) $c['id'] ), $types ) ), ARRAY_A ); $order = $wpdb->get_row( $wpdb->prepare( "SELECT title, created_at FROM %i WHERE contact_id = %d AND type = 'order' ORDER BY created_at ASC, id ASC LIMIT 1", $a, $c['id'] ), ARRAY_A ); $first = $wpdb->get_var( $wpdb->prepare( "SELECT MIN(created_at) FROM %i WHERE contact_id = %d AND type IN ('visit','pageview')", $a, $c['id'] ) ); $start = array_filter( array( $c['first_touch_at'], $first, $conv ? $conv['created_at'] : null, $c['created_at'] ) ); $start = $start ? min( $start ) : $c['created_at']; $out = array( 'source' => Nodebook_Attribution::label( $c['first_source'], $c['first_medium'] ), 'has_source' => '' !== (string) $c['first_source'], 'campaign' => $c['first_campaign'], 'landing' => $c['landing_page'], 'referrer' => $c['first_referrer'], 'start' => $start, 'conversion' => $conv, 'first_order' => $order, 'visits_before' => $conv ? (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM %i WHERE contact_id = %d AND type = 'visit' AND created_at <= %s", $a, $c['id'], $conv['created_at'] ) ) : null, 'days' => $conv ? max( 0, round( ( strtotime( $conv['created_at'] . ' UTC' ) - strtotime( $start . ' UTC' ) ) / DAY_IN_SECONDS, 1 ) ) : null, ); return apply_filters( 'nodebook_contact_journey', $out, $c ); } }