1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.23 2006-04-13 19:30:44 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 if (defined("FULLTEXTSEARCH_STOPLIST"))
87 $this->_stoplist = FULLTEXTSEARCH_STOPLIST;
88 else // default stoplist, localizable.
89 $this->_stoplist = _("(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)");
92 function _optimize() {
93 $this->_tree = $this->_tree->optimize();
97 * Get a PCRE regexp which matches the query.
100 if (!isset($this->_regexp)) {
102 $this->_regexp = '/' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
104 $this->_regexp = '/^' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
106 return $this->_regexp;
110 * Match query against string.
112 * @param $string string The string to match.
113 * @return boolean True if the string matches the query.
115 function match($string) {
116 return preg_match($this->asRegexp(), $string);
121 * Get a regular expression suitable for highlighting matched words.
123 * This returns a PCRE regular expression which matches any non-negated
126 * @return string The PCRE regexp.
128 function getHighlightRegexp() {
129 if (!isset($this->_hilight_regexp)) {
130 $words = array_unique($this->_tree->highlight_words());
132 $this->_hilight_regexp = false;
134 foreach ($words as $key => $word)
135 $words[$key] = preg_quote($word, '/');
136 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
139 return $this->_hilight_regexp;
143 * Make an SQL clause which matches the query. (deprecated, use makeSqlClause instead)
145 * @param $make_sql_clause_cb WikiCallback
146 * A callback which takes a single word as an argument and
147 * returns an SQL clause which will match exactly those records
148 * containing the word. The word passed to the callback will always
149 * be in all lower case.
151 * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
152 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
153 * How? WikiDB backend method?
157 * function sql_title_match($word) {
158 * return sprintf("LOWER(title) like '%s'",
159 * addslashes($word));
164 * $query = new TextSearchQuery("wiki -page");
165 * $cb = new WikiFunctionCb('sql_title_match');
166 * $sql_clause = $query->makeSqlClause($cb);
168 * This will result in $sql_clause containing something like
169 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
171 * @return string The SQL clause.
173 function makeSqlClause($sql_clause_cb) {
174 $this->_sql_clause_cb = $sql_clause_cb;
175 return $this->_sql_clause($this->_tree);
177 // deprecated: use _sql_clause_obj now.
178 function _sql_clause($node) {
180 case 'WORD': // word => %word%
181 return $this->_sql_clause_cb->call($node->word);
183 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
186 $subclauses = array();
187 foreach ($node->leaves as $leaf)
188 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
189 return join(" $node->op ", $subclauses);
191 assert($node->op == 'VOID');
196 /** Get away with the callback and use a db-specific search class instead.
197 * @see WikiDB_backend_PearDB_search
199 function makeSqlClauseObj(&$sql_search_cb) {
200 $this->_sql_clause_cb = $sql_search_cb;
201 return $this->_sql_clause_obj($this->_tree);
204 function _sql_clause_obj($node) {
207 return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
210 $subclauses = array();
211 foreach ($node->leaves as $leaf)
212 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
213 return join(" $node->op ", $subclauses);
219 return $this->_sql_clause_cb->call($node);
224 postgresql tsearch2 uses no WHERE operators, just & | and ! in the searchstring
226 function makeTsearch2SqlClauseObj(&$sql_search_cb) {
227 $this->_sql_clause_cb = $sql_search_cb;
228 return $this->_Tsearch2Sql_clause_obj($this->_tree);
231 function _Tsearch2Sql_clause_obj($node) {
232 // TODO: "such a phrase"
235 return "!" . $node->leaves[0];
237 $subclauses = array();
238 foreach ($node->leaves as $leaf)
239 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
240 return join("&", $subclauses);
242 $subclauses = array();
243 foreach ($node->leaves as $leaf)
244 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
245 return join("|", $subclauses);
251 return $this->_sql_clause_cb->call($node);
255 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
258 * Get printable representation of the parse tree.
260 * This is for debugging only.
261 * @return string Printable parse tree.
263 function asString() {
264 return $this->_as_string($this->_tree);
267 function _as_string($node, $indent = '') {
270 return $indent . "WORD: $node->word";
272 return $indent . "VOID";
274 return $indent . "ALL";
276 $lines = array($indent . $node->op . ":");
278 foreach ($node->leaves as $leaf)
279 $lines[] = $this->_as_string($leaf, $indent);
280 return join("\n", $lines);
286 * This is a TextSearchQuery which matches nothing.
288 class NullTextSearchQuery extends TextSearchQuery {
290 * Create a new query.
292 * @see TextSearchQuery
294 function NullTextSearchQuery() {}
295 function asRegexp() { return '/^(?!a)a/x'; }
296 function match($string) { return false; }
297 function getHighlightRegexp() { return ""; }
298 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
299 function asString() { return "NullTextSearchQuery"; }
303 ////////////////////////////////////////////////////////////////
305 // Remaining classes are private.
307 ////////////////////////////////////////////////////////////////
309 * Virtual base class for nodes in a TextSearchQuery parse tree.
311 * Also serves as a 'VOID' (contentless) node.
313 class TextSearchQuery_node
318 * Optimize this node.
319 * @return object Optimized node.
321 function optimize() {
326 * @return regexp matching this node.
333 * @param bool True if this node has been negated (higher in the parse tree.)
334 * @return array A list of all non-negated words contained by this node.
336 function highlight_words($negated = false) {
340 function sql() { return $this->word; }
346 class TextSearchQuery_node_word
347 extends TextSearchQuery_node
351 function TextSearchQuery_node_word($word) {
355 return '(?=.*' . preg_quote($this->word, '/') . ')';
357 function highlight_words ($negated = false) {
358 return $negated ? array() : array($this->word);
360 function _sql_quote() {
361 $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
362 return $GLOBALS['request']->_dbi->qstr($word);
364 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
367 class TextSearchQuery_node_all
368 extends TextSearchQuery_node {
370 function regexp() { return '(?=.*)'; }
371 function sql() { return '%'; }
373 class TextSearchQuery_node_starts_with
374 extends TextSearchQuery_node_word {
375 var $op = "STARTS_WITH";
376 function regexp() { return '(?=.*\b' . preg_quote($this->word, '/') . ')'; }
377 function sql () { return $this->_sql_quote($this->word).'%'; }
380 class TextSearchQuery_node_ends_with
381 extends TextSearchQuery_node_word {
382 var $op = "ENDS_WITH";
383 function regexp() { return '(?=.*' . preg_quote($this->word, '/') . '\b)'; }
384 function sql () { return '%'.$this->_sql_quote($this->word); }
387 class TextSearchQuery_node_exact
388 extends TextSearchQuery_node_word {
390 function regexp() { return '(?=\b' . preg_quote($this->word, '/') . '\b)'; }
391 function sql () { return $this->_sql_squote($this->word); }
394 class TextSearchQuery_node_regex // posix regex. FIXME!
395 extends TextSearchQuery_node_word {
396 var $op = "REGEX"; // using REGEXP or ~ extension
397 function regexp() { return '(?=.*\b' . $this->word . '\b)'; }
398 function sql () { return $this->_sql_quote($this->word); }
401 class TextSearchQuery_node_regex_glob
402 extends TextSearchQuery_node_regex {
403 var $op = "REGEX_GLOB";
404 function regexp() { return '(?=.*\b' . glob_to_pcre($this->word) . '\b)'; }
407 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
408 extends TextSearchQuery_node_regex {
409 var $op = "REGEX_PCRE";
410 function regexp() { return $this->word; }
413 class TextSearchQuery_node_regex_sql
414 extends TextSearchQuery_node_regex {
415 var $op = "REGEX_SQL"; // using LIKE
416 function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
417 function sql() { return $this->word; }
423 class TextSearchQuery_node_not
424 extends TextSearchQuery_node
428 function TextSearchQuery_node_not($leaf) {
429 $this->leaves = array($leaf);
432 function optimize() {
433 $leaf = &$this->leaves[0];
434 $leaf = $leaf->optimize();
435 if ($leaf->op == 'NOT')
436 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
441 $leaf = &$this->leaves[0];
442 return '(?!' . $leaf->regexp() . ')';
445 function highlight_words ($negated = false) {
446 return $this->leaves[0]->highlight_words(!$negated);
451 * Virtual base class for 'AND' and 'OR conjoins.
453 class TextSearchQuery_node_binop
454 extends TextSearchQuery_node
456 function TextSearchQuery_node_binop($leaves) {
457 $this->leaves = $leaves;
460 function _flatten() {
461 // This flattens e.g. (AND (AND a b) (OR c d) e)
462 // to (AND a b e (OR c d))
464 foreach ($this->leaves as $leaf) {
465 $leaf = $leaf->optimize();
466 if ($this->op == $leaf->op)
467 $flat = array_merge($flat, $leaf->leaves);
471 $this->leaves = $flat;
474 function optimize() {
476 assert(!empty($this->leaves));
477 if (count($this->leaves) == 1)
478 return $this->leaves[0]; // (AND x) -> x
482 function highlight_words($negated = false) {
484 foreach ($this->leaves as $leaf)
485 array_splice($words,0,0,
486 $leaf->highlight_words($negated));
492 * A (possibly multi-argument) 'AND' conjoin.
494 class TextSearchQuery_node_and
495 extends TextSearchQuery_node_binop
499 function optimize() {
502 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
503 // Since OR's are more efficient for regexp matching:
504 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
506 // Suck out the negated leaves.
508 foreach ($this->leaves as $key => $leaf) {
509 if ($leaf->op == 'NOT') {
510 $nots[] = $leaf->leaves[0];
511 unset($this->leaves[$key]);
515 // Combine the negated leaves into a single negated or.
517 $node = ( new TextSearchQuery_node_not
518 (new TextSearchQuery_node_or($nots)) );
519 array_unshift($this->leaves, $node->optimize());
522 assert(!empty($this->leaves));
523 if (count($this->leaves) == 1)
524 return $this->leaves[0]; // (AND x) -> x
529 * Either we need all combinations of all words to be position independent,
530 * or we have to use multiple match calls for each AND
531 * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
535 foreach ($this->leaves as $leaf)
536 $regexp .= $leaf->regexp();
542 * A (possibly multi-argument) 'OR' conjoin.
544 class TextSearchQuery_node_or
545 extends TextSearchQuery_node_binop
550 // We will combine any of our direct descendents which are WORDs
551 // into a single (?=.*(?:word1|word2|...)) regexp.
556 foreach ($this->leaves as $leaf) {
557 if ($leaf->op == 'WORD')
558 $words[] = preg_quote($leaf->word, '/');
560 $regexps[] = $leaf->regexp();
564 array_unshift($regexps,
565 '(?=.*' . $this->_join($words) . ')');
567 return $this->_join($regexps);
570 function _join($regexps) {
571 assert(count($regexps) > 0);
573 if (count($regexps) > 1)
574 return '(?:' . join('|', $regexps) . ')';
581 ////////////////////////////////////////////////////////////////
584 // op's (and, or, not) are forced to lowercase in the tokenizer.
586 ////////////////////////////////////////////////////////////////
587 define ('TSQ_TOK_BINOP', 1);
588 define ('TSQ_TOK_NOT', 2);
589 define ('TSQ_TOK_LPAREN', 4);
590 define ('TSQ_TOK_RPAREN', 8);
591 define ('TSQ_TOK_WORD', 16);
592 define ('TSQ_TOK_STARTS_WITH', 32);
593 define ('TSQ_TOK_ENDS_WITH', 64);
594 define ('TSQ_TOK_EXACT', 128);
595 define ('TSQ_TOK_REGEX', 256);
596 define ('TSQ_TOK_REGEX_GLOB', 512);
597 define ('TSQ_TOK_REGEX_PCRE', 1024);
598 define ('TSQ_TOK_REGEX_SQL', 2048);
599 define ('TSQ_TOK_ALL', 4096);
600 // all bits from word to the last.
601 define ('TSQ_ALLWORDS', (4096*2)-1 - (16-1));
603 class TextSearchQuery_Parser
606 * This is a simple recursive descent parser, based on the following grammar:
621 * atom : '(' list ')'
626 * The terminal tokens are:
633 * /[^-()\s][^()\s]* WORD
644 function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
645 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
646 $this->_regex = $regex;
647 $tree = $this->get_list('toplevel');
648 assert($this->lexer->eof());
653 function get_list ($is_toplevel = false) {
656 // token types we'll accept as words (and thus expr's) for the
657 // purpose of error recovery:
658 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
660 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
662 while ( ($expr = $this->get_expr())
663 || ($expr = $this->get_word($accept_as_words)) ) {
669 return new TextSearchQuery_node;
673 return new TextSearchQuery_node_and($list);
676 function get_expr () {
677 if ( !($expr = $this->get_atom()) )
680 $savedpos = $this->lexer->tell();
681 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
682 if ( ! ($right = $this->get_atom()) ) {
687 $expr = new TextSearchQuery_node_and(array($expr, $right));
690 $expr = new TextSearchQuery_node_or(array($expr, $right));
693 $savedpos = $this->lexer->tell();
695 $this->lexer->seek($savedpos);
701 function get_atom() {
702 if ($word = $this->get_word(TSQ_ALLWORDS))
705 $savedpos = $this->lexer->tell();
706 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
707 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
710 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
711 if ( ($atom = $this->get_atom()) )
712 return new TextSearchQuery_node_not($atom);
714 $this->lexer->seek($savedpos);
718 function get_word($accept = TSQ_ALLWORDS) {
719 foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
720 "REGEX","REGEX_GLOB","REGEX_PCRE","ALL") as $tok) {
721 $const = constant("TSQ_TOK_".$tok);
722 if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
723 $classname = "TextSearchQuery_node_".strtolower($tok);
724 return new $classname($word);
731 class TextSearchQuery_Lexer {
732 function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
733 $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
741 function seek($pos) {
746 return $this->pos == count($this->tokens);
750 * TODO: support more regex styles, esp. prefer the forced ones over auto
753 function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
755 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
756 while (!empty($buf)) {
757 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
758 $val = strtolower($m[1]);
759 $type = TSQ_TOK_BINOP;
761 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
762 $val = strtolower($m[1]);
765 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
767 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
771 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
772 and preg_match('/^\*\s*/', $buf, $m)) {
777 elseif ($regex & (TSQ_REGEX_PCRE)
778 and preg_match('/^\.\*\s*/', $buf, $m)) {
783 elseif ($regex & (TSQ_REGEX_SQL)
784 and preg_match('/^%\s*/', $buf, $m)) {
790 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
791 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
793 $type = TSQ_TOK_STARTS_WITH;
796 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
797 and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
799 $type = TSQ_TOK_STARTS_WITH;
802 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
803 and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
805 $type = TSQ_TOK_ENDS_WITH;
808 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
809 and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
811 $type = TSQ_TOK_ENDS_WITH;
814 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
815 and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
817 $type = TSQ_TOK_EXACT;
821 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
822 $val = str_replace('""', '"', $m[1]);
823 $type = TSQ_TOK_WORD;
826 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
827 $val = str_replace("''", "'", $m[1]);
828 $type = TSQ_TOK_WORD;
831 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
833 $type = TSQ_TOK_WORD;
839 $buf = substr($buf, strlen($m[0]));
841 /* refine the simple parsing from above: bla*bla, bla?bla, ...
842 if ($regex and $type == TSQ_TOK_WORD) {
843 if (substr($val,0,1) == "^")
844 $type = TSQ_TOK_STARTS_WITH;
845 elseif (substr($val,0,1) == "*")
846 $type = TSQ_TOK_ENDS_WITH;
847 elseif (substr($val,-1,1) == "*")
848 $type = TSQ_TOK_STARTS_WITH;
851 $tokens[] = array($type, $val);
856 function get($accept) {
857 if ($this->pos >= count($this->tokens))
860 list ($type, $val) = $this->tokens[$this->pos];
861 if (($type & $accept) == 0)
869 // $Log: not supported by cvs2svn $
875 // c-hanging-comment-ender-p: nil
876 // indent-tabs-mode: nil