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