1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.10 2004-11-23 15:17:16 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);
54 $this->_case_exact = $case_exact;
55 $this->_isregex = $regex;
59 function _optimize() {
60 $this->_tree = $this->_tree->optimize();
64 * Get a regexp which matches the query.
67 if (!isset($this->_regexp)) {
68 if ($this->_isregex) // already regex? glob or pcre
69 $this->_regexp = '/' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
71 $this->_regexp = '/^' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
73 return $this->_regexp;
77 * Match query against string.
79 * @param $string string The string to match.
80 * @return boolean True if the string matches the query.
82 function match($string) {
83 return preg_match($this->asRegexp(), $string);
88 * Get a regular expression suitable for highlighting matched words.
90 * This returns a PCRE regular expression which matches any non-negated
93 * @return string The PCRE regexp.
95 function getHighlightRegexp() {
96 if (!isset($this->_hilight_regexp)) {
97 $words = array_unique($this->_tree->highlight_words());
99 $this->_hilight_regexp = false;
102 foreach ($words as $key => $word)
103 $words[$key] = preg_quote($word, '/');
104 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
107 return $this->_hilight_regexp;
111 * Make an SQL clause which matches the query.
113 * @param $make_sql_clause_cb WikiCallback
114 * A callback which takes a single word as an argument and
115 * returns an SQL clause which will match exactly those records
116 * containing the word. The word passed to the callback will always
117 * be in all lower case.
119 * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
120 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
121 * How? WikiDB backend method?
122 * Case-sensitivity option.
126 * function sql_title_match($word) {
127 * return sprintf("LOWER(title) like '%s'",
128 * addslashes($word));
133 * $query = new TextSearchQuery("wiki -page");
134 * $cb = new WikiFunctionCb('sql_title_match');
135 * $sql_clause = $query->makeSqlClause($cb);
137 * This will result in $sql_clause containing something like
138 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
140 * @return string The PCRE regexp.
142 function makeSqlClause($make_sql_clause_cb) {
143 $this->_sql_clause_cb = $make_sql_clause_cb;
144 return $this->_sql_clause($this->_tree);
147 function _sql_clause($node) {
150 return $this->_sql_clause_cb->call($node->word);
152 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
155 $subclauses = array();
156 foreach ($node->leaves as $leaf)
157 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
158 return join(" $node->op ", $subclauses);
160 assert($node->op == 'VOID');
166 * Get printable representation of the parse tree.
168 * This is for debugging only.
169 * @return string Printable parse tree.
171 function asString() {
172 return $this->_as_string($this->_tree);
175 function _as_string($node, $indent = '') {
178 return $indent . "WORD: $node->word";
180 return $indent . "VOID";
182 $lines = array($indent . $node->op . ":");
184 foreach ($node->leaves as $leaf)
185 $lines[] = $this->_as_string($leaf, $indent);
186 return join("\n", $lines);
192 * This is a TextSearchQuery which matches nothing.
194 class NullTextSearchQuery extends TextSearchQuery {
196 * Create a new query.
198 * @see TextSearchQuery
200 function NullTextSearchQuery() {}
201 function asRegexp() { return '/^(?!a)a/x'; }
202 function match($string) { return false; }
203 function getHighlightRegexp() { return ""; }
204 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
205 function asString() { return "NullTextSearchQuery"; }
209 ////////////////////////////////////////////////////////////////
211 // Remaining classes are private.
213 ////////////////////////////////////////////////////////////////
215 * Virtual base class for nodes in a TextSearchQuery parse tree.
217 * Also servers as a 'VOID' (contentless) node.
219 class TextSearchQuery_node
224 * Optimize this node.
225 * @return object Optimized node.
227 function optimize() {
232 * @return regexp matching this node.
239 * @param bool True if this node has been negated (higher in the parse tree.)
240 * @return array A list of all non-negated words contained by this node.
242 function highlight_words($negated = false) {
250 class TextSearchQuery_node_word
251 extends TextSearchQuery_node
255 function TextSearchQuery_node_word($word) {
260 return '(?=.*' . preg_quote($this->word, '/') . ')';
263 function highlight_words($negated = false) {
264 return $negated ? array() : array($this->word);
272 class TextSearchQuery_node_not
273 extends TextSearchQuery_node
277 function TextSearchQuery_node_not($leaf) {
278 $this->leaves = array($leaf);
281 function optimize() {
282 $leaf = &$this->leaves[0];
283 $leaf = $leaf->optimize();
284 if ($leaf->op == 'NOT')
285 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
290 $leaf = &$this->leaves[0];
291 return '(?!' . $leaf->regexp() . ')';
294 function highlight_words($negated = false) {
295 return $this->leaves[0]->highlight_words(!$negated);
300 * Virtual base class for 'AND' and 'OR conjoins.
302 class TextSearchQuery_node_binop
303 extends TextSearchQuery_node
305 function TextSearchQuery_node_binop($leaves) {
306 $this->leaves = $leaves;
309 function _flatten() {
310 // This flattens e.g. (AND (AND a b) (OR c d) e)
311 // to (AND a b e (OR c d))
313 foreach ($this->leaves as $leaf) {
314 $leaf = $leaf->optimize();
315 if ($this->op == $leaf->op)
316 $flat = array_merge($flat, $leaf->leaves);
320 $this->leaves = $flat;
323 function optimize() {
325 assert(!empty($this->leaves));
326 if (count($this->leaves) == 1)
327 return $this->leaves[0]; // (AND x) -> x
331 function highlight_words($negated = false) {
333 foreach ($this->leaves as $leaf)
334 array_splice($words,0,0,
335 $leaf->highlight_words($negated));
341 * A (possibly multi-argument) 'AND' conjoin.
343 class TextSearchQuery_node_and
344 extends TextSearchQuery_node_binop
348 function optimize() {
351 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
352 // Since OR's are more efficient for regexp matching:
353 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
355 // Suck out the negated leaves.
357 foreach ($this->leaves as $key => $leaf) {
358 if ($leaf->op == 'NOT') {
359 $nots[] = $leaf->leaves[0];
360 unset($this->leaves[$key]);
364 // Combine the negated leaves into a single negated or.
366 $node = ( new TextSearchQuery_node_not
367 (new TextSearchQuery_node_or($nots)) );
368 array_unshift($this->leaves, $node->optimize());
371 assert(!empty($this->leaves));
372 if (count($this->leaves) == 1)
373 return $this->leaves[0]; // (AND x) -> x
379 foreach ($this->leaves as $leaf)
380 $regexp .= $leaf->regexp();
386 * A (possibly multi-argument) 'OR' conjoin.
388 class TextSearchQuery_node_or
389 extends TextSearchQuery_node_binop
394 // We will combine any of our direct descendents which are WORDs
395 // into a single (?=.*(?:word1|word2|...)) regexp.
400 foreach ($this->leaves as $leaf) {
401 if ($leaf->op == 'WORD')
402 $words[] = preg_quote($leaf->word, '/');
404 $regexps[] = $leaf->regexp();
408 array_unshift($regexps,
409 '(?=.*' . $this->_join($words) . ')');
411 return $this->_join($regexps);
414 function _join($regexps) {
415 assert(count($regexps) > 0);
417 if (count($regexps) > 1)
418 return '(?:' . join('|', $regexps) . ')';
425 ////////////////////////////////////////////////////////////////
429 ////////////////////////////////////////////////////////////////
430 define ('TSQ_TOK_WORD', 1);
431 define ('TSQ_TOK_BINOP', 2);
432 define ('TSQ_TOK_NOT', 4);
433 define ('TSQ_TOK_LPAREN', 8);
434 define ('TSQ_TOK_RPAREN', 16);
436 class TextSearchQuery_Parser
439 * This is a simple recursive descent parser, based on the following grammar:
454 * atom : '(' list ')'
459 * The terminal tokens are:
466 * [^-()\s][^()\s]* WORD
471 function parse ($search_expr, $case_exact=false) {
472 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact);
473 $tree = $this->get_list('toplevel');
474 assert($this->lexer->eof());
479 function get_list ($is_toplevel = false) {
482 // token types we'll accept as words (and thus expr's) for the
483 // purpose of error recovery:
484 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
486 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
488 while ( ($expr = $this->get_expr())
489 || ($expr = $this->get_word($accept_as_words)) ) {
496 return new TextSearchQuery_node;
500 return new TextSearchQuery_node_and($list);
503 function get_expr () {
504 if ( !($expr = $this->get_atom()) )
507 $savedpos = $this->lexer->tell();
508 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
509 if ( ! ($right = $this->get_atom()) ) {
514 $expr = new TextSearchQuery_node_and(array($expr, $right));
517 $expr = new TextSearchQuery_node_or(array($expr, $right));
520 $savedpos = $this->lexer->tell();
522 $this->lexer->seek($savedpos);
528 function get_atom() {
529 if ($word = $this->get_word())
532 $savedpos = $this->lexer->tell();
533 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
534 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
537 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
538 if ( ($atom = $this->get_atom()) )
539 return new TextSearchQuery_node_not($atom);
541 $this->lexer->seek($savedpos);
545 function get_word($accept = TSQ_TOK_WORD) {
546 if ( ($word = $this->lexer->get($accept)) )
547 return new TextSearchQuery_node_word($word);
552 class TextSearchQuery_Lexer {
553 function TextSearchQuery_Lexer ($query_str, $case_exact=false) {
554 $this->tokens = $this->tokenize($query_str, $case_exact);
562 function seek($pos) {
567 return $this->pos == count($this->tokens);
570 function tokenize($string, $case_exact=false) {
572 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
573 while (!empty($buf)) {
574 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
575 $val = strtolower($m[1]);
576 $type = TSQ_TOK_BINOP;
578 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
579 $val = strtolower($m[1]);
582 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
584 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
586 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
587 $val = str_replace('""', '"', $m[1]);
588 $type = TSQ_TOK_WORD;
590 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
591 $val = str_replace("''", "'", $m[1]);
592 $type = TSQ_TOK_WORD;
594 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
596 $type = TSQ_TOK_WORD;
602 $buf = substr($buf, strlen($m[0]));
603 $tokens[] = array($type, $val);
608 function get($accept) {
609 if ($this->pos >= count($this->tokens))
612 list ($type, $val) = $this->tokens[$this->pos];
613 if (($type & $accept) == 0)
625 // c-hanging-comment-ender-p: nil
626 // indent-tabs-mode: nil