]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/TextSearchQuery.php
added optimization for a new ALL textsearch token
[SourceForge/phpwiki.git] / lib / TextSearchQuery.php
1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.21 2005-09-14 05:59:48 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     function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
221
222     /**
223      * Get printable representation of the parse tree.
224      *
225      * This is for debugging only.
226      * @return string Printable parse tree.
227      */
228     function asString() {
229         return $this->_as_string($this->_tree);
230     }
231
232     function _as_string($node, $indent = '') {
233         switch ($node->op) {
234         case 'WORD':
235             return $indent . "WORD: $node->word";
236         case 'VOID':
237             return $indent . "VOID";
238         case 'ALL':
239             return $indent . "ALL";
240         default:
241             $lines = array($indent . $node->op . ":");
242             $indent .= "  ";
243             foreach ($node->leaves as $leaf)
244                 $lines[] = $this->_as_string($leaf, $indent);
245             return join("\n", $lines);
246         }
247     }
248 }
249
250 /**
251  * This is a TextSearchQuery which matches nothing.
252  */
253 class NullTextSearchQuery extends TextSearchQuery {
254     /**
255      * Create a new query.
256      *
257      * @see TextSearchQuery
258      */
259     function NullTextSearchQuery() {}
260     function asRegexp()         { return '/^(?!a)a/x'; }
261     function match($string)     { return false; }
262     function getHighlightRegexp() { return ""; }
263     function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
264     function asString() { return "NullTextSearchQuery"; }
265 };
266
267
268 ////////////////////////////////////////////////////////////////
269 //
270 // Remaining classes are private.
271 //
272 ////////////////////////////////////////////////////////////////
273 /**
274  * Virtual base class for nodes in a TextSearchQuery parse tree.
275  *
276  * Also serves as a 'VOID' (contentless) node.
277  */
278 class TextSearchQuery_node
279 {
280     var $op = 'VOID';
281
282     /**
283      * Optimize this node.
284      * @return object Optimized node.
285      */
286     function optimize() {
287         return $this;
288     }
289
290     /**
291      * @return regexp matching this node.
292      */
293     function regexp() {
294         return '';
295     }
296
297     /**
298      * @param bool True if this node has been negated (higher in the parse tree.)
299      * @return array A list of all non-negated words contained by this node.
300      */
301     function highlight_words($negated = false) {
302         return array();
303     }
304
305     function sql()    { return $this->word; }
306 }
307
308 /**
309  * A word.
310  */
311 class TextSearchQuery_node_word
312 extends TextSearchQuery_node
313 {
314     var $op = "WORD";
315     
316     function TextSearchQuery_node_word($word) {
317         $this->word = $word;
318     }
319     function regexp() {
320         return '(?=.*' . preg_quote($this->word, '/') . ')';
321     }
322     function highlight_words($negated = false) {
323         return $negated ? array() : array($this->word);
324     }
325     function _sql_quote() {
326         $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
327         return $GLOBALS['request']->_dbi->qstr($word);
328     }
329     function sql()    { return '%'.$this->_sql_quote($this->word).'%'; }
330 }
331
332 class TextSearchQuery_node_all
333 extends TextSearchQuery_node {
334     var $op = "ALL";
335     function regexp() { return '(?=.*)'; }
336     function sql()    { return '%'; }
337 }
338 class TextSearchQuery_node_starts_with
339 extends TextSearchQuery_node_word {
340     var $op = "STARTS_WITH";
341     function regexp() { return '(?=.*\b' . preg_quote($this->word, '/') . ')'; }
342     function sql()    { return $this->_sql_quote($this->word).'%'; }
343 }
344
345 class TextSearchQuery_node_ends_with
346 extends TextSearchQuery_node_word {
347     var $op = "ENDS_WITH";
348     function regexp() { return '(?=.*' . preg_quote($this->word, '/') . '\b)'; }
349     function sql()    { return '%'.$this->_sql_quote($this->word); }
350 }
351
352 class TextSearchQuery_node_exact
353 extends TextSearchQuery_node_word {
354     var $op = "EXACT";
355     function regexp() { return '(?=\b' . preg_quote($this->word, '/') . '\b)'; }
356     function sql()    { return $this->_sql_squote($this->word); }
357 }
358
359 class TextSearchQuery_node_regex // posix regex. FIXME!
360 extends TextSearchQuery_node_word {
361     var $op = "REGEX"; // using REGEXP or ~ extension
362     function regexp() { return '(?=.*\b' . $this->word . '\b)'; }
363     function sql()    { return $this->_sql_quote($this->word); }
364 }
365
366 class TextSearchQuery_node_regex_glob
367 extends TextSearchQuery_node_regex {
368     var $op = "REGEX_GLOB";
369     function regexp() { return '(?=.*\b' . glob_to_pcre($this->word) . '\b)'; }
370 }
371
372 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
373 extends TextSearchQuery_node_regex {
374     var $op = "REGEX_PCRE";
375     function regexp() { return $this->word; }
376 }
377
378 class TextSearchQuery_node_regex_sql
379 extends TextSearchQuery_node_regex {
380     var $op = "REGEX_SQL"; // using LIKE
381     function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
382     function sql()    { return $this->word; }
383 }
384
385 /**
386  * A negated clause.
387  */
388 class TextSearchQuery_node_not
389 extends TextSearchQuery_node
390 {
391     var $op = "NOT";
392     
393     function TextSearchQuery_node_not($leaf) {
394         $this->leaves = array($leaf);
395     }
396
397     function optimize() {
398         $leaf = &$this->leaves[0];
399         $leaf = $leaf->optimize();
400         if ($leaf->op == 'NOT')
401             return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
402         return $this;
403     }
404     
405     function regexp() {
406         $leaf = &$this->leaves[0];
407         return '(?!' . $leaf->regexp() . ')';
408     }
409
410     function highlight_words($negated = false) {
411         return $this->leaves[0]->highlight_words(!$negated);
412     }
413 }
414
415 /**
416  * Virtual base class for 'AND' and 'OR conjoins.
417  */
418 class TextSearchQuery_node_binop
419 extends TextSearchQuery_node
420 {
421     function TextSearchQuery_node_binop($leaves) {
422         $this->leaves = $leaves;
423     }
424
425     function _flatten() {
426         // This flattens e.g. (AND (AND a b) (OR c d) e)
427         //        to (AND a b e (OR c d))
428         $flat = array();
429         foreach ($this->leaves as $leaf) {
430             $leaf = $leaf->optimize();
431             if ($this->op == $leaf->op)
432                 $flat = array_merge($flat, $leaf->leaves);
433             else
434                 $flat[] = $leaf;
435         }
436         $this->leaves = $flat;
437     }
438
439     function optimize() {
440         $this->_flatten();
441         assert(!empty($this->leaves));
442         if (count($this->leaves) == 1)
443             return $this->leaves[0]; // (AND x) -> x
444         return $this;
445     }
446
447     function highlight_words($negated = false) {
448         $words = array();
449         foreach ($this->leaves as $leaf)
450             array_splice($words,0,0,
451                          $leaf->highlight_words($negated));
452         return $words;
453     }
454 }
455
456 /**
457  * A (possibly multi-argument) 'AND' conjoin.
458  */
459 class TextSearchQuery_node_and
460 extends TextSearchQuery_node_binop
461 {
462     var $op = "AND";
463     
464     function optimize() {
465         $this->_flatten();
466
467         // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
468         // Since OR's are more efficient for regexp matching:
469         //   (?!.*a)(?!.*b)  vs   (?!.*(?:a|b))
470
471         // Suck out the negated leaves.
472         $nots = array();
473         foreach ($this->leaves as $key => $leaf) {
474             if ($leaf->op == 'NOT') {
475                 $nots[] = $leaf->leaves[0];
476                 unset($this->leaves[$key]);
477             }
478         }
479
480         // Combine the negated leaves into a single negated or.
481         if ($nots) {
482             $node = ( new TextSearchQuery_node_not
483                       (new TextSearchQuery_node_or($nots)) );
484             array_unshift($this->leaves, $node->optimize());
485         }
486         
487         assert(!empty($this->leaves));
488         if (count($this->leaves) == 1)
489             return $this->leaves[0];  // (AND x) -> x
490         return $this;
491     }
492
493     /* FIXME!
494      * Either we need all combinations of all words to be position independent,
495      * or we have to use multiple match calls for each AND
496      * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
497      */
498     function regexp() {
499         $regexp = '';
500         foreach ($this->leaves as $leaf)
501             $regexp .= $leaf->regexp();
502         return $regexp;
503     }
504 }
505
506 /**
507  * A (possibly multi-argument) 'OR' conjoin.
508  */
509 class TextSearchQuery_node_or
510 extends TextSearchQuery_node_binop
511 {
512     var $op = "OR";
513
514     function regexp() {
515         // We will combine any of our direct descendents which are WORDs
516         // into a single (?=.*(?:word1|word2|...)) regexp.
517         
518         $regexps = array();
519         $words = array();
520
521         foreach ($this->leaves as $leaf) {
522             if ($leaf->op == 'WORD')
523                 $words[] = preg_quote($leaf->word, '/');
524             else
525                 $regexps[] = $leaf->regexp();
526         }
527
528         if ($words)
529             array_unshift($regexps,
530                           '(?=.*' . $this->_join($words) . ')');
531
532         return $this->_join($regexps);
533     }
534
535     function _join($regexps) {
536         assert(count($regexps) > 0);
537
538         if (count($regexps) > 1)
539             return '(?:' . join('|', $regexps) . ')';
540         else
541             return $regexps[0];
542     }
543 }
544
545
546 ////////////////////////////////////////////////////////////////
547 //
548 // Parser:
549 //   op's (and, or, not) are forced to lowercase in the tokenizer.
550 //
551 ////////////////////////////////////////////////////////////////
552 define ('TSQ_TOK_BINOP',  1);
553 define ('TSQ_TOK_NOT',    2);
554 define ('TSQ_TOK_LPAREN', 4);
555 define ('TSQ_TOK_RPAREN', 8);
556 define ('TSQ_TOK_WORD',   16);
557 define ('TSQ_TOK_STARTS_WITH', 32);
558 define ('TSQ_TOK_ENDS_WITH', 64);
559 define ('TSQ_TOK_EXACT', 128);
560 define ('TSQ_TOK_REGEX', 256);
561 define ('TSQ_TOK_REGEX_GLOB', 512);
562 define ('TSQ_TOK_REGEX_PCRE', 1024);
563 define ('TSQ_TOK_REGEX_SQL', 2048);
564 define ('TSQ_TOK_ALL', 4096);
565 // all bits from word to the last.
566 define ('TSQ_ALLWORDS', (4096*2)-1 - (16-1));
567
568 class TextSearchQuery_Parser 
569 {
570     /*
571      * This is a simple recursive descent parser, based on the following grammar:
572      *
573      * toplist  :
574      *          | toplist expr
575      *          ;
576      *
577      *
578      * list     : expr
579      *          | list expr
580      *          ;
581      *
582      * expr     : atom
583      *          | expr BINOP atom
584      *          ;
585      *
586      * atom     : '(' list ')'
587      *          | NOT atom
588      *          | WORD
589      *          ;
590      *
591      * The terminal tokens are:
592      *
593      *
594      * and|or             BINOP
595      * -|not              NOT
596      * (                  LPAREN
597      * )                  RPAREN
598      * /[^-()\s][^()\s]*  WORD
599      * /"[^"]*"/          WORD
600      * /'[^']*'/          WORD
601      *
602      * ^WORD              STARTS_WITH
603      * WORD*              STARTS_WITH
604      * *WORD              ENDS_WITH
605      * ^WORD$             EXACT
606      * *                  ALL
607      */
608
609     function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
610         $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
611         $this->_regex = $regex;
612         $tree = $this->get_list('toplevel');
613         assert($this->lexer->eof());
614         unset($this->lexer);
615         return $tree;
616     }
617     
618     function get_list ($is_toplevel = false) {
619         $list = array();
620
621         // token types we'll accept as words (and thus expr's) for the
622         // purpose of error recovery:
623         $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
624         if ($is_toplevel)
625             $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
626         
627         while ( ($expr = $this->get_expr())
628                 || ($expr = $this->get_word($accept_as_words)) ) {
629             $list[] = $expr;
630         }
631
632         if (!$list) {
633             if ($is_toplevel)
634                 return new TextSearchQuery_node;
635             else
636                 return false;
637         }
638         return new TextSearchQuery_node_and($list);
639     }
640
641     function get_expr () {
642         if ( !($expr = $this->get_atom()) )
643             return false;
644         
645         $savedpos = $this->lexer->tell();
646         while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
647             if ( ! ($right = $this->get_atom()) ) {
648                 break;
649             }
650             
651             if ($op == 'and')
652                 $expr = new TextSearchQuery_node_and(array($expr, $right));
653             else {
654                 assert($op == 'or');
655                 $expr = new TextSearchQuery_node_or(array($expr, $right));
656             }
657
658             $savedpos = $this->lexer->tell();
659         }
660         $this->lexer->seek($savedpos);
661
662         return $expr;
663     }
664     
665
666     function get_atom() {
667         if ($word = $this->get_word(TSQ_ALLWORDS))
668             return $word;
669
670         $savedpos = $this->lexer->tell();
671         if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
672             if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
673                 return $list;
674         }
675         elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
676             if ( ($atom = $this->get_atom()) )
677                 return new TextSearchQuery_node_not($atom);
678         }
679         $this->lexer->seek($savedpos);
680         return false;
681     }
682
683     function get_word($accept = TSQ_ALLWORDS) {
684         foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
685                        "REGEX","REGEX_GLOB","REGEX_PCRE","ALL") as $tok) {
686             $const = constant("TSQ_TOK_".$tok);
687             if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
688                 $classname = "TextSearchQuery_node_".strtolower($tok);
689                 return new $classname($word);
690             }
691         }
692         return false;
693     }
694 }
695
696 class TextSearchQuery_Lexer {
697     function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
698         $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
699         $this->pos = 0;
700     }
701
702     function tell() {
703         return $this->pos;
704     }
705
706     function seek($pos) {
707         $this->pos = $pos;
708     }
709
710     function eof() {
711         return $this->pos == count($this->tokens);
712     }
713     
714     /**
715      * TODO: support more regex styles, esp. prefer the forced ones over auto
716      * re: and // stuff
717      */
718     function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
719         $tokens = array();
720         $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
721         while (!empty($buf)) {
722             if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
723                 $val = strtolower($m[1]);
724                 $type = TSQ_TOK_BINOP;
725             }
726             elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
727                 $val = strtolower($m[1]);
728                 $type = TSQ_TOK_NOT;
729             }
730             elseif (preg_match('/^([()])\s*/', $buf, $m)) {
731                 $val = $m[1];
732                 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
733             }
734             
735             // * => ALL
736             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
737                     and preg_match('/^\*\s*/', $buf, $m)) {
738                 $val = "*";
739                 $type = TSQ_TOK_ALL;
740             }
741             // .* => ALL
742             elseif ($regex & (TSQ_REGEX_PCRE)
743                     and preg_match('/^\.\*\s*/', $buf, $m)) {
744                 $val = ".*";
745                 $type = TSQ_TOK_ALL;
746             }
747             // % => ALL
748             elseif ($regex & (TSQ_REGEX_SQL)
749                     and preg_match('/^%\s*/', $buf, $m)) {
750                 $val = "%";
751                 $type = TSQ_TOK_ALL;
752             }
753             
754             // ^word
755             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
756                     and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
757                 $val = $m[1];
758                 $type = TSQ_TOK_STARTS_WITH;
759             }
760             // word*
761             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
762                     and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
763                 $val = $m[1];
764                 $type = TSQ_TOK_STARTS_WITH;
765             }
766             // *word
767             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
768                     and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
769                 $val = $m[1];
770                 $type = TSQ_TOK_ENDS_WITH;
771             }
772             // word$
773             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
774                     and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
775                 $val = $m[1];
776                 $type = TSQ_TOK_ENDS_WITH;
777             }
778             // ^word$
779             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
780                     and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
781                 $val = $m[1];
782                 $type = TSQ_TOK_EXACT;
783             }
784             
785             // "words "
786             elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
787                 $val = str_replace('""', '"', $m[1]);
788                 $type = TSQ_TOK_WORD;
789             }
790             // 'words '
791             elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
792                 $val = str_replace("''", "'", $m[1]);
793                 $type = TSQ_TOK_WORD;
794             }
795             // word
796             elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
797                 $val = $m[1];
798                 $type = TSQ_TOK_WORD;
799             }
800             else {
801                 assert(empty($buf));
802                 break;
803             }
804             $buf = substr($buf, strlen($m[0]));
805
806             /* refine the simple parsing from above: bla*bla, bla?bla, ...
807             if ($regex and $type == TSQ_TOK_WORD) {
808                 if (substr($val,0,1) == "^")
809                     $type = TSQ_TOK_STARTS_WITH;
810                 elseif (substr($val,0,1) == "*")
811                     $type = TSQ_TOK_ENDS_WITH;
812                 elseif (substr($val,-1,1) == "*")
813                     $type = TSQ_TOK_STARTS_WITH;
814             }
815             */
816             $tokens[] = array($type, $val);
817         }
818         return $tokens;
819     }
820     
821     function get($accept) {
822         if ($this->pos >= count($this->tokens))
823             return false;
824         
825         list ($type, $val) = $this->tokens[$this->pos];
826         if (($type & $accept) == 0)
827             return false;
828         
829         $this->pos++;
830         return $val;
831     }
832 }
833
834 // Local Variables:
835 // mode: php
836 // tab-width: 8
837 // c-basic-offset: 4
838 // c-hanging-comment-ender-p: nil
839 // indent-tabs-mode: nil
840 // End:   
841 ?>