1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.25 2007-01-03 21:22:34 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 getType() { return 'text'; }
103 function _optimize() {
104 $this->_tree = $this->_tree->optimize();
108 * Get a PCRE regexp which matches the query.
110 function asRegexp() {
111 if (!isset($this->_regexp)) {
112 if (!isset($this->_regex_modifier))
113 $this->_regex_modifier = ($this->_case_exact?'':'i').'sS';
115 $this->_regexp = '/' . $this->_tree->regexp() . '/'.$this->_regex_modifier;
117 $this->_regexp = '/^' . $this->_tree->regexp() . '/'.$this->_regex_modifier;
119 return $this->_regexp;
123 * Match query against string.
125 * @param $string string The string to match.
126 * @return boolean True if the string matches the query.
128 function match($string) {
129 return preg_match($this->asRegexp(), $string);
134 * Get a regular expression suitable for highlighting matched words.
136 * This returns a PCRE regular expression which matches any non-negated
139 * @return string The PCRE regexp.
141 function getHighlightRegexp() {
142 if (!isset($this->_hilight_regexp)) {
143 $words = array_unique($this->_tree->highlight_words());
145 $this->_hilight_regexp = false;
147 foreach ($words as $key => $word)
148 $words[$key] = preg_quote($word, '/');
149 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
152 return $this->_hilight_regexp;
156 * Make an SQL clause which matches the query. (deprecated, use makeSqlClause instead)
158 * @param $make_sql_clause_cb WikiCallback
159 * A callback which takes a single word as an argument and
160 * returns an SQL clause which will match exactly those records
161 * containing the word. The word passed to the callback will always
162 * be in all lower case.
164 * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
165 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
166 * How? WikiDB backend method?
170 * function sql_title_match($word) {
171 * return sprintf("LOWER(title) like '%s'",
172 * addslashes($word));
177 * $query = new TextSearchQuery("wiki -page");
178 * $cb = new WikiFunctionCb('sql_title_match');
179 * $sql_clause = $query->makeSqlClause($cb);
181 * This will result in $sql_clause containing something like
182 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
184 * @return string The SQL clause.
186 function makeSqlClause($sql_clause_cb) {
187 $this->_sql_clause_cb = $sql_clause_cb;
188 return $this->_sql_clause($this->_tree);
190 // deprecated: use _sql_clause_obj now.
191 function _sql_clause($node) {
193 case 'WORD': // word => %word%
194 return $this->_sql_clause_cb->call($node->word);
196 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
199 $subclauses = array();
200 foreach ($node->leaves as $leaf)
201 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
202 return join(" $node->op ", $subclauses);
204 assert($node->op == 'VOID');
209 /** Get away with the callback and use a db-specific search class instead.
210 * @see WikiDB_backend_PearDB_search
212 function makeSqlClauseObj(&$sql_search_cb) {
213 $this->_sql_clause_cb = $sql_search_cb;
214 return $this->_sql_clause_obj($this->_tree);
217 function _sql_clause_obj($node) {
220 return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
223 $subclauses = array();
224 foreach ($node->leaves as $leaf)
225 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
226 return join(" $node->op ", $subclauses);
232 return $this->_sql_clause_cb->call($node);
237 postgresql tsearch2 uses no WHERE operators, just & | and ! in the searchstring
239 function makeTsearch2SqlClauseObj(&$sql_search_cb) {
240 $this->_sql_clause_cb = $sql_search_cb;
241 return $this->_Tsearch2Sql_clause_obj($this->_tree);
244 function _Tsearch2Sql_clause_obj($node) {
245 // TODO: "such a phrase"
248 return "!" . $node->leaves[0];
250 $subclauses = array();
251 foreach ($node->leaves as $leaf)
252 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
253 return join("&", $subclauses);
255 $subclauses = array();
256 foreach ($node->leaves as $leaf)
257 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
258 return join("|", $subclauses);
264 return $this->_sql_clause_cb->call($node);
268 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
271 * Get printable representation of the parse tree.
273 * This is for debugging only.
274 * @return string Printable parse tree.
276 function asString() {
277 return $this->_as_string($this->_tree);
280 function _as_string($node, $indent = '') {
283 return $indent . "WORD: $node->word";
285 return $indent . "VOID";
287 return $indent . "ALL";
289 $lines = array($indent . $node->op . ":");
291 foreach ($node->leaves as $leaf)
292 $lines[] = $this->_as_string($leaf, $indent);
293 return join("\n", $lines);
299 * This is a TextSearchQuery which matches nothing.
301 class NullTextSearchQuery extends TextSearchQuery {
303 * Create a new query.
305 * @see TextSearchQuery
307 function NullTextSearchQuery() {}
308 function asRegexp() { return '/^(?!a)a/x'; }
309 function match($string) { return false; }
310 function getHighlightRegexp() { return ""; }
311 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
312 function asString() { return "NullTextSearchQuery"; }
316 * A simple algebraic matcher for numeric attributes.
317 * NumericSearchQuery can do ("population < 20000 and area > 1000000", array("population", "area"))
318 * ->match(array('population' => 100000, 'area' => 10000000))
320 * Supports all mathematical PHP comparison operators, plus ':=' for equality.
321 * "(x < 2000000 and x >= 10000) or (x >= 100 and x < 2000)"
322 * "x := 100000" is the same as "x == 100000"
324 * Since this is basic numerics only, we simply try to get away with
325 * replacing the variable values at the right positions and do an eval then.
327 * @package NumericSearchQuery
328 * @author Reini Urban
329 * @see SemanticAttributeSearchQuery
331 class NumericSearchQuery
334 * Create a new query.
335 * NumericSearchQuery("population > 20000 or population < 200", "population")
336 * NumericSearchQuery("population < 20000 and area > 1000000", array("population", "area"))
338 * With a single variable it is easy: The valid name must be matched elsewhere, just
339 * replace the given number in match in the query.
342 * With matching a struct we need strict names, no * as name is allowed.
343 * So always when the placeholder is an array, the names of the target struct must match
344 * and all vars be defined. Use the method can_match($struct) therefore.
347 * @param $search_query string A numerical query with placeholders as variable.
348 * @param $placeholders array or string All placeholders in the query must be defined
349 * here, and will be replaced by the matcher.
351 function NumericSearchQuery($search_query, $placeholders) {
352 // added some basic security checks against user input
353 $this->_query = $search_query;
354 $this->_placeholders = $placeholders;
356 // we should also allow the M_ constants
357 $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');
358 $this->_allowed_operators = explode(',', '-,<,<=,>,>=,==,!=,*,+,/,(,),%,and,or,xor,<<,>>,===,!==,&,^,|,&&,||');
359 $this->_parser_check = array();
360 // check should be fast, so make a hash
361 foreach ($this->_allowed_functions as $f)
362 $this->_parser_check[$f] = 1;
363 foreach ($this->_allowed_operators as $f)
364 $this->_parser_check[$f] = 1;
365 if (is_array($placeholders))
366 foreach ($placeholders as $f)
367 $this->_parser_check[$f] = 1;
368 else $this->_parser_check[$placeholders] = 1;
370 // This is a speciality: := looks like the attribute definition and is
371 // therefore a dummy check for this definition.
372 $this->_query = preg_replace("/\b:=\b/", "==", $this->_query);
373 $this->_query = $this->check_query($this->_query);
376 function getType() { return 'numeric'; }
379 * Check the symbolic definition query against unwanted functions and characters.
380 * "population < 20000 and area > 1000000" vs "area > 1000000 and mail($me,file("/etc/passwd"),...)"
381 * http://localhost/wikicvs/SemanticSearch?attribute=*&attr_op=<0 and find(1)>&s=-0.01&start_debug=1
383 function check_query ($query) {
385 while (preg_match("/\A(\w.+)\s*\(\Z/", $query, $m)) {
386 if (!in_array($m[1], $this->_allowed_functions)
387 and !in_array($m[1], $this->_allowed_operators))
389 trigger_error("Illegal function in query: ".$m[1], E_USER_WARNING);
394 // Check for illegal functions and operators, which are no placeholders.
395 if (function_exists('token_get_all')) {
396 $parsed = token_get_all("<?$query?>");
397 foreach ($parsed as $x) { // flat, non-recursive array
398 if (is_string($x) and !isset($this->_parser_check[$x])) {
399 // single char op or name
400 trigger_error("illegal string or operator: \"$x\"". E_USER_WARNING);
403 elseif (is_array($x)) {
404 $n = token_name($x[0]);
405 if ($n == 'T_OPEN_TAG' or $n == 'T_WHITESPACE'
406 or $n == 'T_CLOSE_TAG' or $n == 'T_LNUMBER'
407 or $n == 'T_CONST' or $n == 'T_DNUMBER' ) continue;
408 if ($n == 'T_VARIABLE') { // but we do allow consts
409 trigger_error("illegal variable: \"$x[1]\"", E_USER_WARNING);
412 if (is_string($x[1]) and !isset($this->_parser_check[$x[1]])) {
413 // multi-char char op or name
414 trigger_error("illegal $n: \"$x[1]\"", E_USER_WARNING);
419 //echo "$query <br>";
420 //$this->_parse_token($parsed);
425 { T_OPEN_TAG "<?"} { T_STRING "_x"} { T_WHITESPACE " "} ">" { T_WHITESPACE " "} { T_LNUMBER "0"} { T_CLOSE_TAG "?>"}
426 Interesting: on-char ops, as ">" are not tokenized.
428 { T_OPEN_TAG "< ?" } { T_STRING "_x" } { T_WHITESPACE " " } { T_IS_SMALLER_OR_EQUAL "<=" } { T_WHITESPACE " " } { T_LNUMBER "0" } { T_CLOSE_TAG "?>" }
431 // Detect illegal characters besides nums, words and ops. So attribute names can not be utf-8
432 $c = "/([^\d\w.,\s".preg_quote(join("",$this->_allowed_operators),"/")."])/";
433 if (preg_match($c, $query, $m)) {
434 trigger_error("Illegal character in query: ".$m[1], E_USER_WARNING);
442 * Check the bound, numeric-only query against unwanted functions and sideeffects.
443 * "4560000 < 20000 and 1456022 > 1000000"
445 function _live_check () {
446 // TODO: check $this->_workquery again?
447 return !empty($this->_workquery);
451 * A numeric query can only operate with predefined variables. "x < 0 and y < 1"
453 * @return array The names as array of strings. => ('x', 'y') the placeholders.
456 if(is_array($this->_placeholders)) return $this->_placeholders;
457 else return array($this->_placeholders);
461 * Strip non-numeric chars from the variable (as the groupseperator) and replace
462 * it in the symbolic query for evaluation.
465 * @param $value number A numerical value: integer, float or string.
466 * @param $x string The variable name to be replaced in the query.
469 function _bind($value, $x) {
470 // TODO: check is_number, is_float, is_integer and do casting
471 $this->_bound[] = array('linkname' => $x,
472 'linkvalue' => $value);
473 $value = preg_replace("/[^-+0123456789.,]/", "", $value);
474 //$c = "/\b".preg_quote($x,"/")."\b/";
475 $this->_workquery = preg_replace("/\b".preg_quote($x,"/")."\b/", $value, $this->_workquery);
476 // FIXME: do again a final check. now only numbers and some operators are allowed.
477 return $this->_workquery;
480 /* array of successfully bound vars, and in case of success, the resulting vars
483 return $this->_bound;
487 * With an array of placeholders we need a hash to check against, if all required names are given.
488 * Purpose: Be silent about missing vars, just return false.
491 * @param $variable string or hash of name => value The keys must satisfy all placeholders in the definition.
492 * We want the full hash and not just the keys because a hash check is faster than the array of keys check.
495 function can_match(&$variables) {
496 if (empty($this->_query))
498 $p =& $this->_placeholders;
499 if (!is_array($variables) and !is_array($p))
500 return $variables == $p; // This was easy.
501 // Check if all placeholders have definitions. can be overdefined but not underdefined.
503 if (!isset($variables[$p])) return false;
506 if (!isset($variables[$x])) return false;
513 * We can match against a single variable or against a hash of variables.
514 * With one placeholder we need just a number.
515 * With an array of placeholders we need a hash.
518 * @param $variable number or array of name => value The keys must satisfy all placeholders in the definition.
521 function match(&$variable) {
522 $p =& $this->_placeholders;
523 $this->_workquery = $this->_query;
525 if (is_array($variable)) { // which var to match? we cannot decide this here
526 if (!isset($variable[$p]))
527 trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR);
528 $this->_bind($variable[$p], $p);
530 $this->_bind($variable, $p);
534 if (!isset($variable[$x]))
535 trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR);
536 $this->_bind($variable[$x], $x);
539 if (!$this->_live_check()) // check returned an error
541 $search = $this->_workquery;
543 //if (DEBUG & _DEBUG_VERBOSE)
544 // trigger_error("\$result = (boolean)($search);", E_USER_NOTICE);
545 // we might have a numerical problem:
546 // php-4.2.2 eval'ed as module: "9.636e+08 > 1000" false;
547 // php-5.1.2 cgi true, 4.2.2 cgi true
548 eval("\$result = (boolean)($search);");
549 if ($result and is_array($p)) {
550 return $this->_bound();
557 ////////////////////////////////////////////////////////////////
559 // Remaining classes are private.
561 ////////////////////////////////////////////////////////////////
563 * Virtual base class for nodes in a TextSearchQuery parse tree.
565 * Also serves as a 'VOID' (contentless) node.
567 class TextSearchQuery_node
572 * Optimize this node.
573 * @return object Optimized node.
575 function optimize() {
580 * @return regexp matching this node.
587 * @param bool True if this node has been negated (higher in the parse tree.)
588 * @return array A list of all non-negated words contained by this node.
590 function highlight_words($negated = false) {
594 function sql() { return $this->word; }
600 class TextSearchQuery_node_word
601 extends TextSearchQuery_node
605 function TextSearchQuery_node_word($word) {
609 return '(?=.*' . preg_quote($this->word, '/') . ')';
611 function highlight_words ($negated = false) {
612 return $negated ? array() : array($this->word);
614 function _sql_quote() {
615 $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
616 return $GLOBALS['request']->_dbi->qstr($word);
618 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
621 class TextSearchQuery_node_all
622 extends TextSearchQuery_node {
624 function regexp() { return '(?=.*)'; }
625 function sql() { return '%'; }
627 class TextSearchQuery_node_starts_with
628 extends TextSearchQuery_node_word {
629 var $op = "STARTS_WITH";
630 function regexp() { return '(?=.*\b' . preg_quote($this->word, '/') . ')'; }
631 function sql () { return $this->_sql_quote($this->word).'%'; }
634 class TextSearchQuery_node_ends_with
635 extends TextSearchQuery_node_word {
636 var $op = "ENDS_WITH";
637 function regexp() { return '(?=.*' . preg_quote($this->word, '/') . '\b)'; }
638 function sql () { return '%'.$this->_sql_quote($this->word); }
641 class TextSearchQuery_node_exact
642 extends TextSearchQuery_node_word {
644 function regexp() { return '(?=\b' . preg_quote($this->word, '/') . '\b)'; }
645 function sql () { return $this->_sql_squote($this->word); }
648 class TextSearchQuery_node_regex // posix regex. FIXME!
649 extends TextSearchQuery_node_word {
650 var $op = "REGEX"; // using REGEXP or ~ extension
651 function regexp() { return '(?=.*\b' . $this->word . '\b)'; }
652 function sql () { return $this->_sql_quote($this->word); }
655 class TextSearchQuery_node_regex_glob
656 extends TextSearchQuery_node_regex {
657 var $op = "REGEX_GLOB";
658 function regexp() { return '(?=.*\b' . glob_to_pcre($this->word) . '\b)'; }
661 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
662 extends TextSearchQuery_node_regex {
663 var $op = "REGEX_PCRE";
664 function regexp() { return $this->word; }
667 class TextSearchQuery_node_regex_sql
668 extends TextSearchQuery_node_regex {
669 var $op = "REGEX_SQL"; // using LIKE
670 function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
671 function sql() { return $this->word; }
677 class TextSearchQuery_node_not
678 extends TextSearchQuery_node
682 function TextSearchQuery_node_not($leaf) {
683 $this->leaves = array($leaf);
686 function optimize() {
687 $leaf = &$this->leaves[0];
688 $leaf = $leaf->optimize();
689 if ($leaf->op == 'NOT')
690 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
695 $leaf = &$this->leaves[0];
696 return '(?!' . $leaf->regexp() . ')';
699 function highlight_words ($negated = false) {
700 return $this->leaves[0]->highlight_words(!$negated);
705 * Virtual base class for 'AND' and 'OR conjoins.
707 class TextSearchQuery_node_binop
708 extends TextSearchQuery_node
710 function TextSearchQuery_node_binop($leaves) {
711 $this->leaves = $leaves;
714 function _flatten() {
715 // This flattens e.g. (AND (AND a b) (OR c d) e)
716 // to (AND a b e (OR c d))
718 foreach ($this->leaves as $leaf) {
719 $leaf = $leaf->optimize();
720 if ($this->op == $leaf->op)
721 $flat = array_merge($flat, $leaf->leaves);
725 $this->leaves = $flat;
728 function optimize() {
730 assert(!empty($this->leaves));
731 if (count($this->leaves) == 1)
732 return $this->leaves[0]; // (AND x) -> x
736 function highlight_words($negated = false) {
738 foreach ($this->leaves as $leaf)
739 array_splice($words,0,0,
740 $leaf->highlight_words($negated));
746 * A (possibly multi-argument) 'AND' conjoin.
748 class TextSearchQuery_node_and
749 extends TextSearchQuery_node_binop
753 function optimize() {
756 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
757 // Since OR's are more efficient for regexp matching:
758 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
760 // Suck out the negated leaves.
762 foreach ($this->leaves as $key => $leaf) {
763 if ($leaf->op == 'NOT') {
764 $nots[] = $leaf->leaves[0];
765 unset($this->leaves[$key]);
769 // Combine the negated leaves into a single negated or.
771 $node = ( new TextSearchQuery_node_not
772 (new TextSearchQuery_node_or($nots)) );
773 array_unshift($this->leaves, $node->optimize());
776 assert(!empty($this->leaves));
777 if (count($this->leaves) == 1)
778 return $this->leaves[0]; // (AND x) -> x
783 * Either we need all combinations of all words to be position independent,
784 * or we have to use multiple match calls for each AND
785 * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
789 foreach ($this->leaves as $leaf)
790 $regexp .= $leaf->regexp();
796 * A (possibly multi-argument) 'OR' conjoin.
798 class TextSearchQuery_node_or
799 extends TextSearchQuery_node_binop
804 // We will combine any of our direct descendents which are WORDs
805 // into a single (?=.*(?:word1|word2|...)) regexp.
810 foreach ($this->leaves as $leaf) {
811 if ($leaf->op == 'WORD')
812 $words[] = preg_quote($leaf->word, '/');
814 $regexps[] = $leaf->regexp();
818 array_unshift($regexps,
819 '(?=.*' . $this->_join($words) . ')');
821 return $this->_join($regexps);
824 function _join($regexps) {
825 assert(count($regexps) > 0);
827 if (count($regexps) > 1)
828 return '(?:' . join('|', $regexps) . ')';
835 ////////////////////////////////////////////////////////////////
838 // op's (and, or, not) are forced to lowercase in the tokenizer.
840 ////////////////////////////////////////////////////////////////
841 define ('TSQ_TOK_BINOP', 1);
842 define ('TSQ_TOK_NOT', 2);
843 define ('TSQ_TOK_LPAREN', 4);
844 define ('TSQ_TOK_RPAREN', 8);
845 define ('TSQ_TOK_WORD', 16);
846 define ('TSQ_TOK_STARTS_WITH', 32);
847 define ('TSQ_TOK_ENDS_WITH', 64);
848 define ('TSQ_TOK_EXACT', 128);
849 define ('TSQ_TOK_REGEX', 256);
850 define ('TSQ_TOK_REGEX_GLOB', 512);
851 define ('TSQ_TOK_REGEX_PCRE', 1024);
852 define ('TSQ_TOK_REGEX_SQL', 2048);
853 define ('TSQ_TOK_ALL', 4096);
854 // all bits from word to the last.
855 define ('TSQ_ALLWORDS', (4096*2)-1 - (16-1));
857 class TextSearchQuery_Parser
860 * This is a simple recursive descent parser, based on the following grammar:
875 * atom : '(' list ')'
880 * The terminal tokens are:
887 * /[^-()\s][^()\s]* WORD
898 function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
899 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
900 $this->_regex = $regex;
901 $tree = $this->get_list('toplevel');
902 assert($this->lexer->eof());
907 function get_list ($is_toplevel = false) {
910 // token types we'll accept as words (and thus expr's) for the
911 // purpose of error recovery:
912 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
914 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
916 while ( ($expr = $this->get_expr())
917 || ($expr = $this->get_word($accept_as_words)) ) {
923 return new TextSearchQuery_node;
927 return new TextSearchQuery_node_and($list);
930 function get_expr () {
931 if ( !($expr = $this->get_atom()) )
934 $savedpos = $this->lexer->tell();
935 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
936 if ( ! ($right = $this->get_atom()) ) {
941 $expr = new TextSearchQuery_node_and(array($expr, $right));
944 $expr = new TextSearchQuery_node_or(array($expr, $right));
947 $savedpos = $this->lexer->tell();
949 $this->lexer->seek($savedpos);
955 function get_atom() {
956 if ($word = $this->get_word(TSQ_ALLWORDS))
959 $savedpos = $this->lexer->tell();
960 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
961 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
964 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
965 if ( ($atom = $this->get_atom()) )
966 return new TextSearchQuery_node_not($atom);
968 $this->lexer->seek($savedpos);
972 function get_word($accept = TSQ_ALLWORDS) {
973 foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
974 "REGEX","REGEX_GLOB","REGEX_PCRE","ALL") as $tok) {
975 $const = constant("TSQ_TOK_".$tok);
976 if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
977 $classname = "TextSearchQuery_node_".strtolower($tok);
978 return new $classname($word);
985 class TextSearchQuery_Lexer {
986 function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
987 $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
995 function seek($pos) {
1000 return $this->pos == count($this->tokens);
1004 * TODO: support more regex styles, esp. prefer the forced ones over auto
1007 function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
1009 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
1010 while (!empty($buf)) {
1011 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
1012 $val = strtolower($m[1]);
1013 $type = TSQ_TOK_BINOP;
1015 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
1016 $val = strtolower($m[1]);
1017 $type = TSQ_TOK_NOT;
1019 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
1021 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
1025 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1026 and preg_match('/^\*\s*/', $buf, $m)) {
1028 $type = TSQ_TOK_ALL;
1031 elseif ($regex & (TSQ_REGEX_PCRE)
1032 and preg_match('/^\.\*\s*/', $buf, $m)) {
1034 $type = TSQ_TOK_ALL;
1037 elseif ($regex & (TSQ_REGEX_SQL)
1038 and preg_match('/^%\s*/', $buf, $m)) {
1040 $type = TSQ_TOK_ALL;
1044 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1045 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
1047 $type = TSQ_TOK_STARTS_WITH;
1050 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1051 and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
1053 $type = TSQ_TOK_STARTS_WITH;
1056 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1057 and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
1059 $type = TSQ_TOK_ENDS_WITH;
1062 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1063 and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
1065 $type = TSQ_TOK_ENDS_WITH;
1068 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1069 and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
1071 $type = TSQ_TOK_EXACT;
1075 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
1076 $val = str_replace('""', '"', $m[1]);
1077 $type = TSQ_TOK_WORD;
1080 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
1081 $val = str_replace("''", "'", $m[1]);
1082 $type = TSQ_TOK_WORD;
1085 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
1087 $type = TSQ_TOK_WORD;
1090 assert(empty($buf));
1093 $buf = substr($buf, strlen($m[0]));
1095 /* refine the simple parsing from above: bla*bla, bla?bla, ...
1096 if ($regex and $type == TSQ_TOK_WORD) {
1097 if (substr($val,0,1) == "^")
1098 $type = TSQ_TOK_STARTS_WITH;
1099 elseif (substr($val,0,1) == "*")
1100 $type = TSQ_TOK_ENDS_WITH;
1101 elseif (substr($val,-1,1) == "*")
1102 $type = TSQ_TOK_STARTS_WITH;
1105 $tokens[] = array($type, $val);
1110 function get($accept) {
1111 if ($this->pos >= count($this->tokens))
1114 list ($type, $val) = $this->tokens[$this->pos];
1115 if (($type & $accept) == 0)
1123 // $Log: not supported by cvs2svn $
1124 // Revision 1.24 2007/01/02 13:19:05 rurban
1125 // add NumericSearchQuery. change on pcre: no parsing done, detect modifiers
1127 // Revision 1.23 2006/04/13 19:30:44 rurban
1128 // make TextSearchQuery->_stoplist localizable and overridable within config.ini
1134 // c-basic-offset: 4
1135 // c-hanging-comment-ender-p: nil
1136 // indent-tabs-mode: nil