1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.24 2007-01-02 13:19:05 rurban Exp $');
3 * A text search query, converting queries to PCRE and SQL matchers.
5 * This represents an enhanced "Google-like" text search query:
7 * <dt> default: case-insensitive glob-style search with special operators OR AND NOT -
9 * <dd> Match strings containing the substring 'wiki', and NOT containing the
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)
24 * The full query syntax, in order of precedence, is roughly:
26 * The unary 'NOT' or '-' operator (they are equivalent) negates the
27 * following search clause.
29 * Search clauses may be joined with the (left-associative) binary operators
30 * 'AND' and 'OR'. (case-insensitive)
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'.)
37 * Search clauses can be grouped with parentheses.
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
45 * Force regex on "re:word" => posix-style, "/word/" => pcre-style
46 * or use regex='glob' to use file wildcard-like matching. (not yet)
48 * The parsed tree is then converted to the needed PCRE (highlight,
49 * simple backends) or SQL functions.
51 * @author: Jeff Dairiki
52 * @author: Reini Urban (case and regex detection, enhanced sql callbacks)
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);
63 class TextSearchQuery {
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
73 function TextSearchQuery($search_query, $case_exact=false, $regex='auto') {
74 if ($regex == 'none' or !$regex)
76 elseif (defined("TSQ_REGEX_".strtoupper($regex)))
77 $this->_regex = constant("TSQ_REGEX_".strtoupper($regex));
79 trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex));
82 $this->_case_exact = $case_exact;
83 if ($regex != 'pcre') {
84 $parser = new TextSearchQuery_Parser;
85 $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex);
86 $this->_optimize(); // broken under certain circumstances: "word -word -word"
87 if (defined("FULLTEXTSEARCH_STOPLIST"))
88 $this->_stoplist = FULLTEXTSEARCH_STOPLIST;
89 else // default stoplist, localizable.
90 $this->_stoplist = _("(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)");
93 $this->_tree = new TextSearchQuery_node_regex_pcre($search_query);
94 if (preg_match("/^\/(.*)\/(\w*)$/", $search_query, $m)) {
95 $this->_tree->word = $m[1];
96 $this->_regex_modifier = $m[2]; // overrides case_exact
101 function _optimize() {
102 $this->_tree = $this->_tree->optimize();
106 * Get a PCRE regexp which matches the query.
108 function asRegexp() {
109 if (!isset($this->_regexp)) {
110 if (!isset($this->_regex_modifier))
111 $this->_regex_modifier = ($this->_case_exact?'':'i').'sS';
113 $this->_regexp = '/' . $this->_tree->regexp() . '/'.$this->_regex_modifier;
115 $this->_regexp = '/^' . $this->_tree->regexp() . '/'.$this->_regex_modifier;
117 return $this->_regexp;
121 * Match query against string.
123 * @param $string string The string to match.
124 * @return boolean True if the string matches the query.
126 function match($string) {
127 return preg_match($this->asRegexp(), $string);
132 * Get a regular expression suitable for highlighting matched words.
134 * This returns a PCRE regular expression which matches any non-negated
137 * @return string The PCRE regexp.
139 function getHighlightRegexp() {
140 if (!isset($this->_hilight_regexp)) {
141 $words = array_unique($this->_tree->highlight_words());
143 $this->_hilight_regexp = false;
145 foreach ($words as $key => $word)
146 $words[$key] = preg_quote($word, '/');
147 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
150 return $this->_hilight_regexp;
154 * Make an SQL clause which matches the query. (deprecated, use makeSqlClause instead)
156 * @param $make_sql_clause_cb WikiCallback
157 * A callback which takes a single word as an argument and
158 * returns an SQL clause which will match exactly those records
159 * containing the word. The word passed to the callback will always
160 * be in all lower case.
162 * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
163 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
164 * How? WikiDB backend method?
168 * function sql_title_match($word) {
169 * return sprintf("LOWER(title) like '%s'",
170 * addslashes($word));
175 * $query = new TextSearchQuery("wiki -page");
176 * $cb = new WikiFunctionCb('sql_title_match');
177 * $sql_clause = $query->makeSqlClause($cb);
179 * This will result in $sql_clause containing something like
180 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
182 * @return string The SQL clause.
184 function makeSqlClause($sql_clause_cb) {
185 $this->_sql_clause_cb = $sql_clause_cb;
186 return $this->_sql_clause($this->_tree);
188 // deprecated: use _sql_clause_obj now.
189 function _sql_clause($node) {
191 case 'WORD': // word => %word%
192 return $this->_sql_clause_cb->call($node->word);
194 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
197 $subclauses = array();
198 foreach ($node->leaves as $leaf)
199 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
200 return join(" $node->op ", $subclauses);
202 assert($node->op == 'VOID');
207 /** Get away with the callback and use a db-specific search class instead.
208 * @see WikiDB_backend_PearDB_search
210 function makeSqlClauseObj(&$sql_search_cb) {
211 $this->_sql_clause_cb = $sql_search_cb;
212 return $this->_sql_clause_obj($this->_tree);
215 function _sql_clause_obj($node) {
218 return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
221 $subclauses = array();
222 foreach ($node->leaves as $leaf)
223 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
224 return join(" $node->op ", $subclauses);
230 return $this->_sql_clause_cb->call($node);
235 postgresql tsearch2 uses no WHERE operators, just & | and ! in the searchstring
237 function makeTsearch2SqlClauseObj(&$sql_search_cb) {
238 $this->_sql_clause_cb = $sql_search_cb;
239 return $this->_Tsearch2Sql_clause_obj($this->_tree);
242 function _Tsearch2Sql_clause_obj($node) {
243 // TODO: "such a phrase"
246 return "!" . $node->leaves[0];
248 $subclauses = array();
249 foreach ($node->leaves as $leaf)
250 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
251 return join("&", $subclauses);
253 $subclauses = array();
254 foreach ($node->leaves as $leaf)
255 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
256 return join("|", $subclauses);
262 return $this->_sql_clause_cb->call($node);
266 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
269 * Get printable representation of the parse tree.
271 * This is for debugging only.
272 * @return string Printable parse tree.
274 function asString() {
275 return $this->_as_string($this->_tree);
278 function _as_string($node, $indent = '') {
281 return $indent . "WORD: $node->word";
283 return $indent . "VOID";
285 return $indent . "ALL";
287 $lines = array($indent . $node->op . ":");
289 foreach ($node->leaves as $leaf)
290 $lines[] = $this->_as_string($leaf, $indent);
291 return join("\n", $lines);
297 * This is a TextSearchQuery which matches nothing.
299 class NullTextSearchQuery extends TextSearchQuery {
301 * Create a new query.
303 * @see TextSearchQuery
305 function NullTextSearchQuery() {}
306 function asRegexp() { return '/^(?!a)a/x'; }
307 function match($string) { return false; }
308 function getHighlightRegexp() { return ""; }
309 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
310 function asString() { return "NullTextSearchQuery"; }
314 * A simple algebraic matcher for numeric attributes.
315 * NumericSearchQuery can do ("population < 20000 and area > 1000000", array("population", "area"))
316 * ->match(array('population' => 100000, 'area' => 10000000))
318 * Supports all mathematical PHP comparison operators, plus ':=' for equality.
319 * "(x < 2000000 and x >= 10000) or (x >= 100 and x < 2000)"
320 * "x := 100000" is the same as "x == 100000"
322 * Since this is basic numerics only, we simply try to get away with
323 * replacing the variable values at the right positions and do an eval then.
325 * @package NumericSearchQuery
326 * @author Reini Urban
327 * @see TextSearchQuery @see SemanticAttributeSearchQuery
329 class NumericSearchQuery
330 extends TextSearchQuery
333 * Create a new query.
334 * NumericSearchQuery("population > 20000 or population < 200", "population")
335 * NumericSearchQuery("population < 20000 and area > 1000000", array("population", "area"))
338 * @param $search_query string A numerical query with placeholders as variable.
339 * @param $placeholders array or string All placeholders in the query must be defined
340 * here, and will be replaced by the matcher.
342 function NumericSearchQuery($search_query, $placeholders) {
343 // FIXME: add some basic security checks against user input
344 $this->_query = $search_query;
345 $this->_placeholders = $placeholders;
347 // we also allow the M_ constants
348 $this->_allowed_functions = explode(':','abs:acos:acosh:asin:asinh:atan2:atan:atanh:base_convert:bindec:ceil:cos:cosh:decbin:dechex:decoct:deg2rad:exp:expm1:floor:fmod:getrandmax:hexdec:hypot:is_finite:is_infinite:is_nan:lcg_value:log10:log1p:log:max:min:mt_getrandmax:mt_rand:mt_srand:octdec:pi:pow:rad2deg:rand:round:sin:sinh:sqrt:srand:tan:tanh');
349 $this->_allowed_operators = explode(',', '<,<=,>,>=,==,!=,*,+,/,(,),-');
351 // This is a speciality: := looks like the attribute definition and is
352 // therefore a dummy check for this definition.
353 $this->_query = preg_replace("/\b:=\b/", "==", $this->_query);
354 $this->_query = $this->check($this->_query);
358 * Check the symbolic definition query against unwanted functions and characters.
359 * "population < 20000 and area > 1000000"
361 function check ($query) {
362 while (preg_match("/\A\b(\w.+)\s*\(\b\Z/", $query, $m)) {
363 if (!in_array($m[1],$this->_allowed_functions)) {
364 trigger_error("Illegal function in query: ".$m[1], E_USER_WARNING);
368 // TODO: check for illegal operators. which are no placeholders and functions.
370 // Detect illegal characters
371 $c = "/([^\d\w.,\s".preg_quote(join("",$this->_allowed_operators),"/")."])/";
372 if (preg_match($c, $query, $m)) {
373 trigger_error("Illegal character in query: ".$m[1], E_USER_WARNING);
380 * Check the bound, numeric only query against unwanted functions and sideeffects.
381 * "4560000 < 20000 and 1456022 > 1000000"
383 function _live_check ($query) {
388 * Strip non-numeric chars from the variable (as the groupseperator) and replace
389 * it in the symbolic query for evaluation.
392 * @param $value number A numerical value: integer, float or string.
393 * @param $x string The variable name to be replaced in the query.
396 function bind($value, $x) {
397 // TODO: check is_number, is_float, is_integer and do casting
398 $value = preg_replace("/[^-+0123456789.]/", "", $value);
399 //$c = "/\b".preg_quote($x,"/")."\b/";
400 $result = preg_replace("/\b".preg_quote($x,"/")."\b/", $value, $this->_query);
401 // FIXME: do again a final check. now only numbers and some operators are allowed.
402 return $this->_live_check($result);
406 * We can match against a single variable or against a hash of variables.
409 * @param $search_query string A numerical query with placeholders as variable.
410 * @param $variable array or string Must have the same structure as placeholders in the definition.
413 function match($variable) {
414 if (!is_array($this->_placeholders)) {
415 if (is_array($variable))
416 trigger_error("Not enough placeholders in NumericSearchQuery() defined.\n"
417 ."Require ".count($variables)." variables to be defined.");
418 $search = $this->bind($variable, $this->_placeholders);
420 if (count($variables) <> count($this->_placeholders))
421 trigger_error("Not matching number of variables and placeholders in NumericSearchQuery->match.\n"
422 ."Require ".count($variables)." variables to be bound");
423 foreach ($this->_placeholders as $x) {
424 if (!isset($variable[$x]))
425 trigger_error("Required NumericSearchQuery->match variable $x not defined.");
426 $search = $this->bind($variable[$x], $x);
429 eval("\$result = (boolean)($search);");
435 ////////////////////////////////////////////////////////////////
437 // Remaining classes are private.
439 ////////////////////////////////////////////////////////////////
441 * Virtual base class for nodes in a TextSearchQuery parse tree.
443 * Also serves as a 'VOID' (contentless) node.
445 class TextSearchQuery_node
450 * Optimize this node.
451 * @return object Optimized node.
453 function optimize() {
458 * @return regexp matching this node.
465 * @param bool True if this node has been negated (higher in the parse tree.)
466 * @return array A list of all non-negated words contained by this node.
468 function highlight_words($negated = false) {
472 function sql() { return $this->word; }
478 class TextSearchQuery_node_word
479 extends TextSearchQuery_node
483 function TextSearchQuery_node_word($word) {
487 return '(?=.*' . preg_quote($this->word, '/') . ')';
489 function highlight_words ($negated = false) {
490 return $negated ? array() : array($this->word);
492 function _sql_quote() {
493 $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
494 return $GLOBALS['request']->_dbi->qstr($word);
496 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
499 class TextSearchQuery_node_all
500 extends TextSearchQuery_node {
502 function regexp() { return '(?=.*)'; }
503 function sql() { return '%'; }
505 class TextSearchQuery_node_starts_with
506 extends TextSearchQuery_node_word {
507 var $op = "STARTS_WITH";
508 function regexp() { return '(?=.*\b' . preg_quote($this->word, '/') . ')'; }
509 function sql () { return $this->_sql_quote($this->word).'%'; }
512 class TextSearchQuery_node_ends_with
513 extends TextSearchQuery_node_word {
514 var $op = "ENDS_WITH";
515 function regexp() { return '(?=.*' . preg_quote($this->word, '/') . '\b)'; }
516 function sql () { return '%'.$this->_sql_quote($this->word); }
519 class TextSearchQuery_node_exact
520 extends TextSearchQuery_node_word {
522 function regexp() { return '(?=\b' . preg_quote($this->word, '/') . '\b)'; }
523 function sql () { return $this->_sql_squote($this->word); }
526 class TextSearchQuery_node_regex // posix regex. FIXME!
527 extends TextSearchQuery_node_word {
528 var $op = "REGEX"; // using REGEXP or ~ extension
529 function regexp() { return '(?=.*\b' . $this->word . '\b)'; }
530 function sql () { return $this->_sql_quote($this->word); }
533 class TextSearchQuery_node_regex_glob
534 extends TextSearchQuery_node_regex {
535 var $op = "REGEX_GLOB";
536 function regexp() { return '(?=.*\b' . glob_to_pcre($this->word) . '\b)'; }
539 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
540 extends TextSearchQuery_node_regex {
541 var $op = "REGEX_PCRE";
542 function regexp() { return $this->word; }
545 class TextSearchQuery_node_regex_sql
546 extends TextSearchQuery_node_regex {
547 var $op = "REGEX_SQL"; // using LIKE
548 function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
549 function sql() { return $this->word; }
555 class TextSearchQuery_node_not
556 extends TextSearchQuery_node
560 function TextSearchQuery_node_not($leaf) {
561 $this->leaves = array($leaf);
564 function optimize() {
565 $leaf = &$this->leaves[0];
566 $leaf = $leaf->optimize();
567 if ($leaf->op == 'NOT')
568 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
573 $leaf = &$this->leaves[0];
574 return '(?!' . $leaf->regexp() . ')';
577 function highlight_words ($negated = false) {
578 return $this->leaves[0]->highlight_words(!$negated);
583 * Virtual base class for 'AND' and 'OR conjoins.
585 class TextSearchQuery_node_binop
586 extends TextSearchQuery_node
588 function TextSearchQuery_node_binop($leaves) {
589 $this->leaves = $leaves;
592 function _flatten() {
593 // This flattens e.g. (AND (AND a b) (OR c d) e)
594 // to (AND a b e (OR c d))
596 foreach ($this->leaves as $leaf) {
597 $leaf = $leaf->optimize();
598 if ($this->op == $leaf->op)
599 $flat = array_merge($flat, $leaf->leaves);
603 $this->leaves = $flat;
606 function optimize() {
608 assert(!empty($this->leaves));
609 if (count($this->leaves) == 1)
610 return $this->leaves[0]; // (AND x) -> x
614 function highlight_words($negated = false) {
616 foreach ($this->leaves as $leaf)
617 array_splice($words,0,0,
618 $leaf->highlight_words($negated));
624 * A (possibly multi-argument) 'AND' conjoin.
626 class TextSearchQuery_node_and
627 extends TextSearchQuery_node_binop
631 function optimize() {
634 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
635 // Since OR's are more efficient for regexp matching:
636 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
638 // Suck out the negated leaves.
640 foreach ($this->leaves as $key => $leaf) {
641 if ($leaf->op == 'NOT') {
642 $nots[] = $leaf->leaves[0];
643 unset($this->leaves[$key]);
647 // Combine the negated leaves into a single negated or.
649 $node = ( new TextSearchQuery_node_not
650 (new TextSearchQuery_node_or($nots)) );
651 array_unshift($this->leaves, $node->optimize());
654 assert(!empty($this->leaves));
655 if (count($this->leaves) == 1)
656 return $this->leaves[0]; // (AND x) -> x
661 * Either we need all combinations of all words to be position independent,
662 * or we have to use multiple match calls for each AND
663 * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
667 foreach ($this->leaves as $leaf)
668 $regexp .= $leaf->regexp();
674 * A (possibly multi-argument) 'OR' conjoin.
676 class TextSearchQuery_node_or
677 extends TextSearchQuery_node_binop
682 // We will combine any of our direct descendents which are WORDs
683 // into a single (?=.*(?:word1|word2|...)) regexp.
688 foreach ($this->leaves as $leaf) {
689 if ($leaf->op == 'WORD')
690 $words[] = preg_quote($leaf->word, '/');
692 $regexps[] = $leaf->regexp();
696 array_unshift($regexps,
697 '(?=.*' . $this->_join($words) . ')');
699 return $this->_join($regexps);
702 function _join($regexps) {
703 assert(count($regexps) > 0);
705 if (count($regexps) > 1)
706 return '(?:' . join('|', $regexps) . ')';
713 ////////////////////////////////////////////////////////////////
716 // op's (and, or, not) are forced to lowercase in the tokenizer.
718 ////////////////////////////////////////////////////////////////
719 define ('TSQ_TOK_BINOP', 1);
720 define ('TSQ_TOK_NOT', 2);
721 define ('TSQ_TOK_LPAREN', 4);
722 define ('TSQ_TOK_RPAREN', 8);
723 define ('TSQ_TOK_WORD', 16);
724 define ('TSQ_TOK_STARTS_WITH', 32);
725 define ('TSQ_TOK_ENDS_WITH', 64);
726 define ('TSQ_TOK_EXACT', 128);
727 define ('TSQ_TOK_REGEX', 256);
728 define ('TSQ_TOK_REGEX_GLOB', 512);
729 define ('TSQ_TOK_REGEX_PCRE', 1024);
730 define ('TSQ_TOK_REGEX_SQL', 2048);
731 define ('TSQ_TOK_ALL', 4096);
732 // all bits from word to the last.
733 define ('TSQ_ALLWORDS', (4096*2)-1 - (16-1));
735 class TextSearchQuery_Parser
738 * This is a simple recursive descent parser, based on the following grammar:
753 * atom : '(' list ')'
758 * The terminal tokens are:
765 * /[^-()\s][^()\s]* WORD
776 function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
777 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
778 $this->_regex = $regex;
779 $tree = $this->get_list('toplevel');
780 assert($this->lexer->eof());
785 function get_list ($is_toplevel = false) {
788 // token types we'll accept as words (and thus expr's) for the
789 // purpose of error recovery:
790 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
792 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
794 while ( ($expr = $this->get_expr())
795 || ($expr = $this->get_word($accept_as_words)) ) {
801 return new TextSearchQuery_node;
805 return new TextSearchQuery_node_and($list);
808 function get_expr () {
809 if ( !($expr = $this->get_atom()) )
812 $savedpos = $this->lexer->tell();
813 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
814 if ( ! ($right = $this->get_atom()) ) {
819 $expr = new TextSearchQuery_node_and(array($expr, $right));
822 $expr = new TextSearchQuery_node_or(array($expr, $right));
825 $savedpos = $this->lexer->tell();
827 $this->lexer->seek($savedpos);
833 function get_atom() {
834 if ($word = $this->get_word(TSQ_ALLWORDS))
837 $savedpos = $this->lexer->tell();
838 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
839 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
842 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
843 if ( ($atom = $this->get_atom()) )
844 return new TextSearchQuery_node_not($atom);
846 $this->lexer->seek($savedpos);
850 function get_word($accept = TSQ_ALLWORDS) {
851 foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
852 "REGEX","REGEX_GLOB","REGEX_PCRE","ALL") as $tok) {
853 $const = constant("TSQ_TOK_".$tok);
854 if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
855 $classname = "TextSearchQuery_node_".strtolower($tok);
856 return new $classname($word);
863 class TextSearchQuery_Lexer {
864 function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
865 $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
873 function seek($pos) {
878 return $this->pos == count($this->tokens);
882 * TODO: support more regex styles, esp. prefer the forced ones over auto
885 function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
887 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
888 while (!empty($buf)) {
889 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
890 $val = strtolower($m[1]);
891 $type = TSQ_TOK_BINOP;
893 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
894 $val = strtolower($m[1]);
897 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
899 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
903 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
904 and preg_match('/^\*\s*/', $buf, $m)) {
909 elseif ($regex & (TSQ_REGEX_PCRE)
910 and preg_match('/^\.\*\s*/', $buf, $m)) {
915 elseif ($regex & (TSQ_REGEX_SQL)
916 and preg_match('/^%\s*/', $buf, $m)) {
922 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
923 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
925 $type = TSQ_TOK_STARTS_WITH;
928 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
929 and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
931 $type = TSQ_TOK_STARTS_WITH;
934 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
935 and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
937 $type = TSQ_TOK_ENDS_WITH;
940 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
941 and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
943 $type = TSQ_TOK_ENDS_WITH;
946 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
947 and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
949 $type = TSQ_TOK_EXACT;
953 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
954 $val = str_replace('""', '"', $m[1]);
955 $type = TSQ_TOK_WORD;
958 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
959 $val = str_replace("''", "'", $m[1]);
960 $type = TSQ_TOK_WORD;
963 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
965 $type = TSQ_TOK_WORD;
971 $buf = substr($buf, strlen($m[0]));
973 /* refine the simple parsing from above: bla*bla, bla?bla, ...
974 if ($regex and $type == TSQ_TOK_WORD) {
975 if (substr($val,0,1) == "^")
976 $type = TSQ_TOK_STARTS_WITH;
977 elseif (substr($val,0,1) == "*")
978 $type = TSQ_TOK_ENDS_WITH;
979 elseif (substr($val,-1,1) == "*")
980 $type = TSQ_TOK_STARTS_WITH;
983 $tokens[] = array($type, $val);
988 function get($accept) {
989 if ($this->pos >= count($this->tokens))
992 list ($type, $val) = $this->tokens[$this->pos];
993 if (($type & $accept) == 0)
1001 // $Log: not supported by cvs2svn $
1002 // Revision 1.23 2006/04/13 19:30:44 rurban
1003 // make TextSearchQuery->_stoplist localizable and overridable within config.ini
1009 // c-basic-offset: 4
1010 // c-hanging-comment-ender-p: nil
1011 // indent-tabs-mode: nil