Comments: Avoid DB error in comment meta queries.

In `WP_Comment_Query` always include the table name when referencing `wp_comments.comment_ID`. This avoids ambiguity in when making meta queries as `wp_commentmeta` includes a column of the same name.

Follow up to [47887].

Props genosseeinhorn, azouamauriac, audrasjb, peterwilsoncc.
Fixes #55218.


git-svn-id: https://develop.svn.wordpress.org/trunk@53291 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Peter Wilson
2022-04-27 04:08:16 +00:00
parent 4bc07ccb43
commit 2b16e7fc01
2 changed files with 52 additions and 1 deletions

View File

@@ -595,7 +595,7 @@ class WP_Comment_Query {
// Otherwise we match against email addresses.
if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
// Only include requested comment.
$approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' AND comment_ID = %d )", $unapproved_identifier, (int) $_GET['unapproved'] );
$approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' AND {$wpdb->comments}.comment_ID = %d )", $unapproved_identifier, (int) $_GET['unapproved'] );
} else {
// Include all of the author's unapproved comments.
$approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );

View File

@@ -4968,4 +4968,55 @@ class Tests_Comment_Query extends WP_UnitTestCase {
$this->assertSame( $num_queries_all_args, get_num_queries() );
}
/**
* @ticket 55218
*/
public function test_unapproved_comment_with_meta_query_does_not_trigger_ambiguous_identifier_error() {
$p = self::$post_id;
$c = self::factory()->comment->create(
array(
'comment_post_ID' => $p,
'comment_content' => '1',
'comment_approved' => '0',
'comment_date_gmt' => gmdate( 'Y-m-d H:i:s', time() ),
'comment_author_email' => 'foo@bar.mail',
'comment_meta' => array( 'foo' => 'bar' ),
)
);
$comment = get_comment( $c );
/*
* This is used to get a bunch of globals set up prior to making the
* database query. This helps with prepping for the moderation hash.
*/
$this->go_to(
add_query_arg(
array(
'unapproved' => $comment->comment_ID,
'moderation-hash' => wp_hash( $comment->comment_date_gmt ),
),
get_comment_link( $comment )
)
);
/*
* The result of the query is not needed so it's not assigned to variable.
*
* Returning the ID only limits the database query to only the one that was
* causing the error reported in ticket 55218.
*/
new WP_Comment_Query(
array(
'include_unapproved' => array( 'foo@bar.mail' ),
'meta_query' => array( array( 'key' => 'foo' ) ),
'post_id' => $p,
'fields' => 'ids',
)
);
global $wpdb;
$this->assertNotSame( "Column 'comment_ID' in where clause is ambiguous", $wpdb->last_error );
$this->assertStringNotContainsString( ' comment_ID ', $wpdb->last_query );
}
}