diff --git a/src/Search/Worker.php b/src/Search/Worker.php index 61a4375..6a52619 100644 --- a/src/Search/Worker.php +++ b/src/Search/Worker.php @@ -24,12 +24,15 @@ public function search($term = '', $language, $limit = 10, $offset = 0) { $url = sprintf("http://%s:%d/%s/%s/_search", $host, $port, $index, $language); if (!empty($term)) { - $term = preg_replace('(^\W+)u', '', $term); - $term = preg_replace('(\W+$)u', '', $term); + $term = preg_replace('(^\s+)u', '', $term); + $term = preg_replace('(\s+$)u', '', $term); $activeTerm = strtolower($term); $exactlyTerm = $activeTerm; - if (!preg_match('(\s)', $activeTerm)) { + if (!preg_match('(\s|\\*)', $activeTerm)) { + $queryString = sprintf('(*%s*) OR (%s)', $this->escapeTerm($activeTerm), $this->escapeTerm($exactlyTerm)); $activeTerm = sprintf('*%s*', $activeTerm); + } else { + $queryString = $this->escapeTerm($activeTerm); } $rawQuery = [ @@ -45,7 +48,7 @@ public function search($term = '', $language, $limit = 10, $offset = 0) { 'size' => $limit, 'query' => [ 'query_string' => [ - 'query' => $activeTerm.' OR '.$exactlyTerm, + 'query' => $queryString, 'fields' => [ 'title^2', 'content' ] ] ], @@ -92,6 +95,20 @@ public function search($term = '', $language, $limit = 10, $offset = 0) { return $return; } + public function escapeTerm($term) { + // remove < and > + $result = str_replace(['<', '>'], '', $term); + // prefix special characters with backslash + $result = preg_replace_callback( + '([-+=!(){}[\\]^"~*?:\\\\/]|&&|\\|\\|)', + static function($match) { + return '\\'.$match[0]; + }, + $result + ); + return $result; + } + /** * @param PapayaModuleElasticsearchConnection $connection * @return PapayaModuleElasticsearchConnection @@ -132,4 +149,4 @@ public function option($option, $default = NULL) { } return $this->_moduleOptions->get($option, $default); } -} \ No newline at end of file +}