1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.6 2004-04-18 01:11:51 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 * @author: Jeff Dairiki
38 class TextSearchQuery {
42 * @param $search_query string The query. Syntax is as described above.
43 * Note that an empty $search_query will match anything.
44 * @see TextSearchQuery
46 function TextSearchQuery($search_query, $case_exact=false, $regex=false) {
47 $parser = new TextSearchQuery_Parser;
48 $this->_tree = $parser->parse($search_query);
52 function _optimize() {
53 $this->_tree = $this->_tree->optimize();
57 * Get a regexp which matches the query.
60 if (!isset($this->_regexp))
61 $this->_regexp = '/^' . $this->_tree->regexp() . '/isS';
62 return $this->_regexp;
66 * Match query against string.
68 * @param $string string The string to match.
69 * @return boolean True if the string matches the query.
71 function match($string) {
72 return preg_match($this->asRegexp(), $string);
77 * Get a regular expression suitable for highlighting matched words.
79 * This returns a PCRE regular expression which matches any non-negated
82 * @return string The PCRE regexp.
84 function getHighlightRegexp() {
85 if (!isset($this->_hilight_regexp)) {
86 $words = array_unique($this->_tree->highlight_words());
88 $this->_hilight_regexp = false;
91 foreach ($words as $key => $word)
92 $words[$key] = preg_quote($word, '/');
93 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
96 return $this->_hilight_regexp;
100 * Make an SQL clause which matches the query.
102 * @param $make_sql_clause_cb WikiCallback
103 * A callback which takes a single word as an argument and
104 * returns an SQL clause which will match exactly those records
105 * containing the word. The word passed to the callback will always
106 * be in all lower case.
108 * TODO: support db-specific extensions, like MATCH or REGEX
112 * function sql_title_match($word) {
113 * return sprintf("LOWER(title) like '%s'",
114 * addslashes($word));
119 * $query = new TextSearchQuery("wiki -page");
120 * $cb = new WikiFunctionCb('sql_title_match');
121 * $sql_clause = $query->makeSqlClause($cb);
123 * This will result in $sql_clause containing something like
124 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
126 * @return string The PCRE regexp.
128 function makeSqlClause($make_sql_clause_cb) {
129 $this->_sql_clause_cb = $make_sql_clause_cb;
130 return $this->_sql_clause($this->_tree);
133 function _sql_clause($node) {
136 return $this->_sql_clause_cb->call($node->word);
138 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
141 $subclauses = array();
142 foreach ($node->leaves as $leaf)
143 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
144 return join(" $node->op ", $subclauses);
146 assert($node->op == 'VOID');
152 * Get printable representation of the parse tree.
154 * This is for debugging only.
155 * @return string Printable parse tree.
157 function asString() {
158 return $this->_as_string($this->_tree);
161 function _as_string($node, $indent = '') {
164 return $indent . "WORD: $node->word";
166 return $indent . "VOID";
168 $lines = array($indent . $node->op . ":");
170 foreach ($node->leaves as $leaf)
171 $lines[] = $this->_as_string($leaf, $indent);
172 return join("\n", $lines);
178 * This is a TextSearchQuery which matches nothing.
180 class NullTextSearchQuery extends TextSearchQuery {
182 * Create a new query.
184 * @see TextSearchQuery
186 function NullTextSearchQuery() {}
187 function asRegexp() { return '/^(?!a)a/x'; }
188 function match($string) { return false; }
189 function getHighlightRegexp() { return ""; }
190 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
191 function asString() { return "NullTextSearchQuery"; }
195 ////////////////////////////////////////////////////////////////
197 // Remaining classes are private.
199 ////////////////////////////////////////////////////////////////
201 * Virtual base class for nodes in a TextSearchQuery parse tree.
203 * Also servers as a 'VOID' (contentless) node.
205 class TextSearchQuery_node
210 * Optimize this node.
211 * @return object Optimized node.
213 function optimize() {
218 * @return regexp matching this node.
225 * @param bool True if this node has been negated (higher in the parse tree.)
226 * @return array A list of all non-negated words contained by this node.
228 function highlight_words($negated = false) {
236 class TextSearchQuery_node_word
237 extends TextSearchQuery_node
241 function TextSearchQuery_node_word($word) {
246 return '(?=.*' . preg_quote($this->word, '/') . ')';
249 function highlight_words($negated = false) {
250 return $negated ? array() : array($this->word);
258 class TextSearchQuery_node_not
259 extends TextSearchQuery_node
263 function TextSearchQuery_node_not($leaf) {
264 $this->leaves = array($leaf);
267 function optimize() {
268 $leaf = &$this->leaves[0];
269 $leaf = $leaf->optimize();
270 if ($leaf->op == 'NOT')
271 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
276 $leaf = &$this->leaves[0];
277 return '(?!' . $leaf->regexp() . ')';
280 function highlight_words($negated = false) {
281 return $this->leaves[0]->highlight_words(!$negated);
286 * Virtual base class for 'AND' and 'OR conjoins.
288 class TextSearchQuery_node_binop
289 extends TextSearchQuery_node
291 function TextSearchQuery_node_binop($leaves) {
292 $this->leaves = $leaves;
295 function _flatten() {
296 // This flattens e.g. (AND (AND a b) (OR c d) e)
297 // to (AND a b e (OR c d))
299 foreach ($this->leaves as $leaf) {
300 $leaf = $leaf->optimize();
301 if ($this->op == $leaf->op)
302 $flat = array_merge($flat, $leaf->leaves);
306 $this->leaves = $flat;
309 function optimize() {
311 assert(!empty($this->leaves));
312 if (count($this->leaves) == 1)
313 return $this->leaves[0]; // (AND x) -> x
317 function highlight_words($negated = false) {
319 foreach ($this->leaves as $leaf)
320 array_splice($words,0,0,
321 $leaf->highlight_words($negated));
327 * A (possibly multi-argument) 'AND' conjoin.
329 class TextSearchQuery_node_and
330 extends TextSearchQuery_node_binop
334 function optimize() {
337 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
338 // Since OR's are more efficient for regexp matching:
339 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
341 // Suck out the negated leaves.
343 foreach ($this->leaves as $key => $leaf) {
344 if ($leaf->op == 'NOT') {
345 $nots[] = $leaf->leaves[0];
346 unset($this->leaves[$key]);
350 // Combine the negated leaves into a single negated or.
352 $node = ( new TextSearchQuery_node_not
353 (new TextSearchQuery_node_or($nots)) );
354 array_unshift($this->leaves, $node->optimize());
357 assert(!empty($this->leaves));
358 if (count($this->leaves) == 1)
359 return $this->leaves[0]; // (AND x) -> x
365 foreach ($this->leaves as $leaf)
366 $regexp .= $leaf->regexp();
372 * A (possibly multi-argument) 'OR' conjoin.
374 class TextSearchQuery_node_or
375 extends TextSearchQuery_node_binop
380 // We will combine any of our direct descendents which are WORDs
381 // into a single (?=.*(?:word1|word2|...)) regexp.
386 foreach ($this->leaves as $leaf) {
387 if ($leaf->op == 'WORD')
388 $words[] = preg_quote($leaf->word, '/');
390 $regexps[] = $leaf->regexp();
394 array_unshift($regexps,
395 '(?=.*' . $this->_join($words) . ')');
397 return $this->_join($regexps);
400 function _join($regexps) {
401 assert(count($regexps) > 0);
403 if (count($regexps) > 1)
404 return '(?:' . join('|', $regexps) . ')';
411 ////////////////////////////////////////////////////////////////
415 ////////////////////////////////////////////////////////////////
416 define ('TSQ_TOK_WORD', 1);
417 define ('TSQ_TOK_BINOP', 2);
418 define ('TSQ_TOK_NOT', 4);
419 define ('TSQ_TOK_LPAREN', 8);
420 define ('TSQ_TOK_RPAREN', 16);
422 class TextSearchQuery_Parser
425 * This is a simple recursive descent parser, based on the following grammar:
440 * atom : '(' list ')'
445 * The terminal tokens are:
452 * [^-()\s][^()\s]* WORD
457 function parse ($search_expr) {
458 $this->lexer = new TextSearchQuery_Lexer($search_expr);
459 $tree = $this->get_list('toplevel');
460 assert($this->lexer->eof());
465 function get_list ($is_toplevel = false) {
468 // token types we'll accept as words (and thus expr's) for the
469 // purpose of error recovery:
470 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
472 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
474 while ( ($expr = $this->get_expr())
475 || ($expr = $this->get_word($accept_as_words)) ) {
482 return new TextSearchQuery_node;
486 return new TextSearchQuery_node_and($list);
489 function get_expr () {
490 if ( !($expr = $this->get_atom()) )
493 $savedpos = $this->lexer->tell();
494 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
495 if ( ! ($right = $this->get_atom()) ) {
500 $expr = new TextSearchQuery_node_and(array($expr, $right));
503 $expr = new TextSearchQuery_node_or(array($expr, $right));
506 $savedpos = $this->lexer->tell();
508 $this->lexer->seek($savedpos);
514 function get_atom() {
515 if ($word = $this->get_word())
518 $savedpos = $this->lexer->tell();
519 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
520 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
523 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
524 if ( ($atom = $this->get_atom()) )
525 return new TextSearchQuery_node_not($atom);
527 $this->lexer->seek($savedpos);
531 function get_word($accept = TSQ_TOK_WORD) {
532 if ( ($word = $this->lexer->get($accept)) )
533 return new TextSearchQuery_node_word($word);
538 class TextSearchQuery_Lexer {
539 function TextSearchQuery_Lexer ($query_str) {
540 $this->tokens = $this->tokenize($query_str);
548 function seek($pos) {
553 return $this->pos == count($this->tokens);
556 function tokenize($string) {
558 $buf = strtolower(ltrim($string));
559 while (!empty($buf)) {
560 if (preg_match('/^(and|or)\b\s*/', $buf, $m)) {
562 $type = TSQ_TOK_BINOP;
564 elseif (preg_match('/^(-|not\b)\s*/', $buf, $m)) {
568 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
570 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
572 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
573 $val = str_replace('""', '"', $m[1]);
574 $type = TSQ_TOK_WORD;
576 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
577 $val = str_replace("''", "'", $m[1]);
578 $type = TSQ_TOK_WORD;
580 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
582 $type = TSQ_TOK_WORD;
588 $buf = substr($buf, strlen($m[0]));
589 $tokens[] = array($type, $val);
594 function get($accept) {
595 if ($this->pos >= count($this->tokens))
598 list ($type, $val) = $this->tokens[$this->pos];
599 if (($type & $accept) == 0)
611 // c-hanging-comment-ender-p: nil
612 // indent-tabs-mode: nil