1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.12 2004-11-27 14:39:04 rurban Exp $');
3 * A text search query, converting queries to PCRE or 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> detects regex hints, glob-style or regex-style, and converts them to PCRE or SQL matchers
15 * <dd> "^word$" => EXACT(word)
16 * <dd> "^word" => STARTS_WITH(word)
17 * <dd> "word*" => STARTS_WITH(word)
18 * <dd> "*word" => ENDS_WITH(word)
19 * <dd> "/^word.* /" => REGEX(^word.*)
20 * <dd> "word*word" => REGEX(word.*word)
23 * The full query syntax, in order of precedence, is roughly:
25 * The unary 'NOT' or '-' operator (they are equivalent) negates the
26 * following search clause.
28 * Search clauses may be joined with the (left-associative) binary operators
31 * Two adjoining search clauses are joined with an implicit 'AND'. This has
32 * lower precedence than either an explicit 'AND' or 'OR', so "a b OR c"
33 * parses as "a AND ( b OR c )", while "a AND b OR c" parses as
34 * "( a AND b ) OR c" (due to the left-associativity of 'AND' and 'OR'.)
36 * Search clauses can be grouped with parentheses.
38 * Phrases (or other things which don't look like words) can be forced to
39 * be interpreted as words by quoting them, either with single (') or double (")
40 * quotes. If you wan't to include the quote character within a quoted string,
41 * double-up on the quote character: 'I''m hungry' is equivalent to
44 * Force regex on "re:word" => posix-style, "/word/" => pcre-style
45 * or use regex='glob' to use file wildcard-like matching. (not yet)
47 * The parsed tree is then converted to the needed PCRE (highlight, simple backends)
50 * @author: Jeff Dairiki
51 * @author: Reini Urban (case and regex detection, enhanced sql callbacks)
54 // regex-style: 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
55 define ('TSQ_REGEX_NONE', 0);
56 define ('TSQ_REGEX_AUTO', 1);
57 define ('TSQ_REGEX_POSIX', 2);
58 define ('TSQ_REGEX_GLOB', 4);
59 define ('TSQ_REGEX_PCRE', 8);
60 define ('TSQ_REGEX_SQL', 16);
62 class TextSearchQuery {
66 * @param $search_query string The query. Syntax is as described above.
67 * Note that an empty $search_query will match anything.
68 * @param $case_exact boolean
69 * @param $regex string one of 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
70 * @see TextSearchQuery
72 function TextSearchQuery($search_query, $case_exact=false, $regex='auto') {
73 if ($regex == 'none' or !$regex)
75 elseif (defined("TSQ_REGEX_".strtoupper($regex)))
76 $this->_regex = constant("TSQ_REGEX_".strtoupper($regex));
78 trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex));
81 $this->_case_exact = $case_exact;
82 $parser = new TextSearchQuery_Parser;
83 $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex);
87 function _optimize() {
88 $this->_tree = $this->_tree->optimize();
92 * Get a PCRE regexp which matches the query.
95 if (!isset($this->_regexp)) {
97 $this->_regexp = '/' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
99 $this->_regexp = '/^' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
101 return $this->_regexp;
105 * Match query against string.
107 * @param $string string The string to match.
108 * @return boolean True if the string matches the query.
110 function match($string) {
111 return preg_match($this->asRegexp(), $string);
116 * Get a regular expression suitable for highlighting matched words.
118 * This returns a PCRE regular expression which matches any non-negated
121 * @return string The PCRE regexp.
123 function getHighlightRegexp() {
124 if (!isset($this->_hilight_regexp)) {
125 $words = array_unique($this->_tree->highlight_words());
127 $this->_hilight_regexp = false;
129 foreach ($words as $key => $word)
130 $words[$key] = preg_quote($word, '/');
131 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
134 return $this->_hilight_regexp;
138 * Make an SQL clause which matches the query. (deprecated, use makeSqlClause instead)
140 * @param $make_sql_clause_cb WikiCallback
141 * A callback which takes a single word as an argument and
142 * returns an SQL clause which will match exactly those records
143 * containing the word. The word passed to the callback will always
144 * be in all lower case.
146 * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
147 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
148 * How? WikiDB backend method?
152 * function sql_title_match($word) {
153 * return sprintf("LOWER(title) like '%s'",
154 * addslashes($word));
159 * $query = new TextSearchQuery("wiki -page");
160 * $cb = new WikiFunctionCb('sql_title_match');
161 * $sql_clause = $query->makeSqlClause($cb);
163 * This will result in $sql_clause containing something like
164 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
166 * @return string The SQL clause.
168 function makeSqlClause($sql_clause_cb) {
169 $this->_sql_clause_cb = $sql_clause_cb;
170 return $this->_sql_clause($this->_tree);
172 // deprecated: use _sql_clause_obj now.
173 function _sql_clause($node) {
175 case 'WORD': // word => %word%
176 return $this->_sql_clause_cb->call($node->word);
178 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
181 $subclauses = array();
182 foreach ($node->leaves as $leaf)
183 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
184 return join(" $node->op ", $subclauses);
186 assert($node->op == VOID);
191 /** Get away with the callback and use a db-specific search class instead.
192 * @see WikiDB_backend_PearDB_search
194 function makeSqlClauseObj(&$sql_search_cb) {
195 $this->_sql_clause_cb = $sql_search_cb;
196 return $this->_sql_clause_obj($this->_tree);
199 function _sql_clause_obj($node) {
202 return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
205 $subclauses = array();
206 foreach ($node->leaves as $leaf)
207 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
208 return join(" $node->op ", $subclauses);
212 return $this->_sql_clause_cb->call($node);
217 * Get printable representation of the parse tree.
219 * This is for debugging only.
220 * @return string Printable parse tree.
222 function asString() {
223 return $this->_as_string($this->_tree);
226 function _as_string($node, $indent = '') {
229 return $indent . "WORD: $node->word";
231 return $indent . "VOID";
233 $lines = array($indent . $node->op . ":");
235 foreach ($node->leaves as $leaf)
236 $lines[] = $this->_as_string($leaf, $indent);
237 return join("\n", $lines);
243 * This is a TextSearchQuery which matches nothing.
245 class NullTextSearchQuery extends TextSearchQuery {
247 * Create a new query.
249 * @see TextSearchQuery
251 function NullTextSearchQuery() {}
252 function asRegexp() { return '/^(?!a)a/x'; }
253 function match($string) { return false; }
254 function getHighlightRegexp() { return ""; }
255 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
256 function asString() { return "NullTextSearchQuery"; }
260 ////////////////////////////////////////////////////////////////
262 // Remaining classes are private.
264 ////////////////////////////////////////////////////////////////
266 * Virtual base class for nodes in a TextSearchQuery parse tree.
268 * Also servers as a 'VOID' (contentless) node.
270 class TextSearchQuery_node
275 * Optimize this node.
276 * @return object Optimized node.
278 function optimize() {
283 * @return regexp matching this node.
290 * @param bool True if this node has been negated (higher in the parse tree.)
291 * @return array A list of all non-negated words contained by this node.
293 function highlight_words($negated = false) {
301 class TextSearchQuery_node_word
302 extends TextSearchQuery_node
306 function TextSearchQuery_node_word($word) {
310 return '(?=.*' . preg_quote($this->word, '/') . ')';
312 function highlight_words($negated = false) {
313 return $negated ? array() : array($this->word);
315 function _sql_quote() {
316 $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
317 return $GLOBALS['request']->_dbi->qstr($word);
319 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
322 class TextSearchQuery_node_starts_with
323 extends TextSearchQuery_node_word {
324 var $op = "STARTS_WITH";
325 function regexp() { return '(?=' . preg_quote($this->word, '/') . ')'; }
326 function sql() { return $this->_sql_quote($this->word).'%'; }
329 class TextSearchQuery_node_ends_with
330 extends TextSearchQuery_node_word {
331 var $op = "ENDS_WITH";
332 function regexp() { return '(?=' . preg_quote($this->word, '/') . '.*)'; }
333 function sql() { return '%'.$this->_sql_quote($this->word); }
336 class TextSearchQuery_node_exact
337 extends TextSearchQuery_node_word {
339 function regexp() { return '(?=\B' . preg_quote($this->word, '/') . '\b)'; }
340 function sql() { return $this->_sql_squote($this->word); }
343 class TextSearchQuery_node_regex // posix regex. FIXME!
344 extends TextSearchQuery_node_word {
345 var $op = "REGEX"; // using REGEXP or ~ extension
346 function regexp() { return '(?=\B' . $this->word . '\b)'; }
347 function sql() { return $this->_sql_quote($this->word); }
350 class TextSearchQuery_node_regex_glob
351 extends TextSearchQuery_node_regex {
352 var $op = "REGEX_GLOB";
353 function regexp() { return '(?=\B' . glob_to_pcre($this->word) . '\b)'; }
356 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
357 extends TextSearchQuery_node_regex {
358 var $op = "REGEX_PCRE";
359 function regexp() { return $this->word; }
362 class TextSearchQuery_node_regex_sql
363 extends TextSearchQuery_node_regex {
364 var $op = "REGEX_SQL"; // using LIKE
365 function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
366 function sql() { return $this->word; }
372 class TextSearchQuery_node_not
373 extends TextSearchQuery_node
377 function TextSearchQuery_node_not($leaf) {
378 $this->leaves = array($leaf);
381 function optimize() {
382 $leaf = &$this->leaves[0];
383 $leaf = $leaf->optimize();
384 if ($leaf->op == 'NOT')
385 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
390 $leaf = &$this->leaves[0];
391 return '(?!' . $leaf->regexp() . ')';
394 function highlight_words($negated = false) {
395 return $this->leaves[0]->highlight_words(!$negated);
400 * Virtual base class for 'AND' and 'OR conjoins.
402 class TextSearchQuery_node_binop
403 extends TextSearchQuery_node
405 function TextSearchQuery_node_binop($leaves) {
406 $this->leaves = $leaves;
409 function _flatten() {
410 // This flattens e.g. (AND (AND a b) (OR c d) e)
411 // to (AND a b e (OR c d))
413 foreach ($this->leaves as $leaf) {
414 $leaf = $leaf->optimize();
415 if ($this->op == $leaf->op)
416 $flat = array_merge($flat, $leaf->leaves);
420 $this->leaves = $flat;
423 function optimize() {
425 assert(!empty($this->leaves));
426 if (count($this->leaves) == 1)
427 return $this->leaves[0]; // (AND x) -> x
431 function highlight_words($negated = false) {
433 foreach ($this->leaves as $leaf)
434 array_splice($words,0,0,
435 $leaf->highlight_words($negated));
441 * A (possibly multi-argument) 'AND' conjoin.
443 class TextSearchQuery_node_and
444 extends TextSearchQuery_node_binop
448 function optimize() {
451 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
452 // Since OR's are more efficient for regexp matching:
453 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
455 // Suck out the negated leaves.
457 foreach ($this->leaves as $key => $leaf) {
458 if ($leaf->op == 'NOT') {
459 $nots[] = $leaf->leaves[0];
460 unset($this->leaves[$key]);
464 // Combine the negated leaves into a single negated or.
466 $node = ( new TextSearchQuery_node_not
467 (new TextSearchQuery_node_or($nots)) );
468 array_unshift($this->leaves, $node->optimize());
471 assert(!empty($this->leaves));
472 if (count($this->leaves) == 1)
473 return $this->leaves[0]; // (AND x) -> x
479 foreach ($this->leaves as $leaf)
480 $regexp .= $leaf->regexp();
486 * A (possibly multi-argument) 'OR' conjoin.
488 class TextSearchQuery_node_or
489 extends TextSearchQuery_node_binop
494 // We will combine any of our direct descendents which are WORDs
495 // into a single (?=.*(?:word1|word2|...)) regexp.
500 foreach ($this->leaves as $leaf) {
501 if ($leaf->op == 'WORD')
502 $words[] = preg_quote($leaf->word, '/');
504 $regexps[] = $leaf->regexp();
508 array_unshift($regexps,
509 '(?=.*' . $this->_join($words) . ')');
511 return $this->_join($regexps);
514 function _join($regexps) {
515 assert(count($regexps) > 0);
517 if (count($regexps) > 1)
518 return '(?:' . join('|', $regexps) . ')';
525 ////////////////////////////////////////////////////////////////
528 // op's (and, or, not) are forced to lowercase in the tokenizer.
530 ////////////////////////////////////////////////////////////////
531 define ('TSQ_TOK_BINOP', 1);
532 define ('TSQ_TOK_NOT', 2);
533 define ('TSQ_TOK_LPAREN', 4);
534 define ('TSQ_TOK_RPAREN', 8);
535 define ('TSQ_TOK_WORD', 16);
536 define ('TSQ_TOK_STARTS_WITH', 32);
537 define ('TSQ_TOK_ENDS_WITH', 64);
538 define ('TSQ_TOK_EXACT', 128);
539 define ('TSQ_TOK_REGEX', 256);
540 define ('TSQ_TOK_REGEX_GLOB', 512);
541 define ('TSQ_TOK_REGEX_PCRE', 1024);
542 define ('TSQ_TOK_REGEX_SQL', 2048);
543 // all bits from word to the last.
544 define ('TSQ_ALLWORDS', (2048*2)-1 - (16-1));
546 class TextSearchQuery_Parser
549 * This is a simple recursive descent parser, based on the following grammar:
564 * atom : '(' list ')'
569 * The terminal tokens are:
576 * /[^-()\s][^()\s]* WORD
586 function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
587 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
588 $this->_regex = $regex;
589 $tree = $this->get_list('toplevel');
590 assert($this->lexer->eof());
595 function get_list ($is_toplevel = false) {
598 // token types we'll accept as words (and thus expr's) for the
599 // purpose of error recovery:
600 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
602 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
604 while ( ($expr = $this->get_expr())
605 || ($expr = $this->get_word($accept_as_words)) ) {
611 return new TextSearchQuery_node;
615 return new TextSearchQuery_node_and($list);
618 function get_expr () {
619 if ( !($expr = $this->get_atom()) )
622 $savedpos = $this->lexer->tell();
623 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
624 if ( ! ($right = $this->get_atom()) ) {
629 $expr = new TextSearchQuery_node_and(array($expr, $right));
632 $expr = new TextSearchQuery_node_or(array($expr, $right));
635 $savedpos = $this->lexer->tell();
637 $this->lexer->seek($savedpos);
643 function get_atom() {
644 if ($word = $this->get_word(TSQ_ALLWORDS))
647 $savedpos = $this->lexer->tell();
648 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
649 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
652 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
653 if ( ($atom = $this->get_atom()) )
654 return new TextSearchQuery_node_not($atom);
656 $this->lexer->seek($savedpos);
660 function get_word($accept = TSQ_ALLWORDS) {
661 foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
662 "REGEX","REGEX_GLOB","REGEX_PCRE") as $tok) {
663 $const = constant("TSQ_TOK_".$tok);
664 if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
665 $classname = "TextSearchQuery_node_".strtolower($tok);
666 return new $classname($word);
673 class TextSearchQuery_Lexer {
674 function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
675 $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
683 function seek($pos) {
688 return $this->pos == count($this->tokens);
692 * TODO: support more regex styles, esp. prefer the forced ones over auto
695 function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
697 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
698 while (!empty($buf)) {
699 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
700 $val = strtolower($m[1]);
701 $type = TSQ_TOK_BINOP;
703 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
704 $val = strtolower($m[1]);
707 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
709 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
712 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
713 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
715 $type = TSQ_TOK_STARTS_WITH;
718 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
719 and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
721 $type = TSQ_TOK_STARTS_WITH;
724 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
725 and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
727 $type = TSQ_TOK_ENDS_WITH;
730 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
731 and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
733 $type = TSQ_TOK_EXACT;
736 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
737 $val = str_replace('""', '"', $m[1]);
738 $type = TSQ_TOK_WORD;
741 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
742 $val = str_replace("''", "'", $m[1]);
743 $type = TSQ_TOK_WORD;
746 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
748 $type = TSQ_TOK_WORD;
754 $buf = substr($buf, strlen($m[0]));
756 /* refine the simple parsing from above: bla*bla, bla?bla, ...
757 if ($regex and $type == TSQ_TOK_WORD) {
758 if (substr($val,0,1) == "^")
759 $type = TSQ_TOK_STARTS_WITH;
760 elseif (substr($val,0,1) == "*")
761 $type = TSQ_TOK_ENDS_WITH;
762 elseif (substr($val,-1,1) == "*")
763 $type = TSQ_TOK_STARTS_WITH;
766 $tokens[] = array($type, $val);
771 function get($accept) {
772 if ($this->pos >= count($this->tokens))
775 list ($type, $val) = $this->tokens[$this->pos];
776 if (($type & $accept) == 0)
788 // c-hanging-comment-ender-p: nil
789 // indent-tabs-mode: nil