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