1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.18 2005-02-26 18:30:40 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"
88 function _optimize() {
89 $this->_tree = $this->_tree->optimize();
93 * Get a PCRE regexp which matches the query.
96 if (!isset($this->_regexp)) {
98 $this->_regexp = '/' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
100 $this->_regexp = '/^' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
102 return $this->_regexp;
106 * Match query against string.
108 * @param $string string The string to match.
109 * @return boolean True if the string matches the query.
111 function match($string) {
112 return preg_match($this->asRegexp(), $string);
117 * Get a regular expression suitable for highlighting matched words.
119 * This returns a PCRE regular expression which matches any non-negated
122 * @return string The PCRE regexp.
124 function getHighlightRegexp() {
125 if (!isset($this->_hilight_regexp)) {
126 $words = array_unique($this->_tree->highlight_words());
128 $this->_hilight_regexp = false;
130 foreach ($words as $key => $word)
131 $words[$key] = preg_quote($word, '/');
132 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
135 return $this->_hilight_regexp;
139 * Make an SQL clause which matches the query. (deprecated, use makeSqlClause instead)
141 * @param $make_sql_clause_cb WikiCallback
142 * A callback which takes a single word as an argument and
143 * returns an SQL clause which will match exactly those records
144 * containing the word. The word passed to the callback will always
145 * be in all lower case.
147 * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
148 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
149 * How? WikiDB backend method?
153 * function sql_title_match($word) {
154 * return sprintf("LOWER(title) like '%s'",
155 * addslashes($word));
160 * $query = new TextSearchQuery("wiki -page");
161 * $cb = new WikiFunctionCb('sql_title_match');
162 * $sql_clause = $query->makeSqlClause($cb);
164 * This will result in $sql_clause containing something like
165 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
167 * @return string The SQL clause.
169 function makeSqlClause($sql_clause_cb) {
170 $this->_sql_clause_cb = $sql_clause_cb;
171 return $this->_sql_clause($this->_tree);
173 // deprecated: use _sql_clause_obj now.
174 function _sql_clause($node) {
176 case 'WORD': // word => %word%
177 return $this->_sql_clause_cb->call($node->word);
179 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
182 $subclauses = array();
183 foreach ($node->leaves as $leaf)
184 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
185 return join(" $node->op ", $subclauses);
187 assert($node->op == VOID);
192 /** Get away with the callback and use a db-specific search class instead.
193 * @see WikiDB_backend_PearDB_search
195 function makeSqlClauseObj(&$sql_search_cb) {
196 $this->_sql_clause_cb = $sql_search_cb;
197 return $this->_sql_clause_obj($this->_tree);
200 function _sql_clause_obj($node) {
203 return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
206 $subclauses = array();
207 foreach ($node->leaves as $leaf)
208 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
209 return join(" $node->op ", $subclauses);
213 return $this->_sql_clause_cb->call($node);
217 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
220 * Get printable representation of the parse tree.
222 * This is for debugging only.
223 * @return string Printable parse tree.
225 function asString() {
226 return $this->_as_string($this->_tree);
229 function _as_string($node, $indent = '') {
232 return $indent . "WORD: $node->word";
234 return $indent . "VOID";
236 $lines = array($indent . $node->op . ":");
238 foreach ($node->leaves as $leaf)
239 $lines[] = $this->_as_string($leaf, $indent);
240 return join("\n", $lines);
246 * This is a TextSearchQuery which matches nothing.
248 class NullTextSearchQuery extends TextSearchQuery {
250 * Create a new query.
252 * @see TextSearchQuery
254 function NullTextSearchQuery() {}
255 function asRegexp() { return '/^(?!a)a/x'; }
256 function match($string) { return false; }
257 function getHighlightRegexp() { return ""; }
258 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
259 function asString() { return "NullTextSearchQuery"; }
263 ////////////////////////////////////////////////////////////////
265 // Remaining classes are private.
267 ////////////////////////////////////////////////////////////////
269 * Virtual base class for nodes in a TextSearchQuery parse tree.
271 * Also servers as a 'VOID' (contentless) node.
273 class TextSearchQuery_node
278 * Optimize this node.
279 * @return object Optimized node.
281 function optimize() {
286 * @return regexp matching this node.
293 * @param bool True if this node has been negated (higher in the parse tree.)
294 * @return array A list of all non-negated words contained by this node.
296 function highlight_words($negated = false) {
300 function sql() { return $this->word; }
306 class TextSearchQuery_node_word
307 extends TextSearchQuery_node
311 function TextSearchQuery_node_word($word) {
315 return '(?=.*' . preg_quote($this->word, '/') . ')';
317 function highlight_words($negated = false) {
318 return $negated ? array() : array($this->word);
320 function _sql_quote() {
321 $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
322 return $GLOBALS['request']->_dbi->qstr($word);
324 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
327 class TextSearchQuery_node_starts_with
328 extends TextSearchQuery_node_word {
329 var $op = "STARTS_WITH";
330 function regexp() { return '(?=\b' . preg_quote($this->word, '/') . ')'; }
331 function sql() { return $this->_sql_quote($this->word).'%'; }
334 class TextSearchQuery_node_ends_with
335 extends TextSearchQuery_node_word {
336 var $op = "ENDS_WITH";
337 function regexp() { return '(?=' . preg_quote($this->word, '/') . '\b)'; }
338 function sql() { return '%'.$this->_sql_quote($this->word); }
341 class TextSearchQuery_node_exact
342 extends TextSearchQuery_node_word {
344 function regexp() { return '(?=\b' . preg_quote($this->word, '/') . '\b)'; }
345 function sql() { return $this->_sql_squote($this->word); }
348 class TextSearchQuery_node_regex // posix regex. FIXME!
349 extends TextSearchQuery_node_word {
350 var $op = "REGEX"; // using REGEXP or ~ extension
351 function regexp() { return '(?=\b' . $this->word . '\b)'; }
352 function sql() { return $this->_sql_quote($this->word); }
355 class TextSearchQuery_node_regex_glob
356 extends TextSearchQuery_node_regex {
357 var $op = "REGEX_GLOB";
358 function regexp() { return '(?=\b' . glob_to_pcre($this->word) . '\b)'; }
361 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
362 extends TextSearchQuery_node_regex {
363 var $op = "REGEX_PCRE";
364 function regexp() { return $this->word; }
367 class TextSearchQuery_node_regex_sql
368 extends TextSearchQuery_node_regex {
369 var $op = "REGEX_SQL"; // using LIKE
370 function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
371 function sql() { return $this->word; }
377 class TextSearchQuery_node_not
378 extends TextSearchQuery_node
382 function TextSearchQuery_node_not($leaf) {
383 $this->leaves = array($leaf);
386 function optimize() {
387 $leaf = &$this->leaves[0];
388 $leaf = $leaf->optimize();
389 if ($leaf->op == 'NOT')
390 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
395 $leaf = &$this->leaves[0];
396 return '(?!' . $leaf->regexp() . ')';
399 function highlight_words($negated = false) {
400 return $this->leaves[0]->highlight_words(!$negated);
405 * Virtual base class for 'AND' and 'OR conjoins.
407 class TextSearchQuery_node_binop
408 extends TextSearchQuery_node
410 function TextSearchQuery_node_binop($leaves) {
411 $this->leaves = $leaves;
414 function _flatten() {
415 // This flattens e.g. (AND (AND a b) (OR c d) e)
416 // to (AND a b e (OR c d))
418 foreach ($this->leaves as $leaf) {
419 $leaf = $leaf->optimize();
420 if ($this->op == $leaf->op)
421 $flat = array_merge($flat, $leaf->leaves);
425 $this->leaves = $flat;
428 function optimize() {
430 assert(!empty($this->leaves));
431 if (count($this->leaves) == 1)
432 return $this->leaves[0]; // (AND x) -> x
436 function highlight_words($negated = false) {
438 foreach ($this->leaves as $leaf)
439 array_splice($words,0,0,
440 $leaf->highlight_words($negated));
446 * A (possibly multi-argument) 'AND' conjoin.
448 class TextSearchQuery_node_and
449 extends TextSearchQuery_node_binop
453 function optimize() {
456 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
457 // Since OR's are more efficient for regexp matching:
458 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
460 // Suck out the negated leaves.
462 foreach ($this->leaves as $key => $leaf) {
463 if ($leaf->op == 'NOT') {
464 $nots[] = $leaf->leaves[0];
465 unset($this->leaves[$key]);
469 // Combine the negated leaves into a single negated or.
471 $node = ( new TextSearchQuery_node_not
472 (new TextSearchQuery_node_or($nots)) );
473 array_unshift($this->leaves, $node->optimize());
476 assert(!empty($this->leaves));
477 if (count($this->leaves) == 1)
478 return $this->leaves[0]; // (AND x) -> x
484 foreach ($this->leaves as $leaf)
485 $regexp .= $leaf->regexp();
491 * A (possibly multi-argument) 'OR' conjoin.
493 class TextSearchQuery_node_or
494 extends TextSearchQuery_node_binop
499 // We will combine any of our direct descendents which are WORDs
500 // into a single (?=.*(?:word1|word2|...)) regexp.
505 foreach ($this->leaves as $leaf) {
506 if ($leaf->op == 'WORD')
507 $words[] = preg_quote($leaf->word, '/');
509 $regexps[] = $leaf->regexp();
513 array_unshift($regexps,
514 '(?=.*' . $this->_join($words) . ')');
516 return $this->_join($regexps);
519 function _join($regexps) {
520 assert(count($regexps) > 0);
522 if (count($regexps) > 1)
523 return '(?:' . join('|', $regexps) . ')';
530 ////////////////////////////////////////////////////////////////
533 // op's (and, or, not) are forced to lowercase in the tokenizer.
535 ////////////////////////////////////////////////////////////////
536 define ('TSQ_TOK_BINOP', 1);
537 define ('TSQ_TOK_NOT', 2);
538 define ('TSQ_TOK_LPAREN', 4);
539 define ('TSQ_TOK_RPAREN', 8);
540 define ('TSQ_TOK_WORD', 16);
541 define ('TSQ_TOK_STARTS_WITH', 32);
542 define ('TSQ_TOK_ENDS_WITH', 64);
543 define ('TSQ_TOK_EXACT', 128);
544 define ('TSQ_TOK_REGEX', 256);
545 define ('TSQ_TOK_REGEX_GLOB', 512);
546 define ('TSQ_TOK_REGEX_PCRE', 1024);
547 define ('TSQ_TOK_REGEX_SQL', 2048);
548 // all bits from word to the last.
549 define ('TSQ_ALLWORDS', (2048*2)-1 - (16-1));
551 class TextSearchQuery_Parser
554 * This is a simple recursive descent parser, based on the following grammar:
569 * atom : '(' list ')'
574 * The terminal tokens are:
581 * /[^-()\s][^()\s]* WORD
591 function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
592 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
593 $this->_regex = $regex;
594 $tree = $this->get_list('toplevel');
595 assert($this->lexer->eof());
600 function get_list ($is_toplevel = false) {
603 // token types we'll accept as words (and thus expr's) for the
604 // purpose of error recovery:
605 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
607 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
609 while ( ($expr = $this->get_expr())
610 || ($expr = $this->get_word($accept_as_words)) ) {
616 return new TextSearchQuery_node;
620 return new TextSearchQuery_node_and($list);
623 function get_expr () {
624 if ( !($expr = $this->get_atom()) )
627 $savedpos = $this->lexer->tell();
628 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
629 if ( ! ($right = $this->get_atom()) ) {
634 $expr = new TextSearchQuery_node_and(array($expr, $right));
637 $expr = new TextSearchQuery_node_or(array($expr, $right));
640 $savedpos = $this->lexer->tell();
642 $this->lexer->seek($savedpos);
648 function get_atom() {
649 if ($word = $this->get_word(TSQ_ALLWORDS))
652 $savedpos = $this->lexer->tell();
653 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
654 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
657 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
658 if ( ($atom = $this->get_atom()) )
659 return new TextSearchQuery_node_not($atom);
661 $this->lexer->seek($savedpos);
665 function get_word($accept = TSQ_ALLWORDS) {
666 foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
667 "REGEX","REGEX_GLOB","REGEX_PCRE") as $tok) {
668 $const = constant("TSQ_TOK_".$tok);
669 if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
670 $classname = "TextSearchQuery_node_".strtolower($tok);
671 return new $classname($word);
678 class TextSearchQuery_Lexer {
679 function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
680 $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
688 function seek($pos) {
693 return $this->pos == count($this->tokens);
697 * TODO: support more regex styles, esp. prefer the forced ones over auto
700 function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
702 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
703 while (!empty($buf)) {
704 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
705 $val = strtolower($m[1]);
706 $type = TSQ_TOK_BINOP;
708 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
709 $val = strtolower($m[1]);
712 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
714 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
717 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
718 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
720 $type = TSQ_TOK_STARTS_WITH;
723 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
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_ENDS_WITH;
735 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
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_EXACT;
747 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
748 $val = str_replace('""', '"', $m[1]);
749 $type = TSQ_TOK_WORD;
752 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
753 $val = str_replace("''", "'", $m[1]);
754 $type = TSQ_TOK_WORD;
757 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
759 $type = TSQ_TOK_WORD;
765 $buf = substr($buf, strlen($m[0]));
767 /* refine the simple parsing from above: bla*bla, bla?bla, ...
768 if ($regex and $type == TSQ_TOK_WORD) {
769 if (substr($val,0,1) == "^")
770 $type = TSQ_TOK_STARTS_WITH;
771 elseif (substr($val,0,1) == "*")
772 $type = TSQ_TOK_ENDS_WITH;
773 elseif (substr($val,-1,1) == "*")
774 $type = TSQ_TOK_STARTS_WITH;
777 $tokens[] = array($type, $val);
782 function get($accept) {
783 if ($this->pos >= count($this->tokens))
786 list ($type, $val) = $this->tokens[$this->pos];
787 if (($type & $accept) == 0)
799 // c-hanging-comment-ender-p: nil
800 // indent-tabs-mode: nil