1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.9 2004-11-23 13:35:31 rurban Exp $');
5 * This represents "Google-like" text search queries like:
8 * <dd> Match strings containing the substring 'wiki', and not containing the
10 * <dt> wiki word or page
11 * <dd> Match strings containing the substring 'wiki' and either the substring
12 * 'word' or the substring 'page'.
15 * The full query syntax, in order of precedence, is roughly:
17 * The unary 'NOT' or '-' operator (they are equivalent) negates the
18 * following search clause.
20 * Search clauses may be joined with the (left-associative) binary operators
23 * Two adjoining search clauses are joined with an implicit 'AND'. This has
24 * lower precedence than either an explicit 'AND' or 'OR', so "a b OR c"
25 * parses as "a AND ( b OR c )", while "a AND b OR c" parses as
26 * "( a AND b ) OR c" (due to the left-associativity of 'AND' and 'OR'.)
28 * Search clauses can be grouped with parentheses.
30 * Phrases (or other things which don't look like words) can be forced to
31 * be interpreted as words by quoting them, either with single (') or double (")
32 * quotes. If you wan't to include the quote character within a quoted string,
33 * double-up on the quote character: 'I''m hungry' is equivalent to
36 * FIXME: Clarify wildcards usage. none, glob-style, SQL-style, pcre-style, regex-style
37 * This only converts to PCRE, not to ANSI-SQL or other SQL functions.
38 * But see makeSqlClause().
40 * @author: Jeff Dairiki
42 class TextSearchQuery {
46 * @param $search_query string The query. Syntax is as described above.
47 * Note that an empty $search_query will match anything.
48 * @see TextSearchQuery
49 * TODO: support $regex arg
51 function TextSearchQuery($search_query, $case_exact=false, $regex=false) {
52 $parser = new TextSearchQuery_Parser;
53 $this->_tree = $parser->parse($search_query, $case_exact);
57 function _optimize() {
58 $this->_tree = $this->_tree->optimize();
62 * Get a regexp which matches the query.
65 if (!isset($this->_regexp))
66 $this->_regexp = '/^' . $this->_tree->regexp() . '/isS';
67 return $this->_regexp;
71 * Match query against string.
73 * @param $string string The string to match.
74 * @return boolean True if the string matches the query.
76 function match($string) {
77 return preg_match($this->asRegexp(), $string);
82 * Get a regular expression suitable for highlighting matched words.
84 * This returns a PCRE regular expression which matches any non-negated
87 * @return string The PCRE regexp.
89 function getHighlightRegexp() {
90 if (!isset($this->_hilight_regexp)) {
91 $words = array_unique($this->_tree->highlight_words());
93 $this->_hilight_regexp = false;
96 foreach ($words as $key => $word)
97 $words[$key] = preg_quote($word, '/');
98 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
101 return $this->_hilight_regexp;
105 * Make an SQL clause which matches the query.
107 * @param $make_sql_clause_cb WikiCallback
108 * A callback which takes a single word as an argument and
109 * returns an SQL clause which will match exactly those records
110 * containing the word. The word passed to the callback will always
111 * be in all lower case.
113 * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
114 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
115 * How? WikiDB backend method?
116 * Case-sensitivity option.
120 * function sql_title_match($word) {
121 * return sprintf("LOWER(title) like '%s'",
122 * addslashes($word));
127 * $query = new TextSearchQuery("wiki -page");
128 * $cb = new WikiFunctionCb('sql_title_match');
129 * $sql_clause = $query->makeSqlClause($cb);
131 * This will result in $sql_clause containing something like
132 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
134 * @return string The PCRE regexp.
136 function makeSqlClause($make_sql_clause_cb) {
137 $this->_sql_clause_cb = $make_sql_clause_cb;
138 return $this->_sql_clause($this->_tree);
141 function _sql_clause($node) {
144 return $this->_sql_clause_cb->call($node->word);
146 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
149 $subclauses = array();
150 foreach ($node->leaves as $leaf)
151 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
152 return join(" $node->op ", $subclauses);
154 assert($node->op == 'VOID');
160 * Get printable representation of the parse tree.
162 * This is for debugging only.
163 * @return string Printable parse tree.
165 function asString() {
166 return $this->_as_string($this->_tree);
169 function _as_string($node, $indent = '') {
172 return $indent . "WORD: $node->word";
174 return $indent . "VOID";
176 $lines = array($indent . $node->op . ":");
178 foreach ($node->leaves as $leaf)
179 $lines[] = $this->_as_string($leaf, $indent);
180 return join("\n", $lines);
186 * This is a TextSearchQuery which matches nothing.
188 class NullTextSearchQuery extends TextSearchQuery {
190 * Create a new query.
192 * @see TextSearchQuery
194 function NullTextSearchQuery() {}
195 function asRegexp() { return '/^(?!a)a/x'; }
196 function match($string) { return false; }
197 function getHighlightRegexp() { return ""; }
198 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
199 function asString() { return "NullTextSearchQuery"; }
203 ////////////////////////////////////////////////////////////////
205 // Remaining classes are private.
207 ////////////////////////////////////////////////////////////////
209 * Virtual base class for nodes in a TextSearchQuery parse tree.
211 * Also servers as a 'VOID' (contentless) node.
213 class TextSearchQuery_node
218 * Optimize this node.
219 * @return object Optimized node.
221 function optimize() {
226 * @return regexp matching this node.
233 * @param bool True if this node has been negated (higher in the parse tree.)
234 * @return array A list of all non-negated words contained by this node.
236 function highlight_words($negated = false) {
244 class TextSearchQuery_node_word
245 extends TextSearchQuery_node
249 function TextSearchQuery_node_word($word) {
254 return '(?=.*' . preg_quote($this->word, '/') . ')';
257 function highlight_words($negated = false) {
258 return $negated ? array() : array($this->word);
266 class TextSearchQuery_node_not
267 extends TextSearchQuery_node
271 function TextSearchQuery_node_not($leaf) {
272 $this->leaves = array($leaf);
275 function optimize() {
276 $leaf = &$this->leaves[0];
277 $leaf = $leaf->optimize();
278 if ($leaf->op == 'NOT')
279 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
284 $leaf = &$this->leaves[0];
285 return '(?!' . $leaf->regexp() . ')';
288 function highlight_words($negated = false) {
289 return $this->leaves[0]->highlight_words(!$negated);
294 * Virtual base class for 'AND' and 'OR conjoins.
296 class TextSearchQuery_node_binop
297 extends TextSearchQuery_node
299 function TextSearchQuery_node_binop($leaves) {
300 $this->leaves = $leaves;
303 function _flatten() {
304 // This flattens e.g. (AND (AND a b) (OR c d) e)
305 // to (AND a b e (OR c d))
307 foreach ($this->leaves as $leaf) {
308 $leaf = $leaf->optimize();
309 if ($this->op == $leaf->op)
310 $flat = array_merge($flat, $leaf->leaves);
314 $this->leaves = $flat;
317 function optimize() {
319 assert(!empty($this->leaves));
320 if (count($this->leaves) == 1)
321 return $this->leaves[0]; // (AND x) -> x
325 function highlight_words($negated = false) {
327 foreach ($this->leaves as $leaf)
328 array_splice($words,0,0,
329 $leaf->highlight_words($negated));
335 * A (possibly multi-argument) 'AND' conjoin.
337 class TextSearchQuery_node_and
338 extends TextSearchQuery_node_binop
342 function optimize() {
345 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
346 // Since OR's are more efficient for regexp matching:
347 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
349 // Suck out the negated leaves.
351 foreach ($this->leaves as $key => $leaf) {
352 if ($leaf->op == 'NOT') {
353 $nots[] = $leaf->leaves[0];
354 unset($this->leaves[$key]);
358 // Combine the negated leaves into a single negated or.
360 $node = ( new TextSearchQuery_node_not
361 (new TextSearchQuery_node_or($nots)) );
362 array_unshift($this->leaves, $node->optimize());
365 assert(!empty($this->leaves));
366 if (count($this->leaves) == 1)
367 return $this->leaves[0]; // (AND x) -> x
373 foreach ($this->leaves as $leaf)
374 $regexp .= $leaf->regexp();
380 * A (possibly multi-argument) 'OR' conjoin.
382 class TextSearchQuery_node_or
383 extends TextSearchQuery_node_binop
388 // We will combine any of our direct descendents which are WORDs
389 // into a single (?=.*(?:word1|word2|...)) regexp.
394 foreach ($this->leaves as $leaf) {
395 if ($leaf->op == 'WORD')
396 $words[] = preg_quote($leaf->word, '/');
398 $regexps[] = $leaf->regexp();
402 array_unshift($regexps,
403 '(?=.*' . $this->_join($words) . ')');
405 return $this->_join($regexps);
408 function _join($regexps) {
409 assert(count($regexps) > 0);
411 if (count($regexps) > 1)
412 return '(?:' . join('|', $regexps) . ')';
419 ////////////////////////////////////////////////////////////////
423 ////////////////////////////////////////////////////////////////
424 define ('TSQ_TOK_WORD', 1);
425 define ('TSQ_TOK_BINOP', 2);
426 define ('TSQ_TOK_NOT', 4);
427 define ('TSQ_TOK_LPAREN', 8);
428 define ('TSQ_TOK_RPAREN', 16);
430 class TextSearchQuery_Parser
433 * This is a simple recursive descent parser, based on the following grammar:
448 * atom : '(' list ')'
453 * The terminal tokens are:
460 * [^-()\s][^()\s]* WORD
465 function parse ($search_expr, $case_exact=false) {
466 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact);
467 $tree = $this->get_list('toplevel');
468 assert($this->lexer->eof());
473 function get_list ($is_toplevel = false) {
476 // token types we'll accept as words (and thus expr's) for the
477 // purpose of error recovery:
478 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
480 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
482 while ( ($expr = $this->get_expr())
483 || ($expr = $this->get_word($accept_as_words)) ) {
490 return new TextSearchQuery_node;
494 return new TextSearchQuery_node_and($list);
497 function get_expr () {
498 if ( !($expr = $this->get_atom()) )
501 $savedpos = $this->lexer->tell();
502 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
503 if ( ! ($right = $this->get_atom()) ) {
508 $expr = new TextSearchQuery_node_and(array($expr, $right));
511 $expr = new TextSearchQuery_node_or(array($expr, $right));
514 $savedpos = $this->lexer->tell();
516 $this->lexer->seek($savedpos);
522 function get_atom() {
523 if ($word = $this->get_word())
526 $savedpos = $this->lexer->tell();
527 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
528 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
531 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
532 if ( ($atom = $this->get_atom()) )
533 return new TextSearchQuery_node_not($atom);
535 $this->lexer->seek($savedpos);
539 function get_word($accept = TSQ_TOK_WORD) {
540 if ( ($word = $this->lexer->get($accept)) )
541 return new TextSearchQuery_node_word($word);
546 class TextSearchQuery_Lexer {
547 function TextSearchQuery_Lexer ($query_str, $case_exact=false) {
548 $this->tokens = $this->tokenize($query_str, $case_exact);
556 function seek($pos) {
561 return $this->pos == count($this->tokens);
564 function tokenize($string, $case_exact=false) {
566 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
567 while (!empty($buf)) {
568 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
569 $val = strtolower($m[1]);
570 $type = TSQ_TOK_BINOP;
572 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
573 $val = strtolower($m[1]);
576 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
578 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
580 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
581 $val = str_replace('""', '"', $m[1]);
582 $type = TSQ_TOK_WORD;
584 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
585 $val = str_replace("''", "'", $m[1]);
586 $type = TSQ_TOK_WORD;
588 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
590 $type = TSQ_TOK_WORD;
596 $buf = substr($buf, strlen($m[0]));
597 $tokens[] = array($type, $val);
602 function get($accept) {
603 if ($this->pos >= count($this->tokens))
606 list ($type, $val) = $this->tokens[$this->pos];
607 if (($type & $accept) == 0)
619 // c-hanging-comment-ender-p: nil
620 // indent-tabs-mode: nil