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(phrase)
17 * <dd> "^word" => STARTS_WITH(phrase)
18 * <dd> "word$" => ENDS_WITH(phrase)
19 * <dd> "^word" ... => STARTS_WITH(word)
20 * <dd> "word$" ... => ENDS_WITH(word)
21 * <dd> "word*" => STARTS_WITH(word)
22 * <dd> "*word" => ENDS_WITH(word)
23 * <dd> "/^word.* /" => REGEX(^word.*)
24 * <dd> "word*word" => REGEX(word.*word)
27 * The full query syntax, in order of precedence, is roughly:
29 * The unary 'NOT' or '-' operator (they are equivalent) negates the
30 * following search clause.
32 * Search clauses may be joined with the (left-associative) binary operators
33 * 'AND' and 'OR'. (case-insensitive)
35 * Two adjoining search clauses are joined with an implicit 'AND'. This has
36 * lower precedence than either an explicit 'AND' or 'OR', so "a b OR c"
37 * parses as "a AND ( b OR c )", while "a AND b OR c" parses as
38 * "( a AND b ) OR c" (due to the left-associativity of 'AND' and 'OR'.)
40 * Search clauses can be grouped with parentheses.
42 * Phrases (or other things which don't look like words) can be forced to
43 * be interpreted as words by quoting them, either with single (') or double (")
44 * quotes. If you wan't to include the quote character within a quoted string,
45 * double-up on the quote character: 'I''m hungry' is equivalent to
48 * Force regex on "re:word" => posix-style, "/word/" => pcre-style
49 * or use regex='glob' to use file wildcard-like matching. (not yet)
51 * The parsed tree is then converted to the needed PCRE (highlight,
52 * simple backends) or SQL functions.
54 * @author: Jeff Dairiki
55 * @author: Reini Urban (case and regex detection, enhanced sql callbacks)
58 // regex-style: 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
59 define ('TSQ_REGEX_NONE', 0);
60 define ('TSQ_REGEX_AUTO', 1);
61 define ('TSQ_REGEX_POSIX', 2);
62 define ('TSQ_REGEX_GLOB', 4);
63 define ('TSQ_REGEX_PCRE', 8);
64 define ('TSQ_REGEX_SQL', 16);
66 define ('TSQ_TOK_VOID', 0);
67 define ('TSQ_TOK_BINOP', 1);
68 define ('TSQ_TOK_NOT', 2);
69 define ('TSQ_TOK_LPAREN', 4);
70 define ('TSQ_TOK_RPAREN', 8);
71 define ('TSQ_TOK_WORD', 16);
72 define ('TSQ_TOK_STARTS_WITH', 32);
73 define ('TSQ_TOK_ENDS_WITH', 64);
74 define ('TSQ_TOK_EXACT', 128);
75 define ('TSQ_TOK_REGEX', 256);
76 define ('TSQ_TOK_REGEX_GLOB', 512);
77 define ('TSQ_TOK_REGEX_PCRE', 1024);
78 define ('TSQ_TOK_REGEX_SQL', 2048);
79 define ('TSQ_TOK_ALL', 4096);
80 // all bits from word to the last.
81 define ('TSQ_ALLWORDS', (4096 * 2) - 1 - (16 - 1));
85 private $sql_clause_cb;
91 * @param $search_query string The query. Syntax is as described above.
92 * Note that an empty $search_query will match anything.
93 * @param $case_exact boolean
94 * @param $regex string one of 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
95 * @see TextSearchQuery
97 function TextSearchQuery($search_query, $case_exact = false, $regex = 'auto')
99 if ($regex == 'none' or !$regex) {
101 } elseif (defined("TSQ_REGEX_" . strtoupper($regex))) {
102 $this->_regex = constant("TSQ_REGEX_" . strtoupper($regex));
104 trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex));
107 $this->_regex_modifier = ($case_exact ? '' : 'i') . 'sS';
108 $this->_case_exact = $case_exact;
109 if ($regex != 'pcre') {
110 $parser = new TextSearchQuery_Parser;
111 $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex);
112 $this->optimize(); // broken under certain circumstances: "word -word -word"
113 if (defined("FULLTEXTSEARCH_STOPLIST"))
114 $this->_stoplist = FULLTEXTSEARCH_STOPLIST;
115 else // default stoplist, localizable.
116 $this->_stoplist = _("(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)");
118 $this->_tree = new TextSearchQuery_node_regex_pcre($search_query);
119 if (preg_match("/^\/(.*)\/(\w*)$/", $search_query, $m)) {
120 $this->_tree->word = $m[1];
121 $this->_regex_modifier = $m[2]; // overrides case_exact
131 private function optimize()
133 $this->_tree = $this->_tree->optimize();
137 * Get a PCRE regexp which matches the query.
141 if (!isset($this->_regexp)) {
142 if (!isset($this->_regex_modifier))
143 $this->_regex_modifier = ($this->_case_exact ? '' : 'i') . 'sS';
145 $this->_regexp = '/' . $this->_tree->regexp() . '/' . $this->_regex_modifier;
147 $this->_regexp = '/^' . $this->_tree->regexp() . '/' . $this->_regex_modifier;
149 return $this->_regexp;
153 * Match query against string.
154 * EXACT ("Term") ignores the case_exact setting.
156 * @param $string string The string to match.
157 * @return boolean True if the string matches the query.
159 function match($string)
161 if ($this->_tree->_op == TSQ_TOK_ALL) return true;
162 if ($this->_tree->_op == TSQ_TOK_EXACT) return $this->_tree->word == $string;
163 return preg_match($this->asRegexp(), $string);
166 /* How good does it match? Returns a number */
167 function score($string)
171 foreach (array_unique($this->_tree->highlight_words()) as $word) {
172 if ($nummatch = preg_match_all("/" . preg_quote($word, '/') . "/" .
173 $this->_regex_modifier,
176 $score += ($i-- * $nummatch);
178 return min(1.0, $score / 10.0);
182 * Get a regular expression suitable for highlighting matched words.
184 * This returns a PCRE regular expression which matches any non-negated
187 * @return string The PCRE regexp.
189 function getHighlightRegexp()
191 if (!isset($this->_hilight_regexp)) {
192 $words = array_unique($this->_tree->highlight_words());
194 $this->_hilight_regexp = false;
196 foreach ($words as $key => $word)
197 $words[$key] = preg_quote($word, '/');
198 $this->_hilight_regexp = '(?' . ($this->_case_exact ? '' : 'i') . ':'
199 . join('|', $words) . ')';
202 return $this->_hilight_regexp;
205 /** Get away with the callback and use a db-specific search class instead.
206 * @see WikiDB_backend_PearDB_search
208 function makeSqlClauseObj(&$sql_search_cb)
210 $this->sql_clause_cb = $sql_search_cb;
211 return $this->sql_clause_obj($this->_tree);
214 private function sql_clause_obj($node)
216 switch ($node->_op) {
218 return "NOT (" . $this->sql_clause_cb->call($node->leaves[0]) . ")";
220 $subclauses = array();
221 foreach ($node->leaves as $leaf)
222 $subclauses[] = "(" . $this->sql_clause_obj($leaf) . ")";
223 return join(" $node->op ", $subclauses);
229 return $this->sql_clause_cb->call($node);
234 postgresql tsearch2 uses no WHERE operators, just & | and ! in the searchstring
236 function makeTsearch2SqlClauseObj(&$sql_search_cb)
238 $this->sql_clause_cb = $sql_search_cb;
239 return $this->Tsearch2Sql_clause_obj($this->_tree);
242 private function Tsearch2Sql_clause_obj($node)
244 // TODO: "such a phrase"
245 switch ($node->_op) {
247 return "!" . $node->leaves[0];
249 $subclauses = array();
250 foreach ($node->leaves as $leaf)
251 $subclauses[] = $this->Tsearch2Sql_clause_obj($leaf);
252 return join($node->_op == 'OR' ? "|" : "&", $subclauses);
258 return $this->sql_clause_cb->call($node);
264 return '%' . $this->sql_quote($this->word) . '%';
268 * Get printable representation of the parse tree.
270 * This is for debugging only.
271 * @return string Printable parse tree.
275 return $this->as_string($this->_tree);
278 private function as_string($node, $indent = '')
280 switch ($node->_op) {
282 return $indent . "WORD: $node->word";
284 return $indent . "VOID";
286 return $indent . "ALL";
288 $lines = array($indent . $node->op . ":");
290 foreach ($node->leaves as $leaf)
291 $lines[] = $this->as_string($leaf, $indent);
292 return join("\n", $lines);
298 * This is a TextSearchQuery which matches nothing.
300 class NullTextSearchQuery extends TextSearchQuery
303 * Create a new query.
305 * @see TextSearchQuery
307 function __construct()
316 function match($string)
321 function getHighlightRegexp()
328 return "NullTextSearchQuery";
333 * A simple algebraic matcher for numeric attributes.
334 * NumericSearchQuery can do ("population < 20000 and area > 1000000", array("population", "area"))
335 * ->match(array('population' => 100000, 'area' => 10000000))
337 * Supports all mathematical PHP comparison operators, plus ':=' for equality.
338 * "(x < 2000000 and x >= 10000) or (x >= 100 and x < 2000)"
339 * "x := 100000" is the same as "x == 100000"
341 * Since this is basic numerics only, we simply try to get away with
342 * replacing the variable values at the right positions and do an eval then.
344 * @package NumericSearchQuery
345 * @author Reini Urban
346 * @see SemanticAttributeSearchQuery
348 class NumericSearchQuery
351 protected $workquery;
354 * Create a new query.
355 * NumericSearchQuery("population > 20000 or population < 200", "population")
356 * NumericSearchQuery("population < 20000 and area > 1000000", array("population", "area"))
358 * With a single variable it is easy: The valid name must be matched elsewhere, just
359 * replace the given number in match in the query.
362 * With matching a struct we need strict names, no * as name is allowed.
363 * So always when the placeholder is an array, the names of the target struct must match
364 * and all vars be defined. Use the method can_match($struct) therefore.
366 * @param $search_query string A numerical query with placeholders as variable.
367 * @param $placeholders array or string All placeholders in the query must be defined
368 * here, and will be replaced by the matcher.
370 public function NumericSearchQuery($search_query, $placeholders)
372 // added some basic security checks against user input
373 $this->_query = $search_query;
374 $this->_placeholders = $placeholders;
376 // we should also allow the M_ constants
377 $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');
378 $this->_allowed_operators = explode(',', '-,<,<=,>,>=,==,!=,*,+,/,(,),%,and,or,xor,<<,>>,===,!==,&,^,|,&&,||');
379 $this->_parser_check = array();
380 // check should be fast, so make a hash
381 foreach ($this->_allowed_functions as $f)
382 $this->_parser_check[$f] = 1;
383 foreach ($this->_allowed_operators as $f)
384 $this->_parser_check[$f] = 1;
385 if (is_array($placeholders))
386 foreach ($placeholders as $f)
387 $this->_parser_check[$f] = 1;
388 else $this->_parser_check[$placeholders] = 1;
390 // This is a speciality: := looks like the attribute definition and is
391 // therefore a dummy check for this definition.
392 // php-4.2.2 has a problem with /\b:=\b/ matching "population := 1223400"
393 $this->_query = preg_replace("/:=/", "==", $this->_query);
394 $this->_query = $this->check_query($this->_query);
403 * Check the symbolic definition query against unwanted functions and characters.
404 * "population < 20000 and area > 1000000" vs
405 * "area > 1000000 and mail($me,file("/etc/passwd"),...)"
407 function check_query($query)
409 $tmp = $query; // check for all function calls, in case the tokenizer is not available.
410 while (preg_match("/([a-z][a-z0-9]+)\s*\((.*)$/i", $tmp, $m)) {
411 if (!in_array($m[1], $this->_allowed_functions)
412 and !in_array($m[1], $this->_allowed_operators)
414 trigger_error("Illegal function in query: " . $m[1], E_USER_WARNING);
420 // Strictly check for illegal functions and operators, which are no placeholders.
421 $parsed = token_get_all("<?$query?>");
422 foreach ($parsed as $x) { // flat, non-recursive array
423 if (is_string($x) and !isset($this->_parser_check[$x])) {
424 // single char op or name
425 trigger_error("Illegal string or operator in query: \"$x\"", E_USER_WARNING);
427 } elseif (is_array($x)) {
428 $n = token_name($x[0]);
429 if ($n == 'T_OPEN_TAG' or $n == 'T_WHITESPACE'
430 or $n == 'T_CLOSE_TAG' or $n == 'T_LNUMBER'
431 or $n == 'T_CONST' or $n == 'T_DNUMBER'
433 if ($n == 'T_VARIABLE') { // but we do allow consts
434 trigger_error("Illegal variable in query: \"$x[1]\"", E_USER_WARNING);
437 if (is_string($x[1]) and !isset($this->_parser_check[$x[1]])) {
438 // multi-char char op or name
439 trigger_error("Illegal $n in query: \"$x[1]\"", E_USER_WARNING);
448 * Check the bound, numeric-only query against unwanted functions and sideeffects.
449 * "4560000 < 20000 and 1456022 > 1000000"
451 private function live_check()
453 // TODO: check $this->_workquery again?
454 return !empty($this->workquery);
458 * A numeric query can only operate with predefined variables. "x < 0 and y < 1"
460 * @return array The names as array of strings. => ('x', 'y') the placeholders.
464 if (is_array($this->_placeholders)) return $this->_placeholders;
465 else return array($this->_placeholders);
469 * Strip non-numeric chars from the variable (as the group separator) and replace
470 * it in the symbolic query for evaluation.
472 * @param $value number A numerical value: integer, float or string.
473 * @param $x string The variable name to be replaced in the query.
476 private function bind($value, $x)
478 // TODO: check is_number, is_float, is_integer and do casting
479 $this->bound[] = array('linkname' => $x,
480 'linkvalue' => $value);
481 $value = preg_replace("/[^-+0123456789.,]/", "", $value);
482 //$c = "/\b".preg_quote($x,"/")."\b/";
483 $this->workquery = preg_replace("/\b" . preg_quote($x, "/") . "\b/", $value, $this->workquery);
484 // FIXME: do again a final check. now only numbers and some operators are allowed.
485 return $this->workquery;
488 /* array of successfully bound vars, and in case of success, the resulting vars
490 private function bound()
496 * With an array of placeholders we need a hash to check against, if all required names are given.
497 * Purpose: Be silent about missing vars, just return false.
499 * @param string $variables string or hash of name => value The keys must satisfy all placeholders in the definition.
500 * We want the full hash and not just the keys because a hash check is faster than the array of keys check.
503 public function can_match(&$variables)
505 if (empty($this->_query))
507 $p =& $this->_placeholders;
508 if (!is_array($variables) and !is_array($p))
509 return $variables == $p; // This was easy.
510 // Check if all placeholders have definitions. can be overdefined but not underdefined.
512 if (!isset($variables[$p])) return false;
515 if (!isset($variables[$x])) return false;
522 * We can match against a single variable or against a hash of variables.
523 * With one placeholder we need just a number.
524 * With an array of placeholders we need a hash.
526 * @param $variable number or array of name => value The keys must satisfy all placeholders in the definition.
529 public function match(&$variable)
531 $p =& $this->_placeholders;
532 $this->workquery = $this->_query;
534 if (is_array($variable)) { // which var to match? we cannot decide this here
535 if (!isset($variable[$p]))
536 trigger_error("Required NumericSearchQuery->match variable $p not defined.", E_USER_ERROR);
537 $this->bind($variable[$p], $p);
539 $this->bind($variable, $p);
543 if (!isset($variable[$x]))
544 trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR);
545 $this->bind($variable[$x], $x);
548 if (!$this->live_check()) // check returned an error
550 $search = $this->workquery;
552 //if (DEBUG & _DEBUG_VERBOSE)
553 // trigger_error("\$result = (boolean)($search);", E_USER_NOTICE);
554 // We might have a numerical problem:
555 // php-4.2.2 eval'ed as module: "9.636e+08 > 1000" false;
556 // php-5.1.2 cgi true, 4.2.2 cgi true
557 eval("\$result = (boolean)($search);");
558 if ($result and is_array($p)) {
559 return $this->bound();
565 ////////////////////////////////////////////////////////////////
567 // Remaining classes are private.
569 ////////////////////////////////////////////////////////////////
571 * Virtual base class for nodes in a TextSearchQuery parse tree.
573 * Also serves as a 'VOID' (contentless) node.
575 class TextSearchQuery_node
582 * Optimize this node.
583 * @return object Optimized node.
591 * @return string regexp matching this node.
599 * @param bool $negated True if this node has been negated (higher in the parse tree.)
600 * @return array A list of all non-negated words contained by this node.
602 function highlight_words($negated = false)
615 $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
616 return $request->_dbi->_backend->qstr($word);
621 * A word. Exact or substring?
623 class TextSearchQuery_node_word
624 extends TextSearchQuery_node
627 public $_op = TSQ_TOK_WORD;
629 function __construct($word)
636 return '(?=.*\b' . preg_quote($this->word, '/') . '\b)';
639 function highlight_words($negated = false)
641 return $negated ? array() : array($this->word);
646 return '%' . $this->sql_quote($this->word) . '%';
650 class TextSearchQuery_node_all
651 extends TextSearchQuery_node
654 public $_op = TSQ_TOK_ALL;
667 class TextSearchQuery_node_starts_with
668 extends TextSearchQuery_node_word
670 public $op = "STARTS_WITH";
671 public $_op = TSQ_TOK_STARTS_WITH;
675 return '(?=.*\b' . preg_quote($this->word, '/') . ')';
680 return $this->sql_quote($this->word) . '%';
684 // ^word: full phrase starts with
685 class TextSearchQuery_phrase_starts_with
686 extends TextSearchQuery_node_starts_with
690 return '(?=^' . preg_quote($this->word, '/') . ')';
694 class TextSearchQuery_node_ends_with
695 extends TextSearchQuery_node_word
697 public $op = "ENDS_WITH";
698 public $_op = TSQ_TOK_ENDS_WITH;
702 return '(?=.*' . preg_quote($this->word, '/') . '\b)';
707 return '%' . $this->sql_quote($this->word);
711 // word$: full phrase ends with
712 class TextSearchQuery_phrase_ends_with
713 extends TextSearchQuery_node_ends_with
717 return '(?=' . preg_quote($this->word, '/') . '$)';
721 class TextSearchQuery_node_exact
722 extends TextSearchQuery_node_word
724 public $op = "EXACT";
725 public $_op = TSQ_TOK_EXACT;
729 return '(?=\b' . preg_quote($this->word, '/') . '\b)';
734 return $this->_sql_squote($this->word);
738 class TextSearchQuery_node_regex // posix regex. FIXME!
739 extends TextSearchQuery_node_word
741 public $op = "REGEX"; // using REGEXP or ~ extension
742 public $_op = TSQ_TOK_REGEX;
746 return '(?=.*\b' . $this->word . '\b)';
751 return $this->sql_quote($this->word);
755 class TextSearchQuery_node_regex_glob
756 extends TextSearchQuery_node_regex
758 public $op = "REGEX_GLOB";
759 public $_op = TSQ_TOK_REGEX_GLOB;
763 return '(?=.*\b' . glob_to_pcre($this->word) . '\b)';
767 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
768 extends TextSearchQuery_node_regex
770 public $op = "REGEX_PCRE";
771 public $_op = TSQ_TOK_REGEX_PCRE;
779 class TextSearchQuery_node_regex_sql
780 extends TextSearchQuery_node_regex
782 public $op = "REGEX_SQL"; // using LIKE
783 public $_op = TSQ_TOK_REGEX_SQL;
787 return str_replace(array("/%/", "/_/"), array(".*", "."), $this->word);
799 class TextSearchQuery_node_not
800 extends TextSearchQuery_node
803 public $_op = TSQ_TOK_NOT;
805 function TextSearchQuery_node_not($leaf)
807 $this->leaves = array($leaf);
812 $leaf = &$this->leaves[0];
813 $leaf = $leaf->optimize();
814 if ($leaf->_op == TSQ_TOK_NOT)
815 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
821 $leaf = &$this->leaves[0];
822 return '(?!' . $leaf->regexp() . ')';
825 function highlight_words($negated = false)
827 return $this->leaves[0]->highlight_words(!$negated);
832 * Virtual base class for 'AND' and 'OR conjoins.
834 class TextSearchQuery_node_binop
835 extends TextSearchQuery_node
837 public $_op = TSQ_TOK_BINOP;
839 function __construct($leaves)
841 $this->leaves = $leaves;
844 protected function flatten()
846 // This flattens e.g. (AND (AND a b) (OR c d) e)
847 // to (AND a b e (OR c d))
849 foreach ($this->leaves as $leaf) {
850 $leaf = $leaf->optimize();
851 if ($this->op == $leaf->op)
852 $flat = array_merge($flat, $leaf->leaves);
856 $this->leaves = $flat;
862 assert(!empty($this->leaves));
863 if (count($this->leaves) == 1)
864 return $this->leaves[0]; // (AND x) -> x
868 function highlight_words($negated = false)
871 foreach ($this->leaves as $leaf)
872 array_splice($words, 0, 0,
873 $leaf->highlight_words($negated));
879 * A (possibly multi-argument) 'AND' conjoin.
881 class TextSearchQuery_node_and
882 extends TextSearchQuery_node_binop
890 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
891 // Since OR's are more efficient for regexp matching:
892 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
894 // Suck out the negated leaves.
896 foreach ($this->leaves as $key => $leaf) {
897 if ($leaf->_op == TSQ_TOK_NOT) {
898 $nots[] = $leaf->leaves[0];
899 unset($this->leaves[$key]);
903 // Combine the negated leaves into a single negated or.
905 $node = (new TextSearchQuery_node_not
906 (new TextSearchQuery_node_or($nots)));
907 array_unshift($this->leaves, $node->optimize());
910 assert(!empty($this->leaves));
911 if (count($this->leaves) == 1)
912 return $this->leaves[0]; // (AND x) -> x
917 * Either we need all combinations of all words to be position independent,
918 * or we have to use multiple match calls for each AND
919 * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
924 foreach ($this->leaves as $leaf)
925 $regexp .= $leaf->regexp();
931 * A (possibly multi-argument) 'OR' conjoin.
933 class TextSearchQuery_node_or
934 extends TextSearchQuery_node_binop
940 // We will combine any of our direct descendents which are WORDs
941 // into a single (?=.*(?:word1|word2|...)) regexp.
946 foreach ($this->leaves as $leaf) {
947 if ($leaf->op == TSQ_TOK_WORD)
948 $words[] = preg_quote($leaf->word, '/');
950 $regexps[] = $leaf->regexp();
954 array_unshift($regexps,
955 '(?=.*' . $this->join($words) . ')');
957 return $this->join($regexps);
960 private function join($regexps)
962 assert(count($regexps) > 0);
964 if (count($regexps) > 1)
965 return '(?:' . join('|', $regexps) . ')';
971 ////////////////////////////////////////////////////////////////
974 // op's (and, or, not) are forced to lowercase in the tokenizer.
976 ////////////////////////////////////////////////////////////////
977 class TextSearchQuery_Parser
980 * This is a simple recursive descent parser, based on the following grammar:
995 * atom : '(' list ')'
1000 * The terminal tokens are:
1007 * /[^-()\s][^()\s]* WORD
1011 * ^WORD TextSearchQuery_phrase_starts_with
1021 function parse($search_expr, $case_exact = false, $regex = TSQ_REGEX_AUTO)
1023 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
1024 $this->regex = $regex;
1025 $tree = $this->get_list('toplevel');
1026 // Assert failure when using the following URL in debug mode.
1027 // /TitleSearch?action=FullTextSearch&s=WFXSSProbe'")/>&case_exact=1®ex=sql
1028 // assert($this->lexer->eof());
1029 unset($this->lexer);
1033 function get_list($is_toplevel = false)
1037 // token types we'll accept as words (and thus expr's) for the
1038 // purpose of error recovery:
1039 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
1041 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
1043 while (($expr = $this->get_expr())
1044 || ($expr = $this->get_word($accept_as_words))) {
1050 return new TextSearchQuery_node;
1054 if ($is_toplevel and count($list) == 1) {
1055 if ($this->lexer->query_str[0] == '^')
1056 return new TextSearchQuery_phrase_starts_with($list[0]->word);
1060 return new TextSearchQuery_node_and($list);
1065 if (($expr = $this->get_atom()) === false) // protect against '0'
1068 $savedpos = $this->lexer->tell();
1069 // Bug#1791564: allow string '0'
1070 while (($op = $this->lexer->get(TSQ_TOK_BINOP)) !== false) {
1071 if (!($right = $this->get_atom())) {
1076 $expr = new TextSearchQuery_node_and(array($expr, $right));
1078 assert($op == 'or');
1079 $expr = new TextSearchQuery_node_or(array($expr, $right));
1082 $savedpos = $this->lexer->tell();
1084 $this->lexer->seek($savedpos);
1091 if ($atom = $this->get_word(TSQ_ALLWORDS)) // Bug#1791564 not involved: '*'
1094 $savedpos = $this->lexer->tell();
1095 if ($this->lexer->get(TSQ_TOK_LPAREN)) {
1096 if (($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN)) {
1100 // Handle " ( " or "(test" without closing ")" as plain word
1101 $this->lexer->seek($savedpos);
1102 return new TextSearchQuery_node_word($this->lexer->get(-1));
1104 } elseif ($this->lexer->get(TSQ_TOK_NOT)) {
1105 if (($atom = $this->get_atom()))
1106 return new TextSearchQuery_node_not($atom);
1108 $this->lexer->seek($savedpos);
1112 function get_word($accept = TSQ_ALLWORDS)
1114 // Performance shortcut for ( and ). This is always false
1115 if (!empty($this->lexer->tokens[$this->lexer->pos])) {
1116 list ($type, $val) = $this->lexer->tokens[$this->lexer->pos];
1117 if ($type == TSQ_TOK_LPAREN or $type == TSQ_TOK_RPAREN)
1120 foreach (array("WORD", "STARTS_WITH", "ENDS_WITH", "EXACT",
1121 "REGEX", "REGEX_GLOB", "REGEX_PCRE", "ALL") as $tok) {
1122 $const = constant("TSQ_TOK_" . $tok);
1123 // Bug#1791564: allow word '0'
1124 if ($accept & $const and
1125 (($word = $this->lexer->get($const)) !== false)
1127 // phrase or word level?
1128 if ($tok == 'STARTS_WITH' and $this->lexer->query_str[0] == '^')
1129 $classname = "TextSearchQuery_phrase_" . strtolower($tok);
1130 elseif ($tok == 'ENDS_WITH' and
1131 string_ends_with($this->lexer->query_str, '$')
1133 $classname = "TextSearchQuery_phrase_" . strtolower($tok); else
1134 $classname = "TextSearchQuery_node_" . strtolower($tok);
1135 return new $classname($word);
1142 class TextSearchQuery_Lexer
1144 function TextSearchQuery_Lexer($query_str, $case_exact = false,
1145 $regex = TSQ_REGEX_AUTO)
1147 $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
1148 $this->query_str = $query_str;
1164 return $this->pos == count($this->tokens);
1168 * TODO: support more regex styles, esp. prefer the forced ones over auto
1171 function tokenize($string, $case_exact = false, $regex = TSQ_REGEX_AUTO)
1174 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
1175 while (!empty($buf)) {
1176 if (preg_match('/^([()])\s*/', $buf, $m)) {
1178 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
1180 elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_GLOB)
1181 and preg_match('/^\*\s*/', $buf, $m)
1184 $type = TSQ_TOK_ALL;
1186 elseif ($regex & (TSQ_REGEX_PCRE)
1187 and preg_match('/^\.\*\s*/', $buf, $m)
1190 $type = TSQ_TOK_ALL;
1192 elseif ($regex & (TSQ_REGEX_SQL)
1193 and preg_match('/^%\s*/', $buf, $m)
1196 $type = TSQ_TOK_ALL;
1198 elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_PCRE)
1199 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)
1202 $type = TSQ_TOK_STARTS_WITH;
1204 elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_GLOB)
1205 and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)
1208 $type = TSQ_TOK_STARTS_WITH;
1210 elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_GLOB)
1211 and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)
1214 $type = TSQ_TOK_ENDS_WITH;
1216 elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_PCRE)
1217 and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)
1220 $type = TSQ_TOK_ENDS_WITH;
1222 elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_PCRE)
1223 and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)
1226 $type = TSQ_TOK_EXACT;
1227 } elseif (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
1228 $val = strtolower($m[1]);
1229 $type = TSQ_TOK_BINOP;
1230 } elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
1231 $val = strtolower($m[1]);
1232 $type = TSQ_TOK_NOT;
1234 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
1235 $val = str_replace('""', '"', $m[1]);
1236 $type = TSQ_TOK_WORD;
1238 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
1239 $val = str_replace("''", "'", $m[1]);
1240 $type = TSQ_TOK_WORD;
1242 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
1244 $type = TSQ_TOK_WORD;
1246 assert(empty($buf));
1249 $buf = substr($buf, strlen($m[0]));
1251 /* refine the simple parsing from above: bla*bla, bla?bla, ...
1252 if ($regex and $type == TSQ_TOK_WORD) {
1253 if (substr($val,0,1) == "^")
1254 $type = TSQ_TOK_STARTS_WITH;
1255 elseif (substr($val,0,1) == "*")
1256 $type = TSQ_TOK_ENDS_WITH;
1257 elseif (substr($val,-1,1) == "*")
1258 $type = TSQ_TOK_STARTS_WITH;
1261 $tokens[] = array($type, $val);
1266 function get($accept)
1268 if ($this->pos >= count($this->tokens))
1271 list ($type, $val) = $this->tokens[$this->pos];
1272 if (($type & $accept) == 0)
1283 // c-basic-offset: 4
1284 // c-hanging-comment-ender-p: nil
1285 // indent-tabs-mode: nil