Skip to content

Commit

Permalink
add prepare missing wpdb / improve sql security
Browse files Browse the repository at this point in the history
  • Loading branch information
herewithme committed Jul 30, 2024
1 parent a48058e commit 36a3129
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 13 deletions.
24 changes: 12 additions & 12 deletions classes/cli/migration.php
Original file line number Diff line number Diff line change
Expand Up @@ -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" );
}

/**
Expand Down
9 changes: 8 additions & 1 deletion classes/query.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down

0 comments on commit 36a3129

Please sign in to comment.