From 36a3129f7e5dc536d4d86d5269158b9fff39f608 Mon Sep 17 00:00:00 2001 From: Amaury Balmer Date: Tue, 30 Jul 2024 15:25:06 +0200 Subject: [PATCH] add prepare missing wpdb / improve sql security --- classes/cli/migration.php | 24 ++++++++++++------------ classes/query.php | 9 ++++++++- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/classes/cli/migration.php b/classes/cli/migration.php index 340cca9..e3e12de 100644 --- a/classes/cli/migration.php +++ b/classes/cli/migration.php @@ -27,27 +27,27 @@ private function get_blog_ids_with_meta_key() { switch_to_blog( $blog->blog_id ); // Table exists ? - if ( $wpdb->get_var( "SHOW TABLES LIKE '$wpdb->postmeta'" ) != $wpdb->postmeta ) { + if ( $wpdb->get_var( $wpdb->prepare( "SHOW TABLES LIKE %s", $wpdb->postmeta ) ) === $wpdb->postmeta ) { restore_current_blog(); continue; } - $selects[] = "( - SELECT pm.post_id AS post_id, pm.meta_value AS meta_value, {$blog->blog_id} AS blog_id - FROM {$wpdb->postmeta} AS pm - WHERE 1 = 1 - AND pm.meta_key = '_origin_key' - )"; + $blog_id = (int) $blog->blog_id; // Ensure the blog_id is an integer + $meta_key = '_origin_key'; // Define the meta_key explicitly + + // Use prepare to ensure safe query construction + $selects[] = $wpdb->prepare( "( + SELECT pm.post_id AS post_id, pm.meta_value AS meta_value, %d AS blog_id + FROM {$wpdb->postmeta} AS pm + WHERE pm.meta_key = %s + )", $blog_id, $meta_key ); restore_current_blog(); } - // Make an union, group doublons with concat - $query = ' SELECT post_id, meta_value, blog_id FROM ( '; - $query .= implode( ' UNION ALL ', $selects ); - $query .= ' ) AS wp '; + $union_all_query = implode( ' UNION ALL ', $selects ); - return $wpdb->get_results( $query ); + return $wpdb->get_results( "SELECT post_id, meta_value, blog_id FROM ( $union_all_query ) AS wp" ); } /** diff --git a/classes/query.php b/classes/query.php index 348014c..598add1 100644 --- a/classes/query.php +++ b/classes/query.php @@ -44,7 +44,14 @@ public static function posts_join( $join, WP_Query $query ) { $join_type = $query->get( 'bea_csf_filter' ) === 'local-only' ? 'LEFT' : 'INNER'; - $join .= " $join_type JOIN $wpdb->bea_csf_relations AS bcr ON ( $wpdb->posts.ID = bcr.receiver_id AND bcr.receiver_blog_id = " . get_current_blog_id() . ' ) '; + // Get current blog ID safely + $current_blog_id = (int) get_current_blog_id(); + + // Prepare the join SQL + $join .= $wpdb->prepare( + " $join_type JOIN {$wpdb->bea_csf_relations} AS bcr ON ({$wpdb->posts}.ID = bcr.receiver_id AND bcr.receiver_blog_id = %d) ", + $current_blog_id + ); return $join; }