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