]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/TextSearchQuery.php
Change argument semantics for TextSearchQuery::makeSqlClause.
[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 ////////////////////////////////////////////////////////////////
175 //
176 // Remaining classes are private.
177 //
178 ////////////////////////////////////////////////////////////////
179 /**
180  * Virtual base class for nodes in a TextSearchQuery parse tree.
181  *
182  * Also servers as a 'VOID' (contentless) node.
183  */
184 class TextSearchQuery_node
185 {
186     var $op = 'VOID';
187
188     /**
189      * Optimize this node.
190      * @return object Optimized node.
191      */
192     function optimize() {
193         return $this;
194     }
195
196     /**
197      * @return regexp matching this node.
198      */
199     function regexp() {
200         return '';
201     }
202
203     /**
204      * @param bool True if this node has been negated (higher in the parse tree.)
205      * @return array A list of all non-negated words contained by this node.
206      */
207     function highlight_words($negated = false) {
208         return array();
209     }
210 }
211
212 /**
213  * A word.
214  */
215 class TextSearchQuery_node_word
216 extends TextSearchQuery_node
217 {
218     var $op = "WORD";
219     
220     function TextSearchQuery_node_word($word) {
221         $this->word = $word;
222     }
223
224     function regexp() {
225         return '(?=.*' . preg_quote($this->word, '/') . ')';
226     }
227
228     function highlight_words($negated = false) {
229         return $negated ? array() : array($this->word);
230     }
231 }
232
233
234 /**
235  * A negated clause.
236  */
237 class TextSearchQuery_node_not
238 extends TextSearchQuery_node
239 {
240     var $op = "NOT";
241     
242     function TextSearchQuery_node_not($leaf) {
243         $this->leaves = array($leaf);
244     }
245
246     function optimize() {
247         $leaf = &$this->leaves[0];
248         $leaf = $leaf->optimize();
249         if ($leaf->op == 'NOT')
250             return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
251         return $this;
252     }
253     
254     function regexp() {
255         $leaf = &$this->leaves[0];
256         return '(?!' . $leaf->regexp() . ')';
257     }
258
259     function highlight_words($negated = false) {
260         return $this->leaves[0]->highlight_words(!$negated);
261     }
262 }
263
264 /**
265  * Virtual base class for 'AND' and 'OR conjoins.
266  */
267 class TextSearchQuery_node_binop
268 extends TextSearchQuery_node
269 {
270     function TextSearchQuery_node_binop($leaves) {
271         $this->leaves = $leaves;
272     }
273
274     function _flatten() {
275         // This flattens e.g. (AND (AND a b) (OR c d) e)
276         //        to (AND a b e (OR c d))
277         $flat = array();
278         foreach ($this->leaves as $leaf) {
279             $leaf = $leaf->optimize();
280             if ($this->op == $leaf->op)
281                 $flat = array_merge($flat, $leaf->leaves);
282             else
283                 $flat[] = $leaf;
284         }
285         $this->leaves = $flat;
286     }
287
288     function optimize() {
289         $this->_flatten();
290         assert(!empty($this->leaves));
291         if (count($this->leaves) == 1)
292             return $this->leaves[0]; // (AND x) -> x
293         return $this;
294     }
295
296     function highlight_words($negated = false) {
297         $words = array();
298         foreach ($this->leaves as $leaf)
299             array_splice($words,0,0,
300                          $leaf->highlight_words($negated));
301         return $words;
302     }
303 }
304
305 /**
306  * A (possibly multi-argument) 'AND' conjoin.
307  */
308 class TextSearchQuery_node_and
309 extends TextSearchQuery_node_binop
310 {
311     var $op = "AND";
312     
313     function optimize() {
314         $this->_flatten();
315
316         // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
317         // Since OR's are more efficient for regexp matching:
318         //   (?!.*a)(?!.*b)  vs   (?!.*(?:a|b))
319
320         // Suck out the negated leaves.
321         $nots = array();
322         foreach ($this->leaves as $key => $leaf) {
323             if ($leaf->op == 'NOT') {
324                 $nots[] = $leaf->leaves[0];
325                 unset($this->leaves[$key]);
326             }
327         }
328
329         // Combine the negated leaves into a single negated or.
330         if ($nots) {
331             $node = ( new TextSearchQuery_node_not
332                       (new TextSearchQuery_node_or($nots)) );
333             array_unshift($this->leaves, $node->optimize());
334         }
335         
336         assert(!empty($this->leaves));
337         if (count($this->leaves) == 1)
338             return $this->leaves[0];  // (AND x) -> x
339         return $this;
340     }
341
342     function regexp() {
343         $regexp = '';
344         foreach ($this->leaves as $leaf)
345             $regexp .= $leaf->regexp();
346         return $regexp;
347     }
348 }
349
350 /**
351  * A (possibly multi-argument) 'OR' conjoin.
352  */
353 class TextSearchQuery_node_or
354 extends TextSearchQuery_node_binop
355 {
356     var $op = "OR";
357
358     function regexp() {
359         // We will combine any of our direct descendents which are WORDs
360         // into a single (?=.*(?:word1|word2|...)) regexp.
361         
362         $regexps = array();
363         $words = array();
364
365         foreach ($this->leaves as $leaf) {
366             if ($leaf->op == 'WORD')
367                 $words[] = preg_quote($leaf->word, '/');
368             else
369                 $regexps[] = $leaf->regexp();
370         }
371
372         if ($words)
373             array_unshift($regexps,
374                           '(?=.*' . $this->_join($words) . ')');
375
376         return $this->_join($regexps);
377     }
378
379     function _join($regexps) {
380         assert(count($regexps) > 0);
381
382         if (count($regexps) > 1)
383             return '(?:' . join('|', $regexps) . ')';
384         else
385             return $regexps[0];
386     }
387 }
388
389
390 ////////////////////////////////////////////////////////////////
391 //
392 // Parser:
393 //
394 ////////////////////////////////////////////////////////////////
395 define ('TSQ_TOK_WORD',   1);
396 define ('TSQ_TOK_BINOP',  2);
397 define ('TSQ_TOK_NOT',    4);
398 define ('TSQ_TOK_LPAREN', 8);
399 define ('TSQ_TOK_RPAREN', 16);
400
401 class TextSearchQuery_Parser 
402 {
403     /*
404      * This is a simple recursive descent parser, based on the following grammar:
405      *
406      * toplist  :
407      *          | toplist expr
408      *          ;
409      *
410      *
411      * list     : expr
412      *          | list expr
413      *          ;
414      *
415      * expr     : atom
416      *          | expr BINOP atom
417      *          ;
418      *
419      * atom     : '(' list ')'
420      *          | NOT atom
421      *          | WORD
422      *          ;
423      *
424      * The terminal tokens are:
425      *
426      *
427      * and|or           BINOP
428      * -|not            NOT
429      * (                LPAREN
430      * )                RPAREN
431      * [^-()\s][^()\s]* WORD
432      * "[^"]*"          WORD
433      * '[^']*'          WORD
434      */
435
436     function parse ($search_expr) {
437         $this->lexer = new TextSearchQuery_Lexer($search_expr);
438         $tree = $this->get_list('toplevel');
439         assert($this->lexer->eof());
440         unset($this->lexer);
441         return $tree;
442     }
443     
444     function get_list ($is_toplevel = false) {
445         $list = array();
446
447         // token types we'll accept as words (and thus expr's) for the
448         // purpose of error recovery:
449         $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
450         if ($is_toplevel)
451             $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
452         
453         while ( ($expr = $this->get_expr())
454                 || ($expr = $this->get_word($accept_as_words)) ) {
455             
456             $list[] = $expr;
457         }
458
459         if (!$list) {
460             if ($is_toplevel)
461                 return new TextSearchQuery_node;
462             else
463                 return false;
464         }
465         return new TextSearchQuery_node_and($list);
466     }
467
468     function get_expr () {
469         if ( !($expr = $this->get_atom()) )
470             return false;
471         
472         $savedpos = $this->lexer->tell();
473         while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
474             if ( ! ($right = $this->get_atom()) ) {
475                 break;
476             }
477             
478             if ($op == 'and')
479                 $expr = new TextSearchQuery_node_and(array($expr, $right));
480             else {
481                 assert($op == 'or');
482                 $expr = new TextSearchQuery_node_or(array($expr, $right));
483             }
484
485             $savedpos = $this->lexer->tell();
486         }
487         $this->lexer->seek($savedpos);
488
489         return $expr;
490     }
491     
492
493     function get_atom() {
494         if ($word = $this->get_word())
495             return $word;
496
497         $savedpos = $this->lexer->tell();
498         if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
499             if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
500                 return $list;
501         }
502         elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
503             if ( ($atom = $this->get_atom()) )
504                 return new TextSearchQuery_node_not($atom);
505         }
506         $this->lexer->seek($savedpos);
507         return false;
508     }
509
510     function get_word($accept = TSQ_TOK_WORD) {
511         if ( ($word = $this->lexer->get($accept)) )
512             return new TextSearchQuery_node_word($word);
513         return false;
514     }
515 }
516
517 class TextSearchQuery_Lexer {
518     function TextSearchQuery_Lexer ($query_str) {
519         $this->tokens = $this->tokenize($query_str);
520         $this->pos = 0;
521     }
522
523     function tell() {
524         return $this->pos;
525     }
526
527     function seek($pos) {
528         $this->pos = $pos;
529     }
530
531     function eof() {
532         return $this->pos == count($this->tokens);
533     }
534
535     function tokenize($string) {
536         $tokens = array();
537         $buf = strtolower(ltrim($string));
538         while (!empty($buf)) {
539             if (preg_match('/^(and|or)\s*/', $buf, $m)) {
540                 $val = $m[1];
541                 $type = TSQ_TOK_BINOP;
542             }
543             elseif (preg_match('/^(-|not)\s*/', $buf, $m)) {
544                 $val = $m[1];
545                 $type = TSQ_TOK_NOT;
546             }
547             elseif (preg_match('/^([()])\s*/', $buf, $m)) {
548                 $val = $m[1];
549                 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
550             }
551             elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
552                 $val = str_replace('""', '"', $m[1]);
553                 $type = TSQ_TOK_WORD;
554             }
555             elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
556                 $val = str_replace("''", "'", $m[1]);
557                 $type = TSQ_TOK_WORD;
558             }
559             elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
560                 $val = $m[1];
561                 $type = TSQ_TOK_WORD;
562             }
563             else {
564                 assert(empty($buf));
565                 break;
566             }
567             $buf = substr($buf, strlen($m[0]));
568             $tokens[] = array($type, $val);
569         }
570         return $tokens;
571     }
572     
573     function get($accept) {
574         if ($this->pos >= count($this->tokens))
575             return false;
576         
577         list ($type, $val) = $this->tokens[$this->pos];
578         if (($type & $accept) == 0)
579             return false;
580         
581         $this->pos++;
582         return $val;
583     }
584 }
585
586 // Local Variables:
587 // mode: php
588 // tab-width: 8
589 // c-basic-offset: 4
590 // c-hanging-comment-ender-p: nil
591 // indent-tabs-mode: nil
592 // End:   
593 ?>