prefix . 'aieo_product_session_metrics'; if ( ! self::table_has( $t, array( 'product_id', 'engagement_score', 'total_views' ) ) ) { return array(); } $rows = $wpdb->get_results( "SELECT product_id, PERCENT_RANK() OVER (ORDER BY engagement_score) AS pct FROM `{$t}` WHERE total_views > 0", ARRAY_A ); $map = array(); foreach ( (array) $rows as $r ) { $map[ (int) $r['product_id'] ] = (float) $r['pct']; } return $map; } private static function content_percentiles( $post_type ) { global $wpdb; $t = $wpdb->prefix . 'aieo_core_content_vitals'; if ( ! self::table_has( $t, array( 'content_id', 'post_type', 'content_demand', 'views_lifetime' ) ) ) { return array(); } $rows = $wpdb->get_results( $wpdb->prepare( "SELECT content_id, PERCENT_RANK() OVER (ORDER BY content_demand) AS pct FROM `{$t}` WHERE post_type = %s AND (views_lifetime > 0 OR content_demand > 0)", $post_type ), ARRAY_A ); $map = array(); foreach ( (array) $rows as $r ) { $map[ (int) $r['content_id'] ] = (float) $r['pct']; } return $map; } public static function order_related( array $rows ) { $gamma = self::gamma(); if ( $gamma <= 0 || empty( $rows ) ) { return $rows; } $maps = array(); $idx = 0; foreach ( $rows as &$row ) { $type = (string) ( $row['target_type'] ?? '' ); if ( ! isset( $maps[ $type ] ) ) { $maps[ $type ] = self::behavioral_percentiles( $type ); } $pct = $maps[ $type ][ (int) ( $row['target_id'] ?? 0 ) ] ?? null; $row['behavioral_pct'] = ( null === $pct ) ? null : round( $pct, 4 ); $effective = ( null === $pct ) ? 0.5 : $pct; $row['display_score'] = round( (float) ( $row['score'] ?? 0 ) * ( 1 + $gamma * $effective ), 4 ); $row['__idx'] = $idx++; } unset( $row ); usort( $rows, static function ( $a, $b ) { if ( $a['display_score'] !== $b['display_score'] ) { return ( $a['display_score'] < $b['display_score'] ) ? 1 : -1; } return $a['__idx'] <=> $b['__idx']; } ); $rank = 0; foreach ( $rows as &$row ) { $row['rank'] = ++$rank; unset( $row['__idx'] ); } unset( $row ); return $rows; } private static function table_has( $table, array $cols ) { global $wpdb; if ( (string) $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) ) !== $table ) { return false; } $have = $wpdb->get_col( "SHOW COLUMNS FROM `{$table}`" ); return ! array_diff( $cols, (array) $have ); } }