Skip to content

Commit

Permalink
[FIX] Escape Special Chars In Search Query Terms
Browse files Browse the repository at this point in the history
  • Loading branch information
ThomasWeinert committed Apr 23, 2020
1 parent bf74b2d commit aa8ab53
Showing 1 changed file with 22 additions and 5 deletions.
27 changes: 22 additions & 5 deletions src/Search/Worker.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -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' ]
]
],
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -132,4 +149,4 @@ public function option($option, $default = NULL) {
}
return $this->_moduleOptions->get($option, $default);
}
}
}

0 comments on commit aa8ab53

Please sign in to comment.