1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.13 2004-11-28 20:42:18 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> auto-detect regex hints, glob-style or regex-style, and converts them
15 * to PCRE or 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
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, simple backends)
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);
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);
218 * Get printable representation of the parse tree.
220 * This is for debugging only.
221 * @return string Printable parse tree.
223 function asString() {
224 return $this->_as_string($this->_tree);
227 function _as_string($node, $indent = '') {
230 return $indent . "WORD: $node->word";
232 return $indent . "VOID";
234 $lines = array($indent . $node->op . ":");
236 foreach ($node->leaves as $leaf)
237 $lines[] = $this->_as_string($leaf, $indent);
238 return join("\n", $lines);
244 * This is a TextSearchQuery which matches nothing.
246 class NullTextSearchQuery extends TextSearchQuery {
248 * Create a new query.
250 * @see TextSearchQuery
252 function NullTextSearchQuery() {}
253 function asRegexp() { return '/^(?!a)a/x'; }
254 function match($string) { return false; }
255 function getHighlightRegexp() { return ""; }
256 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
257 function asString() { return "NullTextSearchQuery"; }
261 ////////////////////////////////////////////////////////////////
263 // Remaining classes are private.
265 ////////////////////////////////////////////////////////////////
267 * Virtual base class for nodes in a TextSearchQuery parse tree.
269 * Also servers as a 'VOID' (contentless) node.
271 class TextSearchQuery_node
276 * Optimize this node.
277 * @return object Optimized node.
279 function optimize() {
284 * @return regexp matching this node.
291 * @param bool True if this node has been negated (higher in the parse tree.)
292 * @return array A list of all non-negated words contained by this node.
294 function highlight_words($negated = false) {
302 class TextSearchQuery_node_word
303 extends TextSearchQuery_node
307 function TextSearchQuery_node_word($word) {
311 return '(?=.*' . preg_quote($this->word, '/') . ')';
313 function highlight_words($negated = false) {
314 return $negated ? array() : array($this->word);
316 function _sql_quote() {
317 $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
318 return $GLOBALS['request']->_dbi->qstr($word);
320 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
323 class TextSearchQuery_node_starts_with
324 extends TextSearchQuery_node_word {
325 var $op = "STARTS_WITH";
326 function regexp() { return '(?=' . preg_quote($this->word, '/') . ')'; }
327 function sql() { return $this->_sql_quote($this->word).'%'; }
330 class TextSearchQuery_node_ends_with
331 extends TextSearchQuery_node_word {
332 var $op = "ENDS_WITH";
333 function regexp() { return '(?=' . preg_quote($this->word, '/') . '.*)'; }
334 function sql() { return '%'.$this->_sql_quote($this->word); }
337 class TextSearchQuery_node_exact
338 extends TextSearchQuery_node_word {
340 function regexp() { return '(?=\B' . preg_quote($this->word, '/') . '\b)'; }
341 function sql() { return $this->_sql_squote($this->word); }
344 class TextSearchQuery_node_regex // posix regex. FIXME!
345 extends TextSearchQuery_node_word {
346 var $op = "REGEX"; // using REGEXP or ~ extension
347 function regexp() { return '(?=\B' . $this->word . '\b)'; }
348 function sql() { return $this->_sql_quote($this->word); }
351 class TextSearchQuery_node_regex_glob
352 extends TextSearchQuery_node_regex {
353 var $op = "REGEX_GLOB";
354 function regexp() { return '(?=\B' . glob_to_pcre($this->word) . '\b)'; }
357 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
358 extends TextSearchQuery_node_regex {
359 var $op = "REGEX_PCRE";
360 function regexp() { return $this->word; }
363 class TextSearchQuery_node_regex_sql
364 extends TextSearchQuery_node_regex {
365 var $op = "REGEX_SQL"; // using LIKE
366 function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
367 function sql() { return $this->word; }
373 class TextSearchQuery_node_not
374 extends TextSearchQuery_node
378 function TextSearchQuery_node_not($leaf) {
379 $this->leaves = array($leaf);
382 function optimize() {
383 $leaf = &$this->leaves[0];
384 $leaf = $leaf->optimize();
385 if ($leaf->op == 'NOT')
386 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
391 $leaf = &$this->leaves[0];
392 return '(?!' . $leaf->regexp() . ')';
395 function highlight_words($negated = false) {
396 return $this->leaves[0]->highlight_words(!$negated);
401 * Virtual base class for 'AND' and 'OR conjoins.
403 class TextSearchQuery_node_binop
404 extends TextSearchQuery_node
406 function TextSearchQuery_node_binop($leaves) {
407 $this->leaves = $leaves;
410 function _flatten() {
411 // This flattens e.g. (AND (AND a b) (OR c d) e)
412 // to (AND a b e (OR c d))
414 foreach ($this->leaves as $leaf) {
415 $leaf = $leaf->optimize();
416 if ($this->op == $leaf->op)
417 $flat = array_merge($flat, $leaf->leaves);
421 $this->leaves = $flat;
424 function optimize() {
426 assert(!empty($this->leaves));
427 if (count($this->leaves) == 1)
428 return $this->leaves[0]; // (AND x) -> x
432 function highlight_words($negated = false) {
434 foreach ($this->leaves as $leaf)
435 array_splice($words,0,0,
436 $leaf->highlight_words($negated));
442 * A (possibly multi-argument) 'AND' conjoin.
444 class TextSearchQuery_node_and
445 extends TextSearchQuery_node_binop
449 function optimize() {
452 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
453 // Since OR's are more efficient for regexp matching:
454 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
456 // Suck out the negated leaves.
458 foreach ($this->leaves as $key => $leaf) {
459 if ($leaf->op == 'NOT') {
460 $nots[] = $leaf->leaves[0];
461 unset($this->leaves[$key]);
465 // Combine the negated leaves into a single negated or.
467 $node = ( new TextSearchQuery_node_not
468 (new TextSearchQuery_node_or($nots)) );
469 array_unshift($this->leaves, $node->optimize());
472 assert(!empty($this->leaves));
473 if (count($this->leaves) == 1)
474 return $this->leaves[0]; // (AND x) -> x
480 foreach ($this->leaves as $leaf)
481 $regexp .= $leaf->regexp();
487 * A (possibly multi-argument) 'OR' conjoin.
489 class TextSearchQuery_node_or
490 extends TextSearchQuery_node_binop
495 // We will combine any of our direct descendents which are WORDs
496 // into a single (?=.*(?:word1|word2|...)) regexp.
501 foreach ($this->leaves as $leaf) {
502 if ($leaf->op == 'WORD')
503 $words[] = preg_quote($leaf->word, '/');
505 $regexps[] = $leaf->regexp();
509 array_unshift($regexps,
510 '(?=.*' . $this->_join($words) . ')');
512 return $this->_join($regexps);
515 function _join($regexps) {
516 assert(count($regexps) > 0);
518 if (count($regexps) > 1)
519 return '(?:' . join('|', $regexps) . ')';
526 ////////////////////////////////////////////////////////////////
529 // op's (and, or, not) are forced to lowercase in the tokenizer.
531 ////////////////////////////////////////////////////////////////
532 define ('TSQ_TOK_BINOP', 1);
533 define ('TSQ_TOK_NOT', 2);
534 define ('TSQ_TOK_LPAREN', 4);
535 define ('TSQ_TOK_RPAREN', 8);
536 define ('TSQ_TOK_WORD', 16);
537 define ('TSQ_TOK_STARTS_WITH', 32);
538 define ('TSQ_TOK_ENDS_WITH', 64);
539 define ('TSQ_TOK_EXACT', 128);
540 define ('TSQ_TOK_REGEX', 256);
541 define ('TSQ_TOK_REGEX_GLOB', 512);
542 define ('TSQ_TOK_REGEX_PCRE', 1024);
543 define ('TSQ_TOK_REGEX_SQL', 2048);
544 // all bits from word to the last.
545 define ('TSQ_ALLWORDS', (2048*2)-1 - (16-1));
547 class TextSearchQuery_Parser
550 * This is a simple recursive descent parser, based on the following grammar:
565 * atom : '(' list ')'
570 * The terminal tokens are:
577 * /[^-()\s][^()\s]* WORD
587 function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
588 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
589 $this->_regex = $regex;
590 $tree = $this->get_list('toplevel');
591 assert($this->lexer->eof());
596 function get_list ($is_toplevel = false) {
599 // token types we'll accept as words (and thus expr's) for the
600 // purpose of error recovery:
601 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
603 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
605 while ( ($expr = $this->get_expr())
606 || ($expr = $this->get_word($accept_as_words)) ) {
612 return new TextSearchQuery_node;
616 return new TextSearchQuery_node_and($list);
619 function get_expr () {
620 if ( !($expr = $this->get_atom()) )
623 $savedpos = $this->lexer->tell();
624 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
625 if ( ! ($right = $this->get_atom()) ) {
630 $expr = new TextSearchQuery_node_and(array($expr, $right));
633 $expr = new TextSearchQuery_node_or(array($expr, $right));
636 $savedpos = $this->lexer->tell();
638 $this->lexer->seek($savedpos);
644 function get_atom() {
645 if ($word = $this->get_word(TSQ_ALLWORDS))
648 $savedpos = $this->lexer->tell();
649 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
650 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
653 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
654 if ( ($atom = $this->get_atom()) )
655 return new TextSearchQuery_node_not($atom);
657 $this->lexer->seek($savedpos);
661 function get_word($accept = TSQ_ALLWORDS) {
662 foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
663 "REGEX","REGEX_GLOB","REGEX_PCRE") as $tok) {
664 $const = constant("TSQ_TOK_".$tok);
665 if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
666 $classname = "TextSearchQuery_node_".strtolower($tok);
667 return new $classname($word);
674 class TextSearchQuery_Lexer {
675 function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
676 $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
684 function seek($pos) {
689 return $this->pos == count($this->tokens);
693 * TODO: support more regex styles, esp. prefer the forced ones over auto
696 function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
698 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
699 while (!empty($buf)) {
700 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
701 $val = strtolower($m[1]);
702 $type = TSQ_TOK_BINOP;
704 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
705 $val = strtolower($m[1]);
708 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
710 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
713 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
714 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
716 $type = TSQ_TOK_STARTS_WITH;
719 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
720 and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
722 $type = TSQ_TOK_STARTS_WITH;
725 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
726 and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
728 $type = TSQ_TOK_ENDS_WITH;
731 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
732 and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
734 $type = TSQ_TOK_EXACT;
737 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
738 $val = str_replace('""', '"', $m[1]);
739 $type = TSQ_TOK_WORD;
742 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
743 $val = str_replace("''", "'", $m[1]);
744 $type = TSQ_TOK_WORD;
747 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
749 $type = TSQ_TOK_WORD;
755 $buf = substr($buf, strlen($m[0]));
757 /* refine the simple parsing from above: bla*bla, bla?bla, ...
758 if ($regex and $type == TSQ_TOK_WORD) {
759 if (substr($val,0,1) == "^")
760 $type = TSQ_TOK_STARTS_WITH;
761 elseif (substr($val,0,1) == "*")
762 $type = TSQ_TOK_ENDS_WITH;
763 elseif (substr($val,-1,1) == "*")
764 $type = TSQ_TOK_STARTS_WITH;
767 $tokens[] = array($type, $val);
772 function get($accept) {
773 if ($this->pos >= count($this->tokens))
776 list ($type, $val) = $this->tokens[$this->pos];
777 if (($type & $accept) == 0)
789 // c-hanging-comment-ender-p: nil
790 // indent-tabs-mode: nil