prefix . 'adpresso_stats'; $clicks_log_table = $wpdb->prefix . 'adpresso_clicks_log'; // Group the events, to minimize the number of DB queries $grouped_stats = []; foreach ( $events as $event ) { // Validate the basic data for each event $placement_id = absint( $event['placementId'] ?? 0 ); $group_id = absint( $event['groupId'] ?? 0 ); $ad_id = absint( $event['adId'] ?? 0 ); $event_type = sanitize_key( $event['type'] ?? '' ); if ( ! $ad_id ) { continue; } $key = "{$placement_id}-{$group_id}-{$ad_id}"; if ( ! isset( $grouped_stats[ $key ] ) ) { $grouped_stats[ $key ] = [ 'placement_id' => $placement_id, 'group_id' => $group_id, 'ad_id' => $ad_id, 'impressions' => 0, 'impressions_av' => 0, 'clicks' => 0, ]; } // Increment the counter. switch ( $event_type ) { case 'impression': $grouped_stats[ $key ]['impressions']++; break; case 'impression_av': $grouped_stats[ $key ]['impressions_av']++; break; case 'click': $grouped_stats[ $key ]['clicks']++; if ( adpresso_fs()->is_premium() ) { // Write a detailed click log entry $this->log_click_details( $event, $clicks_log_table ); } break; } } if ( empty( $grouped_stats ) ) { return true; } $date_utc = current_time( 'mysql', true ); $date_only = substr( $date_utc, 0, 10 ); $values = []; foreach ( $grouped_stats as $stat ) { $values[] = $wpdb->prepare( '(%s, %d, %d, %d, %d, %d, %d)', $date_only, $stat['placement_id'], $stat['group_id'], $stat['ad_id'], $stat['impressions'], $stat['clicks'], $stat['impressions_av'] ); } $query = "INSERT INTO {$stats_table} (stat_date, placement_id, group_id, ad_id, impressions, clicks, impressions_av) VALUES " . implode( ',', $values ) . " ON DUPLICATE KEY UPDATE impressions = impressions + VALUES(impressions), clicks = clicks + VALUES(clicks), impressions_av = impressions_av + VALUES(impressions_av)"; // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Bulk insert values are individually prepared above. $wpdb->query( $query ); return true; } /** * Saves detailed click log entry * * @param array $event The clicke vent. * @param string $table_name Name of the log table. */ private function log_click_details( array $event, string $table_name ): void { global $wpdb; // Anonymize the IP address before hashing (GDPR-friendly) $ip = wp_privacy_anonymize_ip( $_SERVER['REMOTE_ADDR'] ?? '' ); $wpdb->insert( $table_name, [ 'timestamp_utc' => current_time( 'mysql', true ), 'placement_id' => absint( $event['placementId'] ?? 0 ), 'group_id' => absint( $event['groupId'] ?? 0 ), 'ad_id' => absint( $event['adId'] ?? 0 ), 'ip_hash' => hash( 'sha256', $ip . wp_salt() ), 'user_agent' => sanitize_text_field( $_SERVER['HTTP_USER_AGENT'] ?? '' ), 'target_url' => esc_url_raw( $event['targetUrl'] ?? '' ), 'referrer_url' => esc_url_raw( $_SERVER['HTTP_REFERER'] ?? '' ), ] ); } }