]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/TextSearchQuery.php
fix AND WORD pcre asRegexp
[SourceForge/phpwiki.git] / lib / TextSearchQuery.php
1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.19 2005-09-11 14:12:13 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     /* FIXME!
483      * Either we need all combinations of all words to be position independent,
484      * or we have to use multiple match calls for each AND
485      * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
486      */
487     function regexp() {
488         $regexp = '';
489         foreach ($this->leaves as $leaf)
490             $regexp .= $leaf->regexp();
491         return $regexp;
492     }
493 }
494
495 /**
496  * A (possibly multi-argument) 'OR' conjoin.
497  */
498 class TextSearchQuery_node_or
499 extends TextSearchQuery_node_binop
500 {
501     var $op = "OR";
502
503     function regexp() {
504         // We will combine any of our direct descendents which are WORDs
505         // into a single (?=.*(?:word1|word2|...)) regexp.
506         
507         $regexps = array();
508         $words = array();
509
510         foreach ($this->leaves as $leaf) {
511             if ($leaf->op == 'WORD')
512                 $words[] = preg_quote($leaf->word, '/');
513             else
514                 $regexps[] = $leaf->regexp();
515         }
516
517         if ($words)
518             array_unshift($regexps,
519                           '(?=.*' . $this->_join($words) . ')');
520
521         return $this->_join($regexps);
522     }
523
524     function _join($regexps) {
525         assert(count($regexps) > 0);
526
527         if (count($regexps) > 1)
528             return '(?:' . join('|', $regexps) . ')';
529         else
530             return $regexps[0];
531     }
532 }
533
534
535 ////////////////////////////////////////////////////////////////
536 //
537 // Parser:
538 //   op's (and, or, not) are forced to lowercase in the tokenizer.
539 //
540 ////////////////////////////////////////////////////////////////
541 define ('TSQ_TOK_BINOP',  1);
542 define ('TSQ_TOK_NOT',    2);
543 define ('TSQ_TOK_LPAREN', 4);
544 define ('TSQ_TOK_RPAREN', 8);
545 define ('TSQ_TOK_WORD',   16);
546 define ('TSQ_TOK_STARTS_WITH', 32);
547 define ('TSQ_TOK_ENDS_WITH', 64);
548 define ('TSQ_TOK_EXACT', 128);
549 define ('TSQ_TOK_REGEX', 256);
550 define ('TSQ_TOK_REGEX_GLOB', 512);
551 define ('TSQ_TOK_REGEX_PCRE', 1024);
552 define ('TSQ_TOK_REGEX_SQL', 2048);
553 // all bits from word to the last.
554 define ('TSQ_ALLWORDS', (2048*2)-1 - (16-1));
555
556 class TextSearchQuery_Parser 
557 {
558     /*
559      * This is a simple recursive descent parser, based on the following grammar:
560      *
561      * toplist  :
562      *          | toplist expr
563      *          ;
564      *
565      *
566      * list     : expr
567      *          | list expr
568      *          ;
569      *
570      * expr     : atom
571      *          | expr BINOP atom
572      *          ;
573      *
574      * atom     : '(' list ')'
575      *          | NOT atom
576      *          | WORD
577      *          ;
578      *
579      * The terminal tokens are:
580      *
581      *
582      * and|or             BINOP
583      * -|not              NOT
584      * (                  LPAREN
585      * )                  RPAREN
586      * /[^-()\s][^()\s]*  WORD
587      * /"[^"]*"/          WORD
588      * /'[^']*'/          WORD
589      *
590      * ^WORD              STARTS_WITH
591      * WORD*              STARTS_WITH
592      * *WORD              ENDS_WITH
593      * ^WORD$             EXACT
594      */
595
596     function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
597         $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
598         $this->_regex = $regex;
599         $tree = $this->get_list('toplevel');
600         assert($this->lexer->eof());
601         unset($this->lexer);
602         return $tree;
603     }
604     
605     function get_list ($is_toplevel = false) {
606         $list = array();
607
608         // token types we'll accept as words (and thus expr's) for the
609         // purpose of error recovery:
610         $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
611         if ($is_toplevel)
612             $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
613         
614         while ( ($expr = $this->get_expr())
615                 || ($expr = $this->get_word($accept_as_words)) ) {
616             $list[] = $expr;
617         }
618
619         if (!$list) {
620             if ($is_toplevel)
621                 return new TextSearchQuery_node;
622             else
623                 return false;
624         }
625         return new TextSearchQuery_node_and($list);
626     }
627
628     function get_expr () {
629         if ( !($expr = $this->get_atom()) )
630             return false;
631         
632         $savedpos = $this->lexer->tell();
633         while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
634             if ( ! ($right = $this->get_atom()) ) {
635                 break;
636             }
637             
638             if ($op == 'and')
639                 $expr = new TextSearchQuery_node_and(array($expr, $right));
640             else {
641                 assert($op == 'or');
642                 $expr = new TextSearchQuery_node_or(array($expr, $right));
643             }
644
645             $savedpos = $this->lexer->tell();
646         }
647         $this->lexer->seek($savedpos);
648
649         return $expr;
650     }
651     
652
653     function get_atom() {
654         if ($word = $this->get_word(TSQ_ALLWORDS))
655             return $word;
656
657         $savedpos = $this->lexer->tell();
658         if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
659             if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
660                 return $list;
661         }
662         elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
663             if ( ($atom = $this->get_atom()) )
664                 return new TextSearchQuery_node_not($atom);
665         }
666         $this->lexer->seek($savedpos);
667         return false;
668     }
669
670     function get_word($accept = TSQ_ALLWORDS) {
671         foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
672                        "REGEX","REGEX_GLOB","REGEX_PCRE") as $tok) {
673             $const = constant("TSQ_TOK_".$tok);
674             if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
675                 $classname = "TextSearchQuery_node_".strtolower($tok);
676                 return new $classname($word);
677             }
678         }
679         return false;
680     }
681 }
682
683 class TextSearchQuery_Lexer {
684     function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
685         $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
686         $this->pos = 0;
687     }
688
689     function tell() {
690         return $this->pos;
691     }
692
693     function seek($pos) {
694         $this->pos = $pos;
695     }
696
697     function eof() {
698         return $this->pos == count($this->tokens);
699     }
700     
701     /**
702      * TODO: support more regex styles, esp. prefer the forced ones over auto
703      * re: and // stuff
704      */
705     function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
706         $tokens = array();
707         $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
708         while (!empty($buf)) {
709             if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
710                 $val = strtolower($m[1]);
711                 $type = TSQ_TOK_BINOP;
712             }
713             elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
714                 $val = strtolower($m[1]);
715                 $type = TSQ_TOK_NOT;
716             }
717             elseif (preg_match('/^([()])\s*/', $buf, $m)) {
718                 $val = $m[1];
719                 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
720             }
721             // ^word
722             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
723                     and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
724                 $val = $m[1];
725                 $type = TSQ_TOK_STARTS_WITH;
726             }
727             // word*
728             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
729                     and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
730                 $val = $m[1];
731                 $type = TSQ_TOK_STARTS_WITH;
732             }
733             // *word
734             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
735                     and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
736                 $val = $m[1];
737                 $type = TSQ_TOK_ENDS_WITH;
738             }
739             // word$
740             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
741                     and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
742                 $val = $m[1];
743                 $type = TSQ_TOK_ENDS_WITH;
744             }
745             // ^word$
746             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
747                     and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
748                 $val = $m[1];
749                 $type = TSQ_TOK_EXACT;
750             }
751             // "words "
752             elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
753                 $val = str_replace('""', '"', $m[1]);
754                 $type = TSQ_TOK_WORD;
755             }
756             // 'words '
757             elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
758                 $val = str_replace("''", "'", $m[1]);
759                 $type = TSQ_TOK_WORD;
760             }
761             // word
762             elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
763                 $val = $m[1];
764                 $type = TSQ_TOK_WORD;
765             }
766             else {
767                 assert(empty($buf));
768                 break;
769             }
770             $buf = substr($buf, strlen($m[0]));
771
772             /* refine the simple parsing from above: bla*bla, bla?bla, ...
773             if ($regex and $type == TSQ_TOK_WORD) {
774                 if (substr($val,0,1) == "^")
775                     $type = TSQ_TOK_STARTS_WITH;
776                 elseif (substr($val,0,1) == "*")
777                     $type = TSQ_TOK_ENDS_WITH;
778                 elseif (substr($val,-1,1) == "*")
779                     $type = TSQ_TOK_STARTS_WITH;
780             }
781             */
782             $tokens[] = array($type, $val);
783         }
784         return $tokens;
785     }
786     
787     function get($accept) {
788         if ($this->pos >= count($this->tokens))
789             return false;
790         
791         list ($type, $val) = $this->tokens[$this->pos];
792         if (($type & $accept) == 0)
793             return false;
794         
795         $this->pos++;
796         return $val;
797     }
798 }
799
800 // Local Variables:
801 // mode: php
802 // tab-width: 8
803 // c-basic-offset: 4
804 // c-hanging-comment-ender-p: nil
805 // indent-tabs-mode: nil
806 // End:   
807 ?>