1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.20 2005-09-11 14:55:05 rurban Exp $');
3 * A text search query, converting queries to PCRE and SQL matchers.
5 * This represents an enhanced "Google-like" text search query:
7 * <dt> default: case-insensitive glob-style search with special operators OR AND NOT -
9 * <dd> Match strings containing the substring 'wiki', and NOT containing the
11 * <dt> wiki word or page
12 * <dd> Match strings containing the substring 'wiki' AND either the substring
13 * 'word' OR the substring 'page'.
14 * <dt> auto-detect regex hints, glob-style or regex-style, and converts them
15 * to PCRE and SQL matchers:
16 * <dd> "^word$" => EXACT(word)
17 * <dd> "^word" => STARTS_WITH(word)
18 * <dd> "word*" => STARTS_WITH(word)
19 * <dd> "*word" => ENDS_WITH(word)
20 * <dd> "/^word.* /" => REGEX(^word.*)
21 * <dd> "word*word" => REGEX(word.*word)
24 * The full query syntax, in order of precedence, is roughly:
26 * The unary 'NOT' or '-' operator (they are equivalent) negates the
27 * following search clause.
29 * Search clauses may be joined with the (left-associative) binary operators
30 * 'AND' and 'OR'. (case-insensitive)
32 * Two adjoining search clauses are joined with an implicit 'AND'. This has
33 * lower precedence than either an explicit 'AND' or 'OR', so "a b OR c"
34 * parses as "a AND ( b OR c )", while "a AND b OR c" parses as
35 * "( a AND b ) OR c" (due to the left-associativity of 'AND' and 'OR'.)
37 * Search clauses can be grouped with parentheses.
39 * Phrases (or other things which don't look like words) can be forced to
40 * be interpreted as words by quoting them, either with single (') or double (")
41 * quotes. If you wan't to include the quote character within a quoted string,
42 * double-up on the quote character: 'I''m hungry' is equivalent to
45 * Force regex on "re:word" => posix-style, "/word/" => pcre-style
46 * or use regex='glob' to use file wildcard-like matching. (not yet)
48 * The parsed tree is then converted to the needed PCRE (highlight,
49 * simple backends) or SQL functions.
51 * @author: Jeff Dairiki
52 * @author: Reini Urban (case and regex detection, enhanced sql callbacks)
55 // regex-style: 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
56 define ('TSQ_REGEX_NONE', 0);
57 define ('TSQ_REGEX_AUTO', 1);
58 define ('TSQ_REGEX_POSIX', 2);
59 define ('TSQ_REGEX_GLOB', 4);
60 define ('TSQ_REGEX_PCRE', 8);
61 define ('TSQ_REGEX_SQL', 16);
63 class TextSearchQuery {
67 * @param $search_query string The query. Syntax is as described above.
68 * Note that an empty $search_query will match anything.
69 * @param $case_exact boolean
70 * @param $regex string one of 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
71 * @see TextSearchQuery
73 function TextSearchQuery($search_query, $case_exact=false, $regex='auto') {
74 if ($regex == 'none' or !$regex)
76 elseif (defined("TSQ_REGEX_".strtoupper($regex)))
77 $this->_regex = constant("TSQ_REGEX_".strtoupper($regex));
79 trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex));
82 $this->_case_exact = $case_exact;
83 $parser = new TextSearchQuery_Parser;
84 $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex);
85 //$this->_optimize(); // broken under certain circumstances: "word -word -word"
86 $this->_stoplist = '(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)';
89 function _optimize() {
90 $this->_tree = $this->_tree->optimize();
94 * Get a PCRE regexp which matches the query.
97 if (!isset($this->_regexp)) {
99 $this->_regexp = '/' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
101 $this->_regexp = '/^' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
103 return $this->_regexp;
107 * Match query against string.
109 * @param $string string The string to match.
110 * @return boolean True if the string matches the query.
112 function match($string) {
113 return preg_match($this->asRegexp(), $string);
118 * Get a regular expression suitable for highlighting matched words.
120 * This returns a PCRE regular expression which matches any non-negated
123 * @return string The PCRE regexp.
125 function getHighlightRegexp() {
126 if (!isset($this->_hilight_regexp)) {
127 $words = array_unique($this->_tree->highlight_words());
129 $this->_hilight_regexp = false;
131 foreach ($words as $key => $word)
132 $words[$key] = preg_quote($word, '/');
133 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
136 return $this->_hilight_regexp;
140 * Make an SQL clause which matches the query. (deprecated, use makeSqlClause instead)
142 * @param $make_sql_clause_cb WikiCallback
143 * A callback which takes a single word as an argument and
144 * returns an SQL clause which will match exactly those records
145 * containing the word. The word passed to the callback will always
146 * be in all lower case.
148 * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
149 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
150 * How? WikiDB backend method?
154 * function sql_title_match($word) {
155 * return sprintf("LOWER(title) like '%s'",
156 * addslashes($word));
161 * $query = new TextSearchQuery("wiki -page");
162 * $cb = new WikiFunctionCb('sql_title_match');
163 * $sql_clause = $query->makeSqlClause($cb);
165 * This will result in $sql_clause containing something like
166 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
168 * @return string The SQL clause.
170 function makeSqlClause($sql_clause_cb) {
171 $this->_sql_clause_cb = $sql_clause_cb;
172 return $this->_sql_clause($this->_tree);
174 // deprecated: use _sql_clause_obj now.
175 function _sql_clause($node) {
177 case 'WORD': // word => %word%
178 return $this->_sql_clause_cb->call($node->word);
180 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
183 $subclauses = array();
184 foreach ($node->leaves as $leaf)
185 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
186 return join(" $node->op ", $subclauses);
188 assert($node->op == VOID);
193 /** Get away with the callback and use a db-specific search class instead.
194 * @see WikiDB_backend_PearDB_search
196 function makeSqlClauseObj(&$sql_search_cb) {
197 $this->_sql_clause_cb = $sql_search_cb;
198 return $this->_sql_clause_obj($this->_tree);
201 function _sql_clause_obj($node) {
204 return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
207 $subclauses = array();
208 foreach ($node->leaves as $leaf)
209 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
210 return join(" $node->op ", $subclauses);
214 return $this->_sql_clause_cb->call($node);
218 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
221 * Get printable representation of the parse tree.
223 * This is for debugging only.
224 * @return string Printable parse tree.
226 function asString() {
227 return $this->_as_string($this->_tree);
230 function _as_string($node, $indent = '') {
233 return $indent . "WORD: $node->word";
235 return $indent . "VOID";
237 $lines = array($indent . $node->op . ":");
239 foreach ($node->leaves as $leaf)
240 $lines[] = $this->_as_string($leaf, $indent);
241 return join("\n", $lines);
247 * This is a TextSearchQuery which matches nothing.
249 class NullTextSearchQuery extends TextSearchQuery {
251 * Create a new query.
253 * @see TextSearchQuery
255 function NullTextSearchQuery() {}
256 function asRegexp() { return '/^(?!a)a/x'; }
257 function match($string) { return false; }
258 function getHighlightRegexp() { return ""; }
259 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
260 function asString() { return "NullTextSearchQuery"; }
264 ////////////////////////////////////////////////////////////////
266 // Remaining classes are private.
268 ////////////////////////////////////////////////////////////////
270 * Virtual base class for nodes in a TextSearchQuery parse tree.
272 * Also servers as a 'VOID' (contentless) node.
274 class TextSearchQuery_node
279 * Optimize this node.
280 * @return object Optimized node.
282 function optimize() {
287 * @return regexp matching this node.
294 * @param bool True if this node has been negated (higher in the parse tree.)
295 * @return array A list of all non-negated words contained by this node.
297 function highlight_words($negated = false) {
301 function sql() { return $this->word; }
307 class TextSearchQuery_node_word
308 extends TextSearchQuery_node
312 function TextSearchQuery_node_word($word) {
316 return '(?=.*' . preg_quote($this->word, '/') . ')';
318 function highlight_words($negated = false) {
319 return $negated ? array() : array($this->word);
321 function _sql_quote() {
322 $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
323 return $GLOBALS['request']->_dbi->qstr($word);
325 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
328 class TextSearchQuery_node_starts_with
329 extends TextSearchQuery_node_word {
330 var $op = "STARTS_WITH";
331 function regexp() { return '(?=.*\b' . preg_quote($this->word, '/') . ')'; }
332 function sql() { return $this->_sql_quote($this->word).'%'; }
335 class TextSearchQuery_node_ends_with
336 extends TextSearchQuery_node_word {
337 var $op = "ENDS_WITH";
338 function regexp() { return '(?=.*' . preg_quote($this->word, '/') . '\b)'; }
339 function sql() { return '%'.$this->_sql_quote($this->word); }
342 class TextSearchQuery_node_exact
343 extends TextSearchQuery_node_word {
345 function regexp() { return '(?=\b' . preg_quote($this->word, '/') . '\b)'; }
346 function sql() { return $this->_sql_squote($this->word); }
349 class TextSearchQuery_node_regex // posix regex. FIXME!
350 extends TextSearchQuery_node_word {
351 var $op = "REGEX"; // using REGEXP or ~ extension
352 function regexp() { return '(?=.*\b' . $this->word . '\b)'; }
353 function sql() { return $this->_sql_quote($this->word); }
356 class TextSearchQuery_node_regex_glob
357 extends TextSearchQuery_node_regex {
358 var $op = "REGEX_GLOB";
359 function regexp() { return '(?=.*\b' . glob_to_pcre($this->word) . '\b)'; }
362 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
363 extends TextSearchQuery_node_regex {
364 var $op = "REGEX_PCRE";
365 function regexp() { return $this->word; }
368 class TextSearchQuery_node_regex_sql
369 extends TextSearchQuery_node_regex {
370 var $op = "REGEX_SQL"; // using LIKE
371 function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
372 function sql() { return $this->word; }
378 class TextSearchQuery_node_not
379 extends TextSearchQuery_node
383 function TextSearchQuery_node_not($leaf) {
384 $this->leaves = array($leaf);
387 function optimize() {
388 $leaf = &$this->leaves[0];
389 $leaf = $leaf->optimize();
390 if ($leaf->op == 'NOT')
391 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
396 $leaf = &$this->leaves[0];
397 return '(?!' . $leaf->regexp() . ')';
400 function highlight_words($negated = false) {
401 return $this->leaves[0]->highlight_words(!$negated);
406 * Virtual base class for 'AND' and 'OR conjoins.
408 class TextSearchQuery_node_binop
409 extends TextSearchQuery_node
411 function TextSearchQuery_node_binop($leaves) {
412 $this->leaves = $leaves;
415 function _flatten() {
416 // This flattens e.g. (AND (AND a b) (OR c d) e)
417 // to (AND a b e (OR c d))
419 foreach ($this->leaves as $leaf) {
420 $leaf = $leaf->optimize();
421 if ($this->op == $leaf->op)
422 $flat = array_merge($flat, $leaf->leaves);
426 $this->leaves = $flat;
429 function optimize() {
431 assert(!empty($this->leaves));
432 if (count($this->leaves) == 1)
433 return $this->leaves[0]; // (AND x) -> x
437 function highlight_words($negated = false) {
439 foreach ($this->leaves as $leaf)
440 array_splice($words,0,0,
441 $leaf->highlight_words($negated));
447 * A (possibly multi-argument) 'AND' conjoin.
449 class TextSearchQuery_node_and
450 extends TextSearchQuery_node_binop
454 function optimize() {
457 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
458 // Since OR's are more efficient for regexp matching:
459 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
461 // Suck out the negated leaves.
463 foreach ($this->leaves as $key => $leaf) {
464 if ($leaf->op == 'NOT') {
465 $nots[] = $leaf->leaves[0];
466 unset($this->leaves[$key]);
470 // Combine the negated leaves into a single negated or.
472 $node = ( new TextSearchQuery_node_not
473 (new TextSearchQuery_node_or($nots)) );
474 array_unshift($this->leaves, $node->optimize());
477 assert(!empty($this->leaves));
478 if (count($this->leaves) == 1)
479 return $this->leaves[0]; // (AND x) -> x
484 * Either we need all combinations of all words to be position independent,
485 * or we have to use multiple match calls for each AND
486 * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
490 foreach ($this->leaves as $leaf)
491 $regexp .= $leaf->regexp();
497 * A (possibly multi-argument) 'OR' conjoin.
499 class TextSearchQuery_node_or
500 extends TextSearchQuery_node_binop
505 // We will combine any of our direct descendents which are WORDs
506 // into a single (?=.*(?:word1|word2|...)) regexp.
511 foreach ($this->leaves as $leaf) {
512 if ($leaf->op == 'WORD')
513 $words[] = preg_quote($leaf->word, '/');
515 $regexps[] = $leaf->regexp();
519 array_unshift($regexps,
520 '(?=.*' . $this->_join($words) . ')');
522 return $this->_join($regexps);
525 function _join($regexps) {
526 assert(count($regexps) > 0);
528 if (count($regexps) > 1)
529 return '(?:' . join('|', $regexps) . ')';
536 ////////////////////////////////////////////////////////////////
539 // op's (and, or, not) are forced to lowercase in the tokenizer.
541 ////////////////////////////////////////////////////////////////
542 define ('TSQ_TOK_BINOP', 1);
543 define ('TSQ_TOK_NOT', 2);
544 define ('TSQ_TOK_LPAREN', 4);
545 define ('TSQ_TOK_RPAREN', 8);
546 define ('TSQ_TOK_WORD', 16);
547 define ('TSQ_TOK_STARTS_WITH', 32);
548 define ('TSQ_TOK_ENDS_WITH', 64);
549 define ('TSQ_TOK_EXACT', 128);
550 define ('TSQ_TOK_REGEX', 256);
551 define ('TSQ_TOK_REGEX_GLOB', 512);
552 define ('TSQ_TOK_REGEX_PCRE', 1024);
553 define ('TSQ_TOK_REGEX_SQL', 2048);
554 // all bits from word to the last.
555 define ('TSQ_ALLWORDS', (2048*2)-1 - (16-1));
557 class TextSearchQuery_Parser
560 * This is a simple recursive descent parser, based on the following grammar:
575 * atom : '(' list ')'
580 * The terminal tokens are:
587 * /[^-()\s][^()\s]* WORD
597 function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
598 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
599 $this->_regex = $regex;
600 $tree = $this->get_list('toplevel');
601 assert($this->lexer->eof());
606 function get_list ($is_toplevel = false) {
609 // token types we'll accept as words (and thus expr's) for the
610 // purpose of error recovery:
611 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
613 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
615 while ( ($expr = $this->get_expr())
616 || ($expr = $this->get_word($accept_as_words)) ) {
622 return new TextSearchQuery_node;
626 return new TextSearchQuery_node_and($list);
629 function get_expr () {
630 if ( !($expr = $this->get_atom()) )
633 $savedpos = $this->lexer->tell();
634 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
635 if ( ! ($right = $this->get_atom()) ) {
640 $expr = new TextSearchQuery_node_and(array($expr, $right));
643 $expr = new TextSearchQuery_node_or(array($expr, $right));
646 $savedpos = $this->lexer->tell();
648 $this->lexer->seek($savedpos);
654 function get_atom() {
655 if ($word = $this->get_word(TSQ_ALLWORDS))
658 $savedpos = $this->lexer->tell();
659 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
660 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
663 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
664 if ( ($atom = $this->get_atom()) )
665 return new TextSearchQuery_node_not($atom);
667 $this->lexer->seek($savedpos);
671 function get_word($accept = TSQ_ALLWORDS) {
672 foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
673 "REGEX","REGEX_GLOB","REGEX_PCRE") as $tok) {
674 $const = constant("TSQ_TOK_".$tok);
675 if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
676 $classname = "TextSearchQuery_node_".strtolower($tok);
677 return new $classname($word);
684 class TextSearchQuery_Lexer {
685 function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
686 $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
694 function seek($pos) {
699 return $this->pos == count($this->tokens);
703 * TODO: support more regex styles, esp. prefer the forced ones over auto
706 function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
708 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
709 while (!empty($buf)) {
710 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
711 $val = strtolower($m[1]);
712 $type = TSQ_TOK_BINOP;
714 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
715 $val = strtolower($m[1]);
718 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
720 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
723 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
724 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
726 $type = TSQ_TOK_STARTS_WITH;
729 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
730 and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
732 $type = TSQ_TOK_STARTS_WITH;
735 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
736 and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
738 $type = TSQ_TOK_ENDS_WITH;
741 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
742 and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
744 $type = TSQ_TOK_ENDS_WITH;
747 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
748 and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
750 $type = TSQ_TOK_EXACT;
753 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
754 $val = str_replace('""', '"', $m[1]);
755 $type = TSQ_TOK_WORD;
758 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
759 $val = str_replace("''", "'", $m[1]);
760 $type = TSQ_TOK_WORD;
763 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
765 $type = TSQ_TOK_WORD;
771 $buf = substr($buf, strlen($m[0]));
773 /* refine the simple parsing from above: bla*bla, bla?bla, ...
774 if ($regex and $type == TSQ_TOK_WORD) {
775 if (substr($val,0,1) == "^")
776 $type = TSQ_TOK_STARTS_WITH;
777 elseif (substr($val,0,1) == "*")
778 $type = TSQ_TOK_ENDS_WITH;
779 elseif (substr($val,-1,1) == "*")
780 $type = TSQ_TOK_STARTS_WITH;
783 $tokens[] = array($type, $val);
788 function get($accept) {
789 if ($this->pos >= count($this->tokens))
792 list ($type, $val) = $this->tokens[$this->pos];
793 if (($type & $accept) == 0)
805 // c-hanging-comment-ender-p: nil
806 // indent-tabs-mode: nil