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