]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/TextSearchQuery.php
fix VOID, add tsearch2 support
[SourceForge/phpwiki.git] / lib / TextSearchQuery.php
1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.22 2005-11-14 22:30:17 rurban Exp $');
2 /**
3  * A text search query, converting queries to PCRE and SQL matchers.
4  *
5  * This represents an enhanced "Google-like" text search query:
6  * <dl>
7  * <dt> default: case-insensitive glob-style search with special operators OR AND NOT -
8  * <dt> wiki -test
9  *   <dd> Match strings containing the substring 'wiki', and NOT containing the
10  *        substring 'test'.
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 and 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)
22  * </dl>
23  *
24  * The full query syntax, in order of precedence, is roughly:
25  *
26  * The unary 'NOT' or '-' operator (they are equivalent) negates the
27  * following search clause.
28  *
29  * Search clauses may be joined with the (left-associative) binary operators
30  * 'AND' and 'OR'. (case-insensitive)
31  *
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'.)
36  *
37  * Search clauses can be grouped with parentheses.
38  *
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
43  * "I'm hungry".
44  *
45  * Force regex on "re:word" => posix-style, "/word/" => pcre-style 
46  * or use regex='glob' to use file wildcard-like matching. (not yet)
47  *
48  * The parsed tree is then converted to the needed PCRE (highlight, 
49  * simple backends) or SQL functions. 
50  *
51  * @author: Jeff Dairiki
52  * @author: Reini Urban (case and regex detection, enhanced sql callbacks)
53  */
54
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);
62
63 class TextSearchQuery {
64     /**
65      * Create a new query.
66      *
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
72      */
73     function TextSearchQuery($search_query, $case_exact=false, $regex='auto') {
74         if ($regex == 'none' or !$regex) 
75             $this->_regex = 0;
76         elseif (defined("TSQ_REGEX_".strtoupper($regex)))
77             $this->_regex = constant("TSQ_REGEX_".strtoupper($regex));
78         else {
79             trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex));
80             $this->_regex = 0;
81         }
82         $this->_case_exact = $case_exact;
83         $parser = new TextSearchQuery_Parser;
84         $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex);
85         $this->_optimize(); // broken under certain circumstances: "word -word -word"
86         $this->_stoplist = '(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)';
87     }
88
89     function _optimize() {
90         $this->_tree = $this->_tree->optimize();
91     }
92
93     /**
94      * Get a PCRE regexp which matches the query.
95      */
96     function asRegexp() {
97         if (!isset($this->_regexp)) {
98             if ($this->_regex)
99                 $this->_regexp =  '/' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
100             else
101                 $this->_regexp =  '/^' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
102         }
103         return $this->_regexp;
104     }
105
106     /**
107      * Match query against string.
108      *
109      * @param $string string The string to match. 
110      * @return boolean True if the string matches the query.
111      */
112     function match($string) {
113         return preg_match($this->asRegexp(), $string);
114     }
115
116     
117     /**
118      * Get a regular expression suitable for highlighting matched words.
119      *
120      * This returns a PCRE regular expression which matches any non-negated
121      * word in the query.
122      *
123      * @return string The PCRE regexp.
124      */
125     function getHighlightRegexp() {
126         if (!isset($this->_hilight_regexp)) {
127             $words = array_unique($this->_tree->highlight_words());
128             if (!$words) {
129                 $this->_hilight_regexp = false;
130             } else {
131                 foreach ($words as $key => $word)
132                     $words[$key] = preg_quote($word, '/');
133                 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
134             }
135         }
136         return $this->_hilight_regexp;
137     }
138
139     /**
140      * Make an SQL clause which matches the query. (deprecated, use makeSqlClause instead)
141      *
142      * @param $make_sql_clause_cb WikiCallback
143      * A callback which takes a single word as an argument and
144      * returns an SQL clause which will match exactly those records
145      * containing the word.  The word passed to the callback will always
146      * be in all lower case.
147      *
148      * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
149      *       mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
150      *       How? WikiDB backend method?
151      *
152      * Old example usage:
153      * <pre>
154      *     function sql_title_match($word) {
155      *         return sprintf("LOWER(title) like '%s'",
156      *                        addslashes($word));
157      *     }
158      *
159      *     ...
160      *
161      *     $query = new TextSearchQuery("wiki -page");
162      *     $cb = new WikiFunctionCb('sql_title_match');
163      *     $sql_clause = $query->makeSqlClause($cb);
164      * </pre>
165      * This will result in $sql_clause containing something like
166      * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
167      *
168      * @return string The SQL clause.
169      */
170     function makeSqlClause($sql_clause_cb) {
171         $this->_sql_clause_cb = $sql_clause_cb;
172         return $this->_sql_clause($this->_tree);
173     }
174     // deprecated: use _sql_clause_obj now.
175     function _sql_clause($node) {
176         switch ($node->op) {
177         case 'WORD':        // word => %word%
178             return $this->_sql_clause_cb->call($node->word);
179         case 'NOT':
180             return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
181         case 'AND':
182         case 'OR':
183             $subclauses = array();
184             foreach ($node->leaves as $leaf)
185                 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
186             return join(" $node->op ", $subclauses);
187         default:
188             assert($node->op == 'VOID');
189             return '1=1';
190         }
191     }
192
193     /** Get away with the callback and use a db-specific search class instead.
194      * @see WikiDB_backend_PearDB_search
195      */
196     function makeSqlClauseObj(&$sql_search_cb) {
197         $this->_sql_clause_cb = $sql_search_cb;
198         return $this->_sql_clause_obj($this->_tree);
199     }
200
201     function _sql_clause_obj($node) {
202         switch ($node->op) {
203         case 'NOT':
204             return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
205         case 'AND':
206         case 'OR':
207             $subclauses = array();
208             foreach ($node->leaves as $leaf)
209                 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
210             return join(" $node->op ", $subclauses);
211         case 'VOID':
212             return '0=1';
213         case 'ALL':
214             return '1=1';
215         default:
216             return $this->_sql_clause_cb->call($node);
217         }
218     }
219
220     /*
221      postgresql tsearch2 uses no WHERE operators, just & | and ! in the searchstring
222      */
223     function makeTsearch2SqlClauseObj(&$sql_search_cb) {
224         $this->_sql_clause_cb = $sql_search_cb;
225         return $this->_Tsearch2Sql_clause_obj($this->_tree);
226     }
227
228     function _Tsearch2Sql_clause_obj($node) {
229         // TODO: "such a phrase"
230         switch ($node->op) {
231         case 'NOT':
232             return "!" . $node->leaves[0];
233         case 'AND':
234             $subclauses = array();
235             foreach ($node->leaves as $leaf)
236                 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
237             return join("&", $subclauses);
238         case 'OR':
239             $subclauses = array();
240             foreach ($node->leaves as $leaf)
241                 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
242             return join("|", $subclauses);
243         case 'VOID':
244             return '';
245         case 'ALL':
246             return '1';
247         default:
248             return $this->_sql_clause_cb->call($node);
249         }
250     }
251
252     function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
253
254     /**
255      * Get printable representation of the parse tree.
256      *
257      * This is for debugging only.
258      * @return string Printable parse tree.
259      */
260     function asString() {
261         return $this->_as_string($this->_tree);
262     }
263
264     function _as_string($node, $indent = '') {
265         switch ($node->op) {
266         case 'WORD':
267             return $indent . "WORD: $node->word";
268         case 'VOID':
269             return $indent . "VOID";
270         case 'ALL':
271             return $indent . "ALL";
272         default:
273             $lines = array($indent . $node->op . ":");
274             $indent .= "  ";
275             foreach ($node->leaves as $leaf)
276                 $lines[] = $this->_as_string($leaf, $indent);
277             return join("\n", $lines);
278         }
279     }
280 }
281
282 /**
283  * This is a TextSearchQuery which matches nothing.
284  */
285 class NullTextSearchQuery extends TextSearchQuery {
286     /**
287      * Create a new query.
288      *
289      * @see TextSearchQuery
290      */
291     function NullTextSearchQuery() {}
292     function asRegexp()         { return '/^(?!a)a/x'; }
293     function match($string)     { return false; }
294     function getHighlightRegexp() { return ""; }
295     function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
296     function asString() { return "NullTextSearchQuery"; }
297 };
298
299
300 ////////////////////////////////////////////////////////////////
301 //
302 // Remaining classes are private.
303 //
304 ////////////////////////////////////////////////////////////////
305 /**
306  * Virtual base class for nodes in a TextSearchQuery parse tree.
307  *
308  * Also serves as a 'VOID' (contentless) node.
309  */
310 class TextSearchQuery_node
311 {
312     var $op = 'VOID';
313
314     /**
315      * Optimize this node.
316      * @return object Optimized node.
317      */
318     function optimize() {
319         return $this;
320     }
321
322     /**
323      * @return regexp matching this node.
324      */
325     function regexp() {
326         return '';
327     }
328
329     /**
330      * @param bool True if this node has been negated (higher in the parse tree.)
331      * @return array A list of all non-negated words contained by this node.
332      */
333     function highlight_words($negated = false) {
334         return array();
335     }
336
337     function sql()    { return $this->word; }
338 }
339
340 /**
341  * A word.
342  */
343 class TextSearchQuery_node_word
344 extends TextSearchQuery_node
345 {
346     var $op = "WORD";
347     
348     function TextSearchQuery_node_word($word) {
349         $this->word = $word;
350     }
351     function regexp() {
352         return '(?=.*' . preg_quote($this->word, '/') . ')';
353     }
354     function highlight_words ($negated = false) {
355         return $negated ? array() : array($this->word);
356     }
357     function _sql_quote() {
358         $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
359         return $GLOBALS['request']->_dbi->qstr($word);
360     }
361     function sql()    { return '%'.$this->_sql_quote($this->word).'%'; }
362 }
363
364 class TextSearchQuery_node_all
365 extends TextSearchQuery_node {
366     var $op = "ALL";
367     function regexp() { return '(?=.*)'; }
368     function sql()    { return '%'; }
369 }
370 class TextSearchQuery_node_starts_with
371 extends TextSearchQuery_node_word {
372     var $op = "STARTS_WITH";
373     function regexp() { return '(?=.*\b' . preg_quote($this->word, '/') . ')'; }
374     function sql ()   { return $this->_sql_quote($this->word).'%'; }
375 }
376
377 class TextSearchQuery_node_ends_with
378 extends TextSearchQuery_node_word {
379     var $op = "ENDS_WITH";
380     function regexp() { return '(?=.*' . preg_quote($this->word, '/') . '\b)'; }
381     function sql ()   { return '%'.$this->_sql_quote($this->word); }
382 }
383
384 class TextSearchQuery_node_exact
385 extends TextSearchQuery_node_word {
386     var $op = "EXACT";
387     function regexp() { return '(?=\b' . preg_quote($this->word, '/') . '\b)'; }
388     function sql ()   { return $this->_sql_squote($this->word); }
389 }
390
391 class TextSearchQuery_node_regex // posix regex. FIXME!
392 extends TextSearchQuery_node_word {
393     var $op = "REGEX"; // using REGEXP or ~ extension
394     function regexp() { return '(?=.*\b' . $this->word . '\b)'; }
395     function sql ()   { return $this->_sql_quote($this->word); }
396 }
397
398 class TextSearchQuery_node_regex_glob
399 extends TextSearchQuery_node_regex {
400     var $op = "REGEX_GLOB";
401     function regexp() { return '(?=.*\b' . glob_to_pcre($this->word) . '\b)'; }
402 }
403
404 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
405 extends TextSearchQuery_node_regex {
406     var $op = "REGEX_PCRE";
407     function regexp() { return $this->word; }
408 }
409
410 class TextSearchQuery_node_regex_sql
411 extends TextSearchQuery_node_regex {
412     var $op = "REGEX_SQL"; // using LIKE
413     function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
414     function sql()    { return $this->word; }
415 }
416
417 /**
418  * A negated clause.
419  */
420 class TextSearchQuery_node_not
421 extends TextSearchQuery_node
422 {
423     var $op = "NOT";
424     
425     function TextSearchQuery_node_not($leaf) {
426         $this->leaves = array($leaf);
427     }
428
429     function optimize() {
430         $leaf = &$this->leaves[0];
431         $leaf = $leaf->optimize();
432         if ($leaf->op == 'NOT')
433             return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
434         return $this;
435     }
436     
437     function regexp() {
438         $leaf = &$this->leaves[0];
439         return '(?!' . $leaf->regexp() . ')';
440     }
441
442     function highlight_words ($negated = false) {
443         return $this->leaves[0]->highlight_words(!$negated);
444     }
445 }
446
447 /**
448  * Virtual base class for 'AND' and 'OR conjoins.
449  */
450 class TextSearchQuery_node_binop
451 extends TextSearchQuery_node
452 {
453     function TextSearchQuery_node_binop($leaves) {
454         $this->leaves = $leaves;
455     }
456
457     function _flatten() {
458         // This flattens e.g. (AND (AND a b) (OR c d) e)
459         //        to (AND a b e (OR c d))
460         $flat = array();
461         foreach ($this->leaves as $leaf) {
462             $leaf = $leaf->optimize();
463             if ($this->op == $leaf->op)
464                 $flat = array_merge($flat, $leaf->leaves);
465             else
466                 $flat[] = $leaf;
467         }
468         $this->leaves = $flat;
469     }
470
471     function optimize() {
472         $this->_flatten();
473         assert(!empty($this->leaves));
474         if (count($this->leaves) == 1)
475             return $this->leaves[0]; // (AND x) -> x
476         return $this;
477     }
478
479     function highlight_words($negated = false) {
480         $words = array();
481         foreach ($this->leaves as $leaf)
482             array_splice($words,0,0,
483                          $leaf->highlight_words($negated));
484         return $words;
485     }
486 }
487
488 /**
489  * A (possibly multi-argument) 'AND' conjoin.
490  */
491 class TextSearchQuery_node_and
492 extends TextSearchQuery_node_binop
493 {
494     var $op = "AND";
495     
496     function optimize() {
497         $this->_flatten();
498
499         // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
500         // Since OR's are more efficient for regexp matching:
501         //   (?!.*a)(?!.*b)  vs   (?!.*(?:a|b))
502
503         // Suck out the negated leaves.
504         $nots = array();
505         foreach ($this->leaves as $key => $leaf) {
506             if ($leaf->op == 'NOT') {
507                 $nots[] = $leaf->leaves[0];
508                 unset($this->leaves[$key]);
509             }
510         }
511
512         // Combine the negated leaves into a single negated or.
513         if ($nots) {
514             $node = ( new TextSearchQuery_node_not
515                       (new TextSearchQuery_node_or($nots)) );
516             array_unshift($this->leaves, $node->optimize());
517         }
518         
519         assert(!empty($this->leaves));
520         if (count($this->leaves) == 1)
521             return $this->leaves[0];  // (AND x) -> x
522         return $this;
523     }
524
525     /* FIXME!
526      * Either we need all combinations of all words to be position independent,
527      * or we have to use multiple match calls for each AND
528      * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
529      */
530     function regexp() {
531         $regexp = '';
532         foreach ($this->leaves as $leaf)
533             $regexp .= $leaf->regexp();
534         return $regexp;
535     }
536 }
537
538 /**
539  * A (possibly multi-argument) 'OR' conjoin.
540  */
541 class TextSearchQuery_node_or
542 extends TextSearchQuery_node_binop
543 {
544     var $op = "OR";
545
546     function regexp() {
547         // We will combine any of our direct descendents which are WORDs
548         // into a single (?=.*(?:word1|word2|...)) regexp.
549         
550         $regexps = array();
551         $words = array();
552
553         foreach ($this->leaves as $leaf) {
554             if ($leaf->op == 'WORD')
555                 $words[] = preg_quote($leaf->word, '/');
556             else
557                 $regexps[] = $leaf->regexp();
558         }
559
560         if ($words)
561             array_unshift($regexps,
562                           '(?=.*' . $this->_join($words) . ')');
563
564         return $this->_join($regexps);
565     }
566
567     function _join($regexps) {
568         assert(count($regexps) > 0);
569
570         if (count($regexps) > 1)
571             return '(?:' . join('|', $regexps) . ')';
572         else
573             return $regexps[0];
574     }
575 }
576
577
578 ////////////////////////////////////////////////////////////////
579 //
580 // Parser:
581 //   op's (and, or, not) are forced to lowercase in the tokenizer.
582 //
583 ////////////////////////////////////////////////////////////////
584 define ('TSQ_TOK_BINOP',  1);
585 define ('TSQ_TOK_NOT',    2);
586 define ('TSQ_TOK_LPAREN', 4);
587 define ('TSQ_TOK_RPAREN', 8);
588 define ('TSQ_TOK_WORD',   16);
589 define ('TSQ_TOK_STARTS_WITH', 32);
590 define ('TSQ_TOK_ENDS_WITH', 64);
591 define ('TSQ_TOK_EXACT', 128);
592 define ('TSQ_TOK_REGEX', 256);
593 define ('TSQ_TOK_REGEX_GLOB', 512);
594 define ('TSQ_TOK_REGEX_PCRE', 1024);
595 define ('TSQ_TOK_REGEX_SQL', 2048);
596 define ('TSQ_TOK_ALL', 4096);
597 // all bits from word to the last.
598 define ('TSQ_ALLWORDS', (4096*2)-1 - (16-1));
599
600 class TextSearchQuery_Parser 
601 {
602     /*
603      * This is a simple recursive descent parser, based on the following grammar:
604      *
605      * toplist  :
606      *          | toplist expr
607      *          ;
608      *
609      *
610      * list     : expr
611      *          | list expr
612      *          ;
613      *
614      * expr     : atom
615      *          | expr BINOP atom
616      *          ;
617      *
618      * atom     : '(' list ')'
619      *          | NOT atom
620      *          | WORD
621      *          ;
622      *
623      * The terminal tokens are:
624      *
625      *
626      * and|or             BINOP
627      * -|not              NOT
628      * (                  LPAREN
629      * )                  RPAREN
630      * /[^-()\s][^()\s]*  WORD
631      * /"[^"]*"/          WORD
632      * /'[^']*'/          WORD
633      *
634      * ^WORD              STARTS_WITH
635      * WORD*              STARTS_WITH
636      * *WORD              ENDS_WITH
637      * ^WORD$             EXACT
638      * *                  ALL
639      */
640
641     function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
642         $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
643         $this->_regex = $regex;
644         $tree = $this->get_list('toplevel');
645         assert($this->lexer->eof());
646         unset($this->lexer);
647         return $tree;
648     }
649     
650     function get_list ($is_toplevel = false) {
651         $list = array();
652
653         // token types we'll accept as words (and thus expr's) for the
654         // purpose of error recovery:
655         $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
656         if ($is_toplevel)
657             $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
658         
659         while ( ($expr = $this->get_expr())
660                 || ($expr = $this->get_word($accept_as_words)) ) {
661             $list[] = $expr;
662         }
663
664         if (!$list) {
665             if ($is_toplevel)
666                 return new TextSearchQuery_node;
667             else
668                 return false;
669         }
670         return new TextSearchQuery_node_and($list);
671     }
672
673     function get_expr () {
674         if ( !($expr = $this->get_atom()) )
675             return false;
676         
677         $savedpos = $this->lexer->tell();
678         while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
679             if ( ! ($right = $this->get_atom()) ) {
680                 break;
681             }
682             
683             if ($op == 'and')
684                 $expr = new TextSearchQuery_node_and(array($expr, $right));
685             else {
686                 assert($op == 'or');
687                 $expr = new TextSearchQuery_node_or(array($expr, $right));
688             }
689
690             $savedpos = $this->lexer->tell();
691         }
692         $this->lexer->seek($savedpos);
693
694         return $expr;
695     }
696     
697
698     function get_atom() {
699         if ($word = $this->get_word(TSQ_ALLWORDS))
700             return $word;
701
702         $savedpos = $this->lexer->tell();
703         if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
704             if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
705                 return $list;
706         }
707         elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
708             if ( ($atom = $this->get_atom()) )
709                 return new TextSearchQuery_node_not($atom);
710         }
711         $this->lexer->seek($savedpos);
712         return false;
713     }
714
715     function get_word($accept = TSQ_ALLWORDS) {
716         foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
717                        "REGEX","REGEX_GLOB","REGEX_PCRE","ALL") as $tok) {
718             $const = constant("TSQ_TOK_".$tok);
719             if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
720                 $classname = "TextSearchQuery_node_".strtolower($tok);
721                 return new $classname($word);
722             }
723         }
724         return false;
725     }
726 }
727
728 class TextSearchQuery_Lexer {
729     function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
730         $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
731         $this->pos = 0;
732     }
733
734     function tell() {
735         return $this->pos;
736     }
737
738     function seek($pos) {
739         $this->pos = $pos;
740     }
741
742     function eof() {
743         return $this->pos == count($this->tokens);
744     }
745     
746     /**
747      * TODO: support more regex styles, esp. prefer the forced ones over auto
748      * re: and // stuff
749      */
750     function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
751         $tokens = array();
752         $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
753         while (!empty($buf)) {
754             if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
755                 $val = strtolower($m[1]);
756                 $type = TSQ_TOK_BINOP;
757             }
758             elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
759                 $val = strtolower($m[1]);
760                 $type = TSQ_TOK_NOT;
761             }
762             elseif (preg_match('/^([()])\s*/', $buf, $m)) {
763                 $val = $m[1];
764                 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
765             }
766             
767             // * => ALL
768             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
769                     and preg_match('/^\*\s*/', $buf, $m)) {
770                 $val = "*";
771                 $type = TSQ_TOK_ALL;
772             }
773             // .* => ALL
774             elseif ($regex & (TSQ_REGEX_PCRE)
775                     and preg_match('/^\.\*\s*/', $buf, $m)) {
776                 $val = ".*";
777                 $type = TSQ_TOK_ALL;
778             }
779             // % => ALL
780             elseif ($regex & (TSQ_REGEX_SQL)
781                     and preg_match('/^%\s*/', $buf, $m)) {
782                 $val = "%";
783                 $type = TSQ_TOK_ALL;
784             }
785             
786             // ^word
787             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
788                     and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
789                 $val = $m[1];
790                 $type = TSQ_TOK_STARTS_WITH;
791             }
792             // word*
793             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
794                     and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
795                 $val = $m[1];
796                 $type = TSQ_TOK_STARTS_WITH;
797             }
798             // *word
799             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
800                     and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
801                 $val = $m[1];
802                 $type = TSQ_TOK_ENDS_WITH;
803             }
804             // word$
805             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
806                     and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
807                 $val = $m[1];
808                 $type = TSQ_TOK_ENDS_WITH;
809             }
810             // ^word$
811             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
812                     and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
813                 $val = $m[1];
814                 $type = TSQ_TOK_EXACT;
815             }
816             
817             // "words "
818             elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
819                 $val = str_replace('""', '"', $m[1]);
820                 $type = TSQ_TOK_WORD;
821             }
822             // 'words '
823             elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
824                 $val = str_replace("''", "'", $m[1]);
825                 $type = TSQ_TOK_WORD;
826             }
827             // word
828             elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
829                 $val = $m[1];
830                 $type = TSQ_TOK_WORD;
831             }
832             else {
833                 assert(empty($buf));
834                 break;
835             }
836             $buf = substr($buf, strlen($m[0]));
837
838             /* refine the simple parsing from above: bla*bla, bla?bla, ...
839             if ($regex and $type == TSQ_TOK_WORD) {
840                 if (substr($val,0,1) == "^")
841                     $type = TSQ_TOK_STARTS_WITH;
842                 elseif (substr($val,0,1) == "*")
843                     $type = TSQ_TOK_ENDS_WITH;
844                 elseif (substr($val,-1,1) == "*")
845                     $type = TSQ_TOK_STARTS_WITH;
846             }
847             */
848             $tokens[] = array($type, $val);
849         }
850         return $tokens;
851     }
852     
853     function get($accept) {
854         if ($this->pos >= count($this->tokens))
855             return false;
856         
857         list ($type, $val) = $this->tokens[$this->pos];
858         if (($type & $accept) == 0)
859             return false;
860         
861         $this->pos++;
862         return $val;
863     }
864 }
865
866 // Local Variables:
867 // mode: php
868 // tab-width: 8
869 // c-basic-offset: 4
870 // c-hanging-comment-ender-p: nil
871 // indent-tabs-mode: nil
872 // End:   
873 ?>