1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.7 2004-09-06 10:22:15 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 AGAINST or REGEX
109 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
110 * How? WikiDB backend method?
114 * function sql_title_match($word) {
115 * return sprintf("LOWER(title) like '%s'",
116 * addslashes($word));
121 * $query = new TextSearchQuery("wiki -page");
122 * $cb = new WikiFunctionCb('sql_title_match');
123 * $sql_clause = $query->makeSqlClause($cb);
125 * This will result in $sql_clause containing something like
126 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
128 * @return string The PCRE regexp.
130 function makeSqlClause($make_sql_clause_cb) {
131 $this->_sql_clause_cb = $make_sql_clause_cb;
132 return $this->_sql_clause($this->_tree);
135 function _sql_clause($node) {
138 return $this->_sql_clause_cb->call($node->word);
140 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
143 $subclauses = array();
144 foreach ($node->leaves as $leaf)
145 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
146 return join(" $node->op ", $subclauses);
148 assert($node->op == 'VOID');
154 * Get printable representation of the parse tree.
156 * This is for debugging only.
157 * @return string Printable parse tree.
159 function asString() {
160 return $this->_as_string($this->_tree);
163 function _as_string($node, $indent = '') {
166 return $indent . "WORD: $node->word";
168 return $indent . "VOID";
170 $lines = array($indent . $node->op . ":");
172 foreach ($node->leaves as $leaf)
173 $lines[] = $this->_as_string($leaf, $indent);
174 return join("\n", $lines);
180 * This is a TextSearchQuery which matches nothing.
182 class NullTextSearchQuery extends TextSearchQuery {
184 * Create a new query.
186 * @see TextSearchQuery
188 function NullTextSearchQuery() {}
189 function asRegexp() { return '/^(?!a)a/x'; }
190 function match($string) { return false; }
191 function getHighlightRegexp() { return ""; }
192 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
193 function asString() { return "NullTextSearchQuery"; }
197 ////////////////////////////////////////////////////////////////
199 // Remaining classes are private.
201 ////////////////////////////////////////////////////////////////
203 * Virtual base class for nodes in a TextSearchQuery parse tree.
205 * Also servers as a 'VOID' (contentless) node.
207 class TextSearchQuery_node
212 * Optimize this node.
213 * @return object Optimized node.
215 function optimize() {
220 * @return regexp matching this node.
227 * @param bool True if this node has been negated (higher in the parse tree.)
228 * @return array A list of all non-negated words contained by this node.
230 function highlight_words($negated = false) {
238 class TextSearchQuery_node_word
239 extends TextSearchQuery_node
243 function TextSearchQuery_node_word($word) {
248 return '(?=.*' . preg_quote($this->word, '/') . ')';
251 function highlight_words($negated = false) {
252 return $negated ? array() : array($this->word);
260 class TextSearchQuery_node_not
261 extends TextSearchQuery_node
265 function TextSearchQuery_node_not($leaf) {
266 $this->leaves = array($leaf);
269 function optimize() {
270 $leaf = &$this->leaves[0];
271 $leaf = $leaf->optimize();
272 if ($leaf->op == 'NOT')
273 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
278 $leaf = &$this->leaves[0];
279 return '(?!' . $leaf->regexp() . ')';
282 function highlight_words($negated = false) {
283 return $this->leaves[0]->highlight_words(!$negated);
288 * Virtual base class for 'AND' and 'OR conjoins.
290 class TextSearchQuery_node_binop
291 extends TextSearchQuery_node
293 function TextSearchQuery_node_binop($leaves) {
294 $this->leaves = $leaves;
297 function _flatten() {
298 // This flattens e.g. (AND (AND a b) (OR c d) e)
299 // to (AND a b e (OR c d))
301 foreach ($this->leaves as $leaf) {
302 $leaf = $leaf->optimize();
303 if ($this->op == $leaf->op)
304 $flat = array_merge($flat, $leaf->leaves);
308 $this->leaves = $flat;
311 function optimize() {
313 assert(!empty($this->leaves));
314 if (count($this->leaves) == 1)
315 return $this->leaves[0]; // (AND x) -> x
319 function highlight_words($negated = false) {
321 foreach ($this->leaves as $leaf)
322 array_splice($words,0,0,
323 $leaf->highlight_words($negated));
329 * A (possibly multi-argument) 'AND' conjoin.
331 class TextSearchQuery_node_and
332 extends TextSearchQuery_node_binop
336 function optimize() {
339 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
340 // Since OR's are more efficient for regexp matching:
341 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
343 // Suck out the negated leaves.
345 foreach ($this->leaves as $key => $leaf) {
346 if ($leaf->op == 'NOT') {
347 $nots[] = $leaf->leaves[0];
348 unset($this->leaves[$key]);
352 // Combine the negated leaves into a single negated or.
354 $node = ( new TextSearchQuery_node_not
355 (new TextSearchQuery_node_or($nots)) );
356 array_unshift($this->leaves, $node->optimize());
359 assert(!empty($this->leaves));
360 if (count($this->leaves) == 1)
361 return $this->leaves[0]; // (AND x) -> x
367 foreach ($this->leaves as $leaf)
368 $regexp .= $leaf->regexp();
374 * A (possibly multi-argument) 'OR' conjoin.
376 class TextSearchQuery_node_or
377 extends TextSearchQuery_node_binop
382 // We will combine any of our direct descendents which are WORDs
383 // into a single (?=.*(?:word1|word2|...)) regexp.
388 foreach ($this->leaves as $leaf) {
389 if ($leaf->op == 'WORD')
390 $words[] = preg_quote($leaf->word, '/');
392 $regexps[] = $leaf->regexp();
396 array_unshift($regexps,
397 '(?=.*' . $this->_join($words) . ')');
399 return $this->_join($regexps);
402 function _join($regexps) {
403 assert(count($regexps) > 0);
405 if (count($regexps) > 1)
406 return '(?:' . join('|', $regexps) . ')';
413 ////////////////////////////////////////////////////////////////
417 ////////////////////////////////////////////////////////////////
418 define ('TSQ_TOK_WORD', 1);
419 define ('TSQ_TOK_BINOP', 2);
420 define ('TSQ_TOK_NOT', 4);
421 define ('TSQ_TOK_LPAREN', 8);
422 define ('TSQ_TOK_RPAREN', 16);
424 class TextSearchQuery_Parser
427 * This is a simple recursive descent parser, based on the following grammar:
442 * atom : '(' list ')'
447 * The terminal tokens are:
454 * [^-()\s][^()\s]* WORD
459 function parse ($search_expr) {
460 $this->lexer = new TextSearchQuery_Lexer($search_expr);
461 $tree = $this->get_list('toplevel');
462 assert($this->lexer->eof());
467 function get_list ($is_toplevel = false) {
470 // token types we'll accept as words (and thus expr's) for the
471 // purpose of error recovery:
472 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
474 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
476 while ( ($expr = $this->get_expr())
477 || ($expr = $this->get_word($accept_as_words)) ) {
484 return new TextSearchQuery_node;
488 return new TextSearchQuery_node_and($list);
491 function get_expr () {
492 if ( !($expr = $this->get_atom()) )
495 $savedpos = $this->lexer->tell();
496 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
497 if ( ! ($right = $this->get_atom()) ) {
502 $expr = new TextSearchQuery_node_and(array($expr, $right));
505 $expr = new TextSearchQuery_node_or(array($expr, $right));
508 $savedpos = $this->lexer->tell();
510 $this->lexer->seek($savedpos);
516 function get_atom() {
517 if ($word = $this->get_word())
520 $savedpos = $this->lexer->tell();
521 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
522 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
525 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
526 if ( ($atom = $this->get_atom()) )
527 return new TextSearchQuery_node_not($atom);
529 $this->lexer->seek($savedpos);
533 function get_word($accept = TSQ_TOK_WORD) {
534 if ( ($word = $this->lexer->get($accept)) )
535 return new TextSearchQuery_node_word($word);
540 class TextSearchQuery_Lexer {
541 function TextSearchQuery_Lexer ($query_str) {
542 $this->tokens = $this->tokenize($query_str);
550 function seek($pos) {
555 return $this->pos == count($this->tokens);
558 function tokenize($string) {
560 $buf = strtolower(ltrim($string));
561 while (!empty($buf)) {
562 if (preg_match('/^(and|or)\b\s*/', $buf, $m)) {
564 $type = TSQ_TOK_BINOP;
566 elseif (preg_match('/^(-|not\b)\s*/', $buf, $m)) {
570 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
572 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
574 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
575 $val = str_replace('""', '"', $m[1]);
576 $type = TSQ_TOK_WORD;
578 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
579 $val = str_replace("''", "'", $m[1]);
580 $type = TSQ_TOK_WORD;
582 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
584 $type = TSQ_TOK_WORD;
590 $buf = substr($buf, strlen($m[0]));
591 $tokens[] = array($type, $val);
596 function get($accept) {
597 if ($this->pos >= count($this->tokens))
600 list ($type, $val) = $this->tokens[$this->pos];
601 if (($type & $accept) == 0)
613 // c-hanging-comment-ender-p: nil
614 // indent-tabs-mode: nil