From bbaa6b6f715abb5545d6bbbdb2159c629334ff1d Mon Sep 17 00:00:00 2001 From: Dion Hulse Date: Wed, 20 Jan 2016 04:37:13 +0000 Subject: [PATCH] Query: Avoid invalid SQL when building ORDER BY clause using long search strings. The introduction of negative search terms in 4.4 [34934] introduced the possibility that the ORDER BY clause of a search query could be assembled in such a way as to create invalid syntax. The current changeset fixes this by ensuring that the ORDER BY clause corresponding to the search terms is excluded when it would otherwise be empty. Merges [36251] to the 4.4 branch. Props salvoaranzulla, boonebgorges. Fixes #35361. git-svn-id: https://develop.svn.wordpress.org/branches/4.4@36354 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/query.php | 7 +++++-- tests/phpunit/tests/query/search.php | 12 ++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/query.php b/src/wp-includes/query.php index 733eea7dc7..b4aae270b2 100644 --- a/src/wp-includes/query.php +++ b/src/wp-includes/query.php @@ -2300,7 +2300,7 @@ class WP_Query { $like = '%' . $wpdb->esc_like( $q['s'] ) . '%'; } - $search_orderby = '(CASE '; + $search_orderby = ''; // sentence match in 'post_title' if ( $like ) { @@ -2321,7 +2321,10 @@ class WP_Query { if ( $like ) { $search_orderby .= $wpdb->prepare( "WHEN $wpdb->posts.post_content LIKE %s THEN 4 ", $like ); } - $search_orderby .= 'ELSE 5 END)'; + + if ( $search_orderby ) { + $search_orderby = '(CASE ' . $search_orderby . 'ELSE 5 END)'; + } } else { // single word or sentence search $search_orderby = reset( $q['search_orderby_title'] ) . ' DESC'; diff --git a/tests/phpunit/tests/query/search.php b/tests/phpunit/tests/query/search.php index caf862c0d6..5fe6d5e62a 100644 --- a/tests/phpunit/tests/query/search.php +++ b/tests/phpunit/tests/query/search.php @@ -125,4 +125,16 @@ class Tests_Query_Search extends WP_UnitTestCase { $this->assertEqualSets( array( $p3 ), $q->posts ); } + + /** + * @ticket 35361 + */ + public function test_search_orderby_should_be_empty_when_search_string_is_longer_than_6_words_and_exclusion_operator_is_used() { + $q = new WP_Query( array( + 's' => 'foo1 foo2 foo3 foo4 foo5 foo6 foo7 -bar', + 'fields' => 'ids', + ) ); + + $this->assertNotRegExp( '|ORDER BY \(CASE[^\)]+\)|', $q->request ); + } }