]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/TextSearchQuery.php
add case_exact search
[SourceForge/phpwiki.git] / lib / TextSearchQuery.php
1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.9 2004-11-23 13:35:31 rurban Exp $');
2 /**
3  * A text search query.
4  *
5  * This represents "Google-like" text search queries like:
6  * <dl>
7  * <dt> wiki -test
8  *   <dd> Match strings containing the substring 'wiki',  and not containing the
9  *        substring 'test'.
10  * <dt> wiki word or page
11  *   <dd> Match strings containing the substring 'wiki' and either the substring
12  *        'word' or the substring 'page'.
13  * </dl>
14  *
15  * The full query syntax, in order of precedence, is roughly:
16  *
17  * The unary 'NOT' or '-' operator (they are equivalent) negates the
18  * following search clause.
19  *
20  * Search clauses may be joined with the (left-associative) binary operators
21  * 'AND' and 'OR'.
22  *
23  * Two adjoining search clauses are joined with an implicit 'AND'.  This has
24  * lower precedence than either an explicit 'AND' or 'OR', so "a b OR c"
25  * parses as "a AND ( b OR c )", while "a AND b OR c" parses as
26  * "( a AND b ) OR c" (due to the left-associativity of 'AND' and 'OR'.)
27  *
28  * Search clauses can be grouped with parentheses.
29  *
30  * Phrases (or other things which don't look like words) can be forced to
31  * be interpreted as words by quoting them, either with single (') or double (")
32  * quotes.  If you wan't to include the quote character within a quoted string,
33  * double-up on the quote character: 'I''m hungry' is equivalent to
34  * "I'm hungry".
35  *
36  * FIXME: Clarify wildcards usage. none, glob-style, SQL-style, pcre-style, regex-style
37  * This only converts to PCRE, not to ANSI-SQL or other SQL functions.
38  * But see makeSqlClause().
39  *
40  * @author: Jeff Dairiki
41  */
42 class TextSearchQuery {
43     /**
44      * Create a new query.
45      *
46      * @param $search_query string The query.  Syntax is as described above.
47      * Note that an empty $search_query will match anything.
48      * @see TextSearchQuery
49      * TODO: support $regex arg
50      */
51     function TextSearchQuery($search_query, $case_exact=false, $regex=false) {
52         $parser = new TextSearchQuery_Parser;
53         $this->_tree = $parser->parse($search_query, $case_exact);
54         $this->_optimize();
55     }
56
57     function _optimize() {
58         $this->_tree = $this->_tree->optimize();
59     }
60
61     /**
62      * Get a regexp which matches the query.
63      */
64     function asRegexp() {
65         if (!isset($this->_regexp))
66             $this->_regexp =  '/^' . $this->_tree->regexp() . '/isS';
67         return $this->_regexp;
68     }
69
70     /**
71      * Match query against string.
72      *
73      * @param $string string The string to match. 
74      * @return boolean True if the string matches the query.
75      */
76     function match($string) {
77         return preg_match($this->asRegexp(), $string);
78     }
79
80     
81     /**
82      * Get a regular expression suitable for highlighting matched words.
83      *
84      * This returns a PCRE regular expression which matches any non-negated
85      * word in the query.
86      *
87      * @return string The PCRE regexp.
88      */
89     function getHighlightRegexp() {
90         if (!isset($this->_hilight_regexp)) {
91             $words = array_unique($this->_tree->highlight_words());
92             if (!$words) {
93                 $this->_hilight_regexp = false;
94             }
95             else {
96                 foreach ($words as $key => $word)
97                     $words[$key] = preg_quote($word, '/');
98                 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
99             }
100         }
101         return $this->_hilight_regexp;
102     }
103
104     /**
105      * Make an SQL clause which matches the query.
106      *
107      * @param $make_sql_clause_cb WikiCallback
108      * A callback which takes a single word as an argument and
109      * returns an SQL clause which will match exactly those records
110      * containing the word.  The word passed to the callback will always
111      * be in all lower case.
112      *
113      * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
114      *       mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
115      *       How? WikiDB backend method?
116      *       Case-sensitivity option.
117      *
118      * Example usage:
119      * <pre>
120      *     function sql_title_match($word) {
121      *         return sprintf("LOWER(title) like '%s'",
122      *                        addslashes($word));
123      *     }
124      *
125      *     ...
126      *
127      *     $query = new TextSearchQuery("wiki -page");
128      *     $cb = new WikiFunctionCb('sql_title_match');
129      *     $sql_clause = $query->makeSqlClause($cb);
130      * </pre>
131      * This will result in $sql_clause containing something like
132      * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
133      *
134      * @return string The PCRE regexp.
135      */
136     function makeSqlClause($make_sql_clause_cb) {
137         $this->_sql_clause_cb = $make_sql_clause_cb;
138         return $this->_sql_clause($this->_tree);
139     }
140
141     function _sql_clause($node) {
142         switch ($node->op) {
143         case 'WORD':
144             return $this->_sql_clause_cb->call($node->word);
145         case 'NOT':
146             return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
147         case 'AND':
148         case 'OR':
149             $subclauses = array();
150             foreach ($node->leaves as $leaf)
151                 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
152             return join(" $node->op ", $subclauses);
153         default:
154             assert($node->op == 'VOID');
155             return '1=1';
156         }
157     }
158
159     /**
160      * Get printable representation of the parse tree.
161      *
162      * This is for debugging only.
163      * @return string Printable parse tree.
164      */
165     function asString() {
166         return $this->_as_string($this->_tree);
167     }
168
169     function _as_string($node, $indent = '') {
170         switch ($node->op) {
171         case 'WORD':
172             return $indent . "WORD: $node->word";
173         case 'VOID':
174             return $indent . "VOID";
175         default:
176             $lines = array($indent . $node->op . ":");
177             $indent .= "  ";
178             foreach ($node->leaves as $leaf)
179                 $lines[] = $this->_as_string($leaf, $indent);
180             return join("\n", $lines);
181         }
182     }
183 }
184
185 /**
186  * This is a TextSearchQuery which matches nothing.
187  */
188 class NullTextSearchQuery extends TextSearchQuery {
189     /**
190      * Create a new query.
191      *
192      * @see TextSearchQuery
193      */
194     function NullTextSearchQuery() {}
195     function asRegexp()         { return '/^(?!a)a/x'; }
196     function match($string)     { return false; }
197     function getHighlightRegexp() { return ""; }
198     function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
199     function asString() { return "NullTextSearchQuery"; }
200 };
201
202
203 ////////////////////////////////////////////////////////////////
204 //
205 // Remaining classes are private.
206 //
207 ////////////////////////////////////////////////////////////////
208 /**
209  * Virtual base class for nodes in a TextSearchQuery parse tree.
210  *
211  * Also servers as a 'VOID' (contentless) node.
212  */
213 class TextSearchQuery_node
214 {
215     var $op = 'VOID';
216
217     /**
218      * Optimize this node.
219      * @return object Optimized node.
220      */
221     function optimize() {
222         return $this;
223     }
224
225     /**
226      * @return regexp matching this node.
227      */
228     function regexp() {
229         return '';
230     }
231
232     /**
233      * @param bool True if this node has been negated (higher in the parse tree.)
234      * @return array A list of all non-negated words contained by this node.
235      */
236     function highlight_words($negated = false) {
237         return array();
238     }
239 }
240
241 /**
242  * A word.
243  */
244 class TextSearchQuery_node_word
245 extends TextSearchQuery_node
246 {
247     var $op = "WORD";
248     
249     function TextSearchQuery_node_word($word) {
250         $this->word = $word;
251     }
252
253     function regexp() {
254         return '(?=.*' . preg_quote($this->word, '/') . ')';
255     }
256
257     function highlight_words($negated = false) {
258         return $negated ? array() : array($this->word);
259     }
260 }
261
262
263 /**
264  * A negated clause.
265  */
266 class TextSearchQuery_node_not
267 extends TextSearchQuery_node
268 {
269     var $op = "NOT";
270     
271     function TextSearchQuery_node_not($leaf) {
272         $this->leaves = array($leaf);
273     }
274
275     function optimize() {
276         $leaf = &$this->leaves[0];
277         $leaf = $leaf->optimize();
278         if ($leaf->op == 'NOT')
279             return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
280         return $this;
281     }
282     
283     function regexp() {
284         $leaf = &$this->leaves[0];
285         return '(?!' . $leaf->regexp() . ')';
286     }
287
288     function highlight_words($negated = false) {
289         return $this->leaves[0]->highlight_words(!$negated);
290     }
291 }
292
293 /**
294  * Virtual base class for 'AND' and 'OR conjoins.
295  */
296 class TextSearchQuery_node_binop
297 extends TextSearchQuery_node
298 {
299     function TextSearchQuery_node_binop($leaves) {
300         $this->leaves = $leaves;
301     }
302
303     function _flatten() {
304         // This flattens e.g. (AND (AND a b) (OR c d) e)
305         //        to (AND a b e (OR c d))
306         $flat = array();
307         foreach ($this->leaves as $leaf) {
308             $leaf = $leaf->optimize();
309             if ($this->op == $leaf->op)
310                 $flat = array_merge($flat, $leaf->leaves);
311             else
312                 $flat[] = $leaf;
313         }
314         $this->leaves = $flat;
315     }
316
317     function optimize() {
318         $this->_flatten();
319         assert(!empty($this->leaves));
320         if (count($this->leaves) == 1)
321             return $this->leaves[0]; // (AND x) -> x
322         return $this;
323     }
324
325     function highlight_words($negated = false) {
326         $words = array();
327         foreach ($this->leaves as $leaf)
328             array_splice($words,0,0,
329                          $leaf->highlight_words($negated));
330         return $words;
331     }
332 }
333
334 /**
335  * A (possibly multi-argument) 'AND' conjoin.
336  */
337 class TextSearchQuery_node_and
338 extends TextSearchQuery_node_binop
339 {
340     var $op = "AND";
341     
342     function optimize() {
343         $this->_flatten();
344
345         // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
346         // Since OR's are more efficient for regexp matching:
347         //   (?!.*a)(?!.*b)  vs   (?!.*(?:a|b))
348
349         // Suck out the negated leaves.
350         $nots = array();
351         foreach ($this->leaves as $key => $leaf) {
352             if ($leaf->op == 'NOT') {
353                 $nots[] = $leaf->leaves[0];
354                 unset($this->leaves[$key]);
355             }
356         }
357
358         // Combine the negated leaves into a single negated or.
359         if ($nots) {
360             $node = ( new TextSearchQuery_node_not
361                       (new TextSearchQuery_node_or($nots)) );
362             array_unshift($this->leaves, $node->optimize());
363         }
364         
365         assert(!empty($this->leaves));
366         if (count($this->leaves) == 1)
367             return $this->leaves[0];  // (AND x) -> x
368         return $this;
369     }
370
371     function regexp() {
372         $regexp = '';
373         foreach ($this->leaves as $leaf)
374             $regexp .= $leaf->regexp();
375         return $regexp;
376     }
377 }
378
379 /**
380  * A (possibly multi-argument) 'OR' conjoin.
381  */
382 class TextSearchQuery_node_or
383 extends TextSearchQuery_node_binop
384 {
385     var $op = "OR";
386
387     function regexp() {
388         // We will combine any of our direct descendents which are WORDs
389         // into a single (?=.*(?:word1|word2|...)) regexp.
390         
391         $regexps = array();
392         $words = array();
393
394         foreach ($this->leaves as $leaf) {
395             if ($leaf->op == 'WORD')
396                 $words[] = preg_quote($leaf->word, '/');
397             else
398                 $regexps[] = $leaf->regexp();
399         }
400
401         if ($words)
402             array_unshift($regexps,
403                           '(?=.*' . $this->_join($words) . ')');
404
405         return $this->_join($regexps);
406     }
407
408     function _join($regexps) {
409         assert(count($regexps) > 0);
410
411         if (count($regexps) > 1)
412             return '(?:' . join('|', $regexps) . ')';
413         else
414             return $regexps[0];
415     }
416 }
417
418
419 ////////////////////////////////////////////////////////////////
420 //
421 // Parser:
422 //
423 ////////////////////////////////////////////////////////////////
424 define ('TSQ_TOK_WORD',   1);
425 define ('TSQ_TOK_BINOP',  2);
426 define ('TSQ_TOK_NOT',    4);
427 define ('TSQ_TOK_LPAREN', 8);
428 define ('TSQ_TOK_RPAREN', 16);
429
430 class TextSearchQuery_Parser 
431 {
432     /*
433      * This is a simple recursive descent parser, based on the following grammar:
434      *
435      * toplist  :
436      *          | toplist expr
437      *          ;
438      *
439      *
440      * list     : expr
441      *          | list expr
442      *          ;
443      *
444      * expr     : atom
445      *          | expr BINOP atom
446      *          ;
447      *
448      * atom     : '(' list ')'
449      *          | NOT atom
450      *          | WORD
451      *          ;
452      *
453      * The terminal tokens are:
454      *
455      *
456      * and|or           BINOP
457      * -|not            NOT
458      * (                LPAREN
459      * )                RPAREN
460      * [^-()\s][^()\s]* WORD
461      * "[^"]*"          WORD
462      * '[^']*'          WORD
463      */
464
465     function parse ($search_expr, $case_exact=false) {
466         $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact);
467         $tree = $this->get_list('toplevel');
468         assert($this->lexer->eof());
469         unset($this->lexer);
470         return $tree;
471     }
472     
473     function get_list ($is_toplevel = false) {
474         $list = array();
475
476         // token types we'll accept as words (and thus expr's) for the
477         // purpose of error recovery:
478         $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
479         if ($is_toplevel)
480             $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
481         
482         while ( ($expr = $this->get_expr())
483                 || ($expr = $this->get_word($accept_as_words)) ) {
484             
485             $list[] = $expr;
486         }
487
488         if (!$list) {
489             if ($is_toplevel)
490                 return new TextSearchQuery_node;
491             else
492                 return false;
493         }
494         return new TextSearchQuery_node_and($list);
495     }
496
497     function get_expr () {
498         if ( !($expr = $this->get_atom()) )
499             return false;
500         
501         $savedpos = $this->lexer->tell();
502         while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
503             if ( ! ($right = $this->get_atom()) ) {
504                 break;
505             }
506             
507             if ($op == 'and')
508                 $expr = new TextSearchQuery_node_and(array($expr, $right));
509             else {
510                 assert($op == 'or');
511                 $expr = new TextSearchQuery_node_or(array($expr, $right));
512             }
513
514             $savedpos = $this->lexer->tell();
515         }
516         $this->lexer->seek($savedpos);
517
518         return $expr;
519     }
520     
521
522     function get_atom() {
523         if ($word = $this->get_word())
524             return $word;
525
526         $savedpos = $this->lexer->tell();
527         if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
528             if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
529                 return $list;
530         }
531         elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
532             if ( ($atom = $this->get_atom()) )
533                 return new TextSearchQuery_node_not($atom);
534         }
535         $this->lexer->seek($savedpos);
536         return false;
537     }
538
539     function get_word($accept = TSQ_TOK_WORD) {
540         if ( ($word = $this->lexer->get($accept)) )
541             return new TextSearchQuery_node_word($word);
542         return false;
543     }
544 }
545
546 class TextSearchQuery_Lexer {
547     function TextSearchQuery_Lexer ($query_str, $case_exact=false) {
548         $this->tokens = $this->tokenize($query_str, $case_exact);
549         $this->pos = 0;
550     }
551
552     function tell() {
553         return $this->pos;
554     }
555
556     function seek($pos) {
557         $this->pos = $pos;
558     }
559
560     function eof() {
561         return $this->pos == count($this->tokens);
562     }
563
564     function tokenize($string, $case_exact=false) {
565         $tokens = array();
566         $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
567         while (!empty($buf)) {
568             if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
569                 $val = strtolower($m[1]);
570                 $type = TSQ_TOK_BINOP;
571             }
572             elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
573                 $val = strtolower($m[1]);
574                 $type = TSQ_TOK_NOT;
575             }
576             elseif (preg_match('/^([()])\s*/', $buf, $m)) {
577                 $val = $m[1];
578                 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
579             }
580             elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
581                 $val = str_replace('""', '"', $m[1]);
582                 $type = TSQ_TOK_WORD;
583             }
584             elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
585                 $val = str_replace("''", "'", $m[1]);
586                 $type = TSQ_TOK_WORD;
587             }
588             elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
589                 $val = $m[1];
590                 $type = TSQ_TOK_WORD;
591             }
592             else {
593                 assert(empty($buf));
594                 break;
595             }
596             $buf = substr($buf, strlen($m[0]));
597             $tokens[] = array($type, $val);
598         }
599         return $tokens;
600     }
601     
602     function get($accept) {
603         if ($this->pos >= count($this->tokens))
604             return false;
605         
606         list ($type, $val) = $this->tokens[$this->pos];
607         if (($type & $accept) == 0)
608             return false;
609         
610         $this->pos++;
611         return $val;
612     }
613 }
614
615 // Local Variables:
616 // mode: php
617 // tab-width: 8
618 // c-basic-offset: 4
619 // c-hanging-comment-ender-p: nil
620 // indent-tabs-mode: nil
621 // End:   
622 ?>