1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.32 2008-05-06 19:25:55 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 define ('TSQ_TOK_VOID', 0);
64 define ('TSQ_TOK_BINOP', 1);
65 define ('TSQ_TOK_NOT', 2);
66 define ('TSQ_TOK_LPAREN', 4);
67 define ('TSQ_TOK_RPAREN', 8);
68 define ('TSQ_TOK_WORD', 16);
69 define ('TSQ_TOK_STARTS_WITH', 32);
70 define ('TSQ_TOK_ENDS_WITH', 64);
71 define ('TSQ_TOK_EXACT', 128);
72 define ('TSQ_TOK_REGEX', 256);
73 define ('TSQ_TOK_REGEX_GLOB', 512);
74 define ('TSQ_TOK_REGEX_PCRE', 1024);
75 define ('TSQ_TOK_REGEX_SQL', 2048);
76 define ('TSQ_TOK_ALL', 4096);
77 // all bits from word to the last.
78 define ('TSQ_ALLWORDS', (4096*2)-1 - (16-1));
81 define ('TSQ_NODE_ALL', 0);
82 define ('TSQ_NODE_EXACT', 1);
83 define ('TSQ_NODE_NOT', 2);
84 define ('TSQ_NODE_WORD', 3);
85 define ('TSQ_NODE_STARTS_WITH', 4);
86 define ('TSQ_NODE_ENDS_WITH', 5);
87 define ('TSQ_NODE_REGEX', 6);
88 define ('TSQ_NODE_REGEX_GLOB', 7);
89 define ('TSQ_NODE_REGEX_PCRE', 8);
90 define ('TSQ_NODE_REGEX_SQL', 9);
91 define ('TSQ_NODE_AND', 10);
92 define ('TSQ_NODE_OR', 11);
96 class TextSearchQuery {
100 * @param $search_query string The query. Syntax is as described above.
101 * Note that an empty $search_query will match anything.
102 * @param $case_exact boolean
103 * @param $regex string one of 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
104 * @see TextSearchQuery
106 function TextSearchQuery($search_query, $case_exact=false, $regex='auto') {
107 if ($regex == 'none' or !$regex)
109 elseif (defined("TSQ_REGEX_".strtoupper($regex)))
110 $this->_regex = constant("TSQ_REGEX_".strtoupper($regex));
112 trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex));
115 $this->_case_exact = $case_exact;
116 if ($regex != 'pcre') {
117 $parser = new TextSearchQuery_Parser;
118 $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex);
119 $this->_optimize(); // broken under certain circumstances: "word -word -word"
120 if (defined("FULLTEXTSEARCH_STOPLIST"))
121 $this->_stoplist = FULLTEXTSEARCH_STOPLIST;
122 else // default stoplist, localizable.
123 $this->_stoplist = _("(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)");
126 $this->_tree = new TextSearchQuery_node_regex_pcre($search_query);
127 if (preg_match("/^\/(.*)\/(\w*)$/", $search_query, $m)) {
128 $this->_tree->word = $m[1];
129 $this->_regex_modifier = $m[2]; // overrides case_exact
134 function getType() { return 'text'; }
136 function _optimize() {
137 $this->_tree = $this->_tree->optimize();
141 * Get a PCRE regexp which matches the query.
143 function asRegexp() {
144 if (!isset($this->_regexp)) {
145 if (!isset($this->_regex_modifier))
146 $this->_regex_modifier = ($this->_case_exact?'':'i').'sS';
148 $this->_regexp = '/' . $this->_tree->regexp() . '/'.$this->_regex_modifier;
150 $this->_regexp = '/^' . $this->_tree->regexp() . '/'.$this->_regex_modifier;
152 return $this->_regexp;
156 * Match query against string.
157 * EXACT ("Term") ignores the case_exact setting.
159 * @param $string string The string to match.
160 * @return boolean True if the string matches the query.
162 function match($string) {
163 if ($this->_tree->_op = TSQ_TOK_ALL) return true;
164 if ($this->_tree->_op = TSQ_TOK_EXACT) return $this->_tree->word == $string;
165 return preg_match($this->asRegexp(), $string);
168 /* How good does it match? Returns a number */
169 function score($string) {
172 foreach (array_unique($this->_tree->highlight_words()) as $word) {
173 if ($nummatch = preg_match_all("/".preg_quote($word, '/')."/".
174 $this->_regex_modifier,
176 $score += ($i-- * $nummatch);
178 return min(1.0, $score / 10.0);
183 * Get a regular expression suitable for highlighting matched words.
185 * This returns a PCRE regular expression which matches any non-negated
188 * @return string The PCRE regexp.
190 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;
206 * Make an SQL clause which matches the query.
207 * Deprecated, use makeSqlClauseObj instead.
209 * @param $make_sql_clause_cb WikiCallback
210 * A callback which takes a single word as an argument and
211 * returns an SQL clause which will match exactly those records
212 * containing the word. The word passed to the callback will always
213 * be in all lower case.
215 * Support db-specific extensions, like MATCH AGAINST or REGEX
216 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
217 * by using makeSqlClauseObj
221 * function sql_title_match($word) {
222 * return sprintf("LOWER(title) like '%s'",
223 * addslashes($word));
228 * $query = new TextSearchQuery("wiki -page");
229 * $cb = new WikiFunctionCb('sql_title_match');
230 * $sql_clause = $query->makeSqlClause($cb);
232 * This will result in $sql_clause containing something like
233 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
235 * @return string The SQL clause.
237 function makeSqlClause($sql_clause_cb) {
238 $this->_sql_clause_cb = $sql_clause_cb;
239 return $this->_sql_clause($this->_tree);
241 // deprecated: use _sql_clause_obj now.
242 function _sql_clause($node) {
243 switch ($node->_op) {
244 case TSQ_TOK_WORD: // word => %word%
245 return $this->_sql_clause_cb->call($node->word);
247 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
249 $subclauses = array();
250 foreach ($node->leaves as $leaf)
251 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
252 return join(" $node->op ", $subclauses);
254 assert($node->_op == TSQ_TOK_VOID);
259 /** Get away with the callback and use a db-specific search class instead.
260 * @see WikiDB_backend_PearDB_search
262 function makeSqlClauseObj(&$sql_search_cb) {
263 $this->_sql_clause_cb = $sql_search_cb;
264 return $this->_sql_clause_obj($this->_tree);
267 function _sql_clause_obj($node) {
268 switch ($node->_op) {
270 return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
272 $subclauses = array();
273 foreach ($node->leaves as $leaf)
274 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
275 return join(" $node->op ", $subclauses);
281 return $this->_sql_clause_cb->call($node);
286 postgresql tsearch2 uses no WHERE operators, just & | and ! in the searchstring
288 function makeTsearch2SqlClauseObj(&$sql_search_cb) {
289 $this->_sql_clause_cb = $sql_search_cb;
290 return $this->_Tsearch2Sql_clause_obj($this->_tree);
293 function _Tsearch2Sql_clause_obj($node) {
294 // TODO: "such a phrase"
295 switch ($node->_op) {
297 return "!" . $node->leaves[0];
299 $subclauses = array();
300 foreach ($node->leaves as $leaf)
301 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
302 return join($node->_op == 'AND' ? "&" : "|", $subclauses);
308 return $this->_sql_clause_cb->call($node);
312 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
315 * Get printable representation of the parse tree.
317 * This is for debugging only.
318 * @return string Printable parse tree.
320 function asString() {
321 return $this->_as_string($this->_tree);
324 function _as_string($node, $indent = '') {
325 switch ($node->_op) {
327 return $indent . "WORD: $node->word";
329 return $indent . "VOID";
331 return $indent . "ALL";
333 $lines = array($indent . $node->op . ":");
335 foreach ($node->leaves as $leaf)
336 $lines[] = $this->_as_string($leaf, $indent);
337 return join("\n", $lines);
343 * This is a TextSearchQuery which matches nothing.
345 class NullTextSearchQuery extends TextSearchQuery {
347 * Create a new query.
349 * @see TextSearchQuery
351 function NullTextSearchQuery() {}
352 function asRegexp() { return '/^(?!a)a/x'; }
353 function match($string) { return false; }
354 function getHighlightRegexp() { return ""; }
355 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
356 function asString() { return "NullTextSearchQuery"; }
360 * A simple algebraic matcher for numeric attributes.
361 * NumericSearchQuery can do ("population < 20000 and area > 1000000", array("population", "area"))
362 * ->match(array('population' => 100000, 'area' => 10000000))
364 * Supports all mathematical PHP comparison operators, plus ':=' for equality.
365 * "(x < 2000000 and x >= 10000) or (x >= 100 and x < 2000)"
366 * "x := 100000" is the same as "x == 100000"
368 * Since this is basic numerics only, we simply try to get away with
369 * replacing the variable values at the right positions and do an eval then.
371 * @package NumericSearchQuery
372 * @author Reini Urban
373 * @see SemanticAttributeSearchQuery
375 class NumericSearchQuery
378 * Create a new query.
379 * NumericSearchQuery("population > 20000 or population < 200", "population")
380 * NumericSearchQuery("population < 20000 and area > 1000000", array("population", "area"))
382 * With a single variable it is easy: The valid name must be matched elsewhere, just
383 * replace the given number in match in the query.
386 * With matching a struct we need strict names, no * as name is allowed.
387 * So always when the placeholder is an array, the names of the target struct must match
388 * and all vars be defined. Use the method can_match($struct) therefore.
391 * @param $search_query string A numerical query with placeholders as variable.
392 * @param $placeholders array or string All placeholders in the query must be defined
393 * here, and will be replaced by the matcher.
395 function NumericSearchQuery($search_query, $placeholders) {
396 // added some basic security checks against user input
397 $this->_query = $search_query;
398 $this->_placeholders = $placeholders;
400 // we should also allow the M_ constants
401 $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');
402 $this->_allowed_operators = explode(',', '-,<,<=,>,>=,==,!=,*,+,/,(,),%,and,or,xor,<<,>>,===,!==,&,^,|,&&,||');
403 $this->_parser_check = array();
404 // check should be fast, so make a hash
405 foreach ($this->_allowed_functions as $f)
406 $this->_parser_check[$f] = 1;
407 foreach ($this->_allowed_operators as $f)
408 $this->_parser_check[$f] = 1;
409 if (is_array($placeholders))
410 foreach ($placeholders as $f)
411 $this->_parser_check[$f] = 1;
412 else $this->_parser_check[$placeholders] = 1;
414 // This is a speciality: := looks like the attribute definition and is
415 // therefore a dummy check for this definition.
416 // php-4.2.2 has a problem with /\b:=\b/ matching "population := 1223400"
417 $this->_query = preg_replace("/:=/", "==", $this->_query);
418 $this->_query = $this->check_query($this->_query);
421 function getType() { return 'numeric'; }
424 * Check the symbolic definition query against unwanted functions and characters.
425 * "population < 20000 and area > 1000000" vs
426 * "area > 1000000 and mail($me,file("/etc/passwd"),...)"
427 * http://localhost/wikicvs/SemanticSearch?attribute=*&attr_op=<0 and find(1)>&s=-0.01&start_debug=1
429 function check_query ($query) {
430 $tmp = $query; // check for all function calls, in case the tokenizer is not available.
431 while (preg_match("/([a-z][a-z0-9]+)\s*\((.*)$/i", $tmp, $m)) {
432 if (!in_array($m[1], $this->_allowed_functions)
433 and !in_array($m[1], $this->_allowed_operators))
435 trigger_error("Illegal function in query: ".$m[1], E_USER_WARNING);
441 // Strictly check for illegal functions and operators, which are no placeholders.
442 if (function_exists('token_get_all')) {
443 $parsed = token_get_all("<?$query?>");
444 foreach ($parsed as $x) { // flat, non-recursive array
445 if (is_string($x) and !isset($this->_parser_check[$x])) {
446 // single char op or name
447 trigger_error("Illegal string or operator in query: \"$x\"", E_USER_WARNING);
450 elseif (is_array($x)) {
451 $n = token_name($x[0]);
452 if ($n == 'T_OPEN_TAG' or $n == 'T_WHITESPACE'
453 or $n == 'T_CLOSE_TAG' or $n == 'T_LNUMBER'
454 or $n == 'T_CONST' or $n == 'T_DNUMBER' ) continue;
455 if ($n == 'T_VARIABLE') { // but we do allow consts
456 trigger_error("Illegal variable in query: \"$x[1]\"", E_USER_WARNING);
459 if (is_string($x[1]) and !isset($this->_parser_check[$x[1]])) {
460 // multi-char char op or name
461 trigger_error("Illegal $n in query: \"$x[1]\"", E_USER_WARNING);
466 //echo "$query <br>";
467 //$this->_parse_token($parsed);
472 { T_OPEN_TAG "<?"} { T_STRING "_x"} { T_WHITESPACE " "} ">" { T_WHITESPACE " "} { T_LNUMBER "0"} { T_CLOSE_TAG "?>"}
473 Interesting: on-char ops, as ">" are not tokenized.
475 { T_OPEN_TAG "< ?" } { T_STRING "_x" } { T_WHITESPACE " " } { T_IS_SMALLER_OR_EQUAL "<=" } { T_WHITESPACE " " } { T_LNUMBER "0" } { T_CLOSE_TAG "?>" }
478 // Detect illegal characters besides nums, words and ops.
479 // So attribute names can not be utf-8
480 $c = "/([^\d\w.,\s".preg_quote(join("",$this->_allowed_operators),"/")."])/";
481 if (preg_match($c, $query, $m)) {
482 trigger_error("Illegal character in query: ".$m[1], E_USER_WARNING);
490 * Check the bound, numeric-only query against unwanted functions and sideeffects.
491 * "4560000 < 20000 and 1456022 > 1000000"
493 function _live_check () {
494 // TODO: check $this->_workquery again?
495 return !empty($this->_workquery);
499 * A numeric query can only operate with predefined variables. "x < 0 and y < 1"
501 * @return array The names as array of strings. => ('x', 'y') the placeholders.
504 if(is_array($this->_placeholders)) return $this->_placeholders;
505 else return array($this->_placeholders);
509 * Strip non-numeric chars from the variable (as the groupseperator) and replace
510 * it in the symbolic query for evaluation.
513 * @param $value number A numerical value: integer, float or string.
514 * @param $x string The variable name to be replaced in the query.
517 function _bind($value, $x) {
518 // TODO: check is_number, is_float, is_integer and do casting
519 $this->_bound[] = array('linkname' => $x,
520 'linkvalue' => $value);
521 $value = preg_replace("/[^-+0123456789.,]/", "", $value);
522 //$c = "/\b".preg_quote($x,"/")."\b/";
523 $this->_workquery = preg_replace("/\b".preg_quote($x,"/")."\b/", $value, $this->_workquery);
524 // FIXME: do again a final check. now only numbers and some operators are allowed.
525 return $this->_workquery;
528 /* array of successfully bound vars, and in case of success, the resulting vars
531 return $this->_bound;
535 * With an array of placeholders we need a hash to check against, if all required names are given.
536 * Purpose: Be silent about missing vars, just return false.
539 * @param $variable string or hash of name => value The keys must satisfy all placeholders in the definition.
540 * We want the full hash and not just the keys because a hash check is faster than the array of keys check.
543 function can_match(&$variables) {
544 if (empty($this->_query))
546 $p =& $this->_placeholders;
547 if (!is_array($variables) and !is_array($p))
548 return $variables == $p; // This was easy.
549 // Check if all placeholders have definitions. can be overdefined but not underdefined.
551 if (!isset($variables[$p])) return false;
554 if (!isset($variables[$x])) return false;
561 * We can match against a single variable or against a hash of variables.
562 * With one placeholder we need just a number.
563 * With an array of placeholders we need a hash.
566 * @param $variable number or array of name => value The keys must satisfy all placeholders in the definition.
569 function match(&$variable) {
570 $p =& $this->_placeholders;
571 $this->_workquery = $this->_query;
573 if (is_array($variable)) { // which var to match? we cannot decide this here
574 if (!isset($variable[$p]))
575 trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR);
576 $this->_bind($variable[$p], $p);
578 $this->_bind($variable, $p);
582 if (!isset($variable[$x]))
583 trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR);
584 $this->_bind($variable[$x], $x);
587 if (!$this->_live_check()) // check returned an error
589 $search = $this->_workquery;
591 //if (DEBUG & _DEBUG_VERBOSE)
592 // trigger_error("\$result = (boolean)($search);", E_USER_NOTICE);
593 // We might have a numerical problem:
594 // php-4.2.2 eval'ed as module: "9.636e+08 > 1000" false;
595 // php-5.1.2 cgi true, 4.2.2 cgi true
596 eval("\$result = (boolean)($search);");
597 if ($result and is_array($p)) {
598 return $this->_bound();
605 ////////////////////////////////////////////////////////////////
607 // Remaining classes are private.
609 ////////////////////////////////////////////////////////////////
611 * Virtual base class for nodes in a TextSearchQuery parse tree.
613 * Also serves as a 'VOID' (contentless) node.
615 class TextSearchQuery_node
621 * Optimize this node.
622 * @return object Optimized node.
624 function optimize() {
629 * @return regexp matching this node.
636 * @param bool True if this node has been negated (higher in the parse tree.)
637 * @return array A list of all non-negated words contained by this node.
639 function highlight_words($negated = false) {
643 function sql() { return $this->word; }
645 function _sql_quote() {
647 $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
648 return $request->_dbi->_backend->qstr($word);
653 * A word. exact or substring?
655 class TextSearchQuery_node_word
656 extends TextSearchQuery_node
659 var $_op = TSQ_TOK_WORD;
661 function TextSearchQuery_node_word($word) {
665 return '(?=.*\b' . preg_quote($this->word, '/') . '\b)';
667 function highlight_words ($negated = false) {
668 return $negated ? array() : array($this->word);
670 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
673 class TextSearchQuery_node_all
674 extends TextSearchQuery_node {
676 var $_op = TSQ_TOK_ALL;
677 function regexp() { return '(?=.*)'; }
678 function sql() { return '%'; }
680 class TextSearchQuery_node_starts_with
681 extends TextSearchQuery_node_word {
682 var $op = "STARTS_WITH";
683 var $_op = TSQ_TOK_STARTS_WITH;
684 function regexp() { return '(?=.*\b' . preg_quote($this->word, '/') . ')'; }
685 function sql () { return $this->_sql_quote($this->word).'%'; }
688 class TextSearchQuery_node_ends_with
689 extends TextSearchQuery_node_word {
690 var $op = "ENDS_WITH";
691 var $_op = TSQ_TOK_ENDS_WITH;
692 function regexp() { return '(?=.*' . preg_quote($this->word, '/') . '\b)'; }
693 function sql () { return '%'.$this->_sql_quote($this->word); }
696 class TextSearchQuery_node_exact
697 extends TextSearchQuery_node_word {
699 var $_op = TSQ_TOK_EXACT;
700 function regexp() { return '(?=\b' . preg_quote($this->word, '/') . '\b)'; }
701 function sql () { return $this->_sql_squote($this->word); }
704 class TextSearchQuery_node_regex // posix regex. FIXME!
705 extends TextSearchQuery_node_word {
706 var $op = "REGEX"; // using REGEXP or ~ extension
707 var $_op = TSQ_TOK_REGEX;
708 function regexp() { return '(?=.*\b' . $this->word . '\b)'; }
709 function sql () { return $this->_sql_quote($this->word); }
712 class TextSearchQuery_node_regex_glob
713 extends TextSearchQuery_node_regex {
714 var $op = "REGEX_GLOB";
715 var $_op = TSQ_TOK_REGEX_GLOB;
716 function regexp() { return '(?=.*\b' . glob_to_pcre($this->word) . '\b)'; }
719 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
720 extends TextSearchQuery_node_regex {
721 var $op = "REGEX_PCRE";
722 var $_op = TSQ_TOK_REGEX_PCRE;
723 function regexp() { return $this->word; }
726 class TextSearchQuery_node_regex_sql
727 extends TextSearchQuery_node_regex {
728 var $op = "REGEX_SQL"; // using LIKE
729 var $_op = TSQ_TOK_REGEX_SQL;
730 function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
731 function sql() { return $this->word; }
737 class TextSearchQuery_node_not
738 extends TextSearchQuery_node
741 var $_op = TSQ_TOK_NOT;
743 function TextSearchQuery_node_not($leaf) {
744 $this->leaves = array($leaf);
747 function optimize() {
748 $leaf = &$this->leaves[0];
749 $leaf = $leaf->optimize();
750 if ($leaf->_op == TSQ_TOK_NOT)
751 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
756 $leaf = &$this->leaves[0];
757 return '(?!' . $leaf->regexp() . ')';
760 function highlight_words ($negated = false) {
761 return $this->leaves[0]->highlight_words(!$negated);
766 * Virtual base class for 'AND' and 'OR conjoins.
768 class TextSearchQuery_node_binop
769 extends TextSearchQuery_node
771 var $_op = TSQ_TOK_BINOP;
772 function TextSearchQuery_node_binop($leaves) {
773 $this->leaves = $leaves;
776 function _flatten() {
777 // This flattens e.g. (AND (AND a b) (OR c d) e)
778 // to (AND a b e (OR c d))
780 foreach ($this->leaves as $leaf) {
781 $leaf = $leaf->optimize();
782 if ($this->op == $leaf->op)
783 $flat = array_merge($flat, $leaf->leaves);
787 $this->leaves = $flat;
790 function optimize() {
792 assert(!empty($this->leaves));
793 if (count($this->leaves) == 1)
794 return $this->leaves[0]; // (AND x) -> x
798 function highlight_words($negated = false) {
800 foreach ($this->leaves as $leaf)
801 array_splice($words,0,0,
802 $leaf->highlight_words($negated));
808 * A (possibly multi-argument) 'AND' conjoin.
810 class TextSearchQuery_node_and
811 extends TextSearchQuery_node_binop
815 function optimize() {
818 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
819 // Since OR's are more efficient for regexp matching:
820 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
822 // Suck out the negated leaves.
824 foreach ($this->leaves as $key => $leaf) {
825 if ($leaf->_op == TSQ_TOK_NOT) {
826 $nots[] = $leaf->leaves[0];
827 unset($this->leaves[$key]);
831 // Combine the negated leaves into a single negated or.
833 $node = ( new TextSearchQuery_node_not
834 (new TextSearchQuery_node_or($nots)) );
835 array_unshift($this->leaves, $node->optimize());
838 assert(!empty($this->leaves));
839 if (count($this->leaves) == 1)
840 return $this->leaves[0]; // (AND x) -> x
845 * Either we need all combinations of all words to be position independent,
846 * or we have to use multiple match calls for each AND
847 * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
851 foreach ($this->leaves as $leaf)
852 $regexp .= $leaf->regexp();
858 * A (possibly multi-argument) 'OR' conjoin.
860 class TextSearchQuery_node_or
861 extends TextSearchQuery_node_binop
866 // We will combine any of our direct descendents which are WORDs
867 // into a single (?=.*(?:word1|word2|...)) regexp.
872 foreach ($this->leaves as $leaf) {
873 if ($leaf->op == TSQ_TOK_WORD)
874 $words[] = preg_quote($leaf->word, '/');
876 $regexps[] = $leaf->regexp();
880 array_unshift($regexps,
881 '(?=.*' . $this->_join($words) . ')');
883 return $this->_join($regexps);
886 function _join($regexps) {
887 assert(count($regexps) > 0);
889 if (count($regexps) > 1)
890 return '(?:' . join('|', $regexps) . ')';
897 ////////////////////////////////////////////////////////////////
900 // op's (and, or, not) are forced to lowercase in the tokenizer.
902 ////////////////////////////////////////////////////////////////
903 class TextSearchQuery_Parser
906 * This is a simple recursive descent parser, based on the following grammar:
921 * atom : '(' list ')'
926 * The terminal tokens are:
933 * /[^-()\s][^()\s]* WORD
944 function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
945 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
946 $this->_regex = $regex;
947 $tree = $this->get_list('toplevel');
948 assert($this->lexer->eof());
953 function get_list ($is_toplevel = false) {
956 // token types we'll accept as words (and thus expr's) for the
957 // purpose of error recovery:
958 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
960 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
962 while ( ($expr = $this->get_expr())
963 || ($expr = $this->get_word($accept_as_words)) )
970 return new TextSearchQuery_node;
974 return new TextSearchQuery_node_and($list);
977 function get_expr () {
978 if ( ($expr = $this->get_atom()) === false ) // protect against '0'
981 $savedpos = $this->lexer->tell();
982 // Bug#1791564: allow string '0'
983 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) !== false) {
984 if ( ! ($right = $this->get_atom()) ) {
989 $expr = new TextSearchQuery_node_and(array($expr, $right));
992 $expr = new TextSearchQuery_node_or(array($expr, $right));
995 $savedpos = $this->lexer->tell();
997 $this->lexer->seek($savedpos);
1003 function get_atom() {
1004 if ($atom = $this->get_word(TSQ_ALLWORDS)) // Bug#1791564 not involved: '*'
1007 $savedpos = $this->lexer->tell();
1008 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
1009 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) ) {
1013 // Handle " ( " or "(test" without closing ")" as plain word
1014 $this->lexer->seek($savedpos);
1015 return new TextSearchQuery_node_word($this->lexer->get(-1));
1018 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
1019 if ( ($atom = $this->get_atom()) )
1020 return new TextSearchQuery_node_not($atom);
1022 $this->lexer->seek($savedpos);
1026 function get_word($accept = TSQ_ALLWORDS) {
1027 // Performance shortcut for ( and ). This is always false
1028 if (!empty($this->lexer->tokens[$this->lexer->pos])) {
1029 list ($type, $val) = $this->lexer->tokens[$this->lexer->pos];
1030 if ($type == TSQ_TOK_LPAREN or $type == TSQ_TOK_RPAREN)
1033 foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
1034 "REGEX","REGEX_GLOB","REGEX_PCRE","ALL") as $tok) {
1035 $const = constant("TSQ_TOK_".$tok);
1036 // Bug#1791564: allow word '0'
1037 if ( $accept & $const and
1038 (($word = $this->lexer->get($const)) !== false))
1040 $classname = "TextSearchQuery_node_".strtolower($tok);
1041 return new $classname($word);
1048 class TextSearchQuery_Lexer {
1049 function TextSearchQuery_Lexer ($query_str, $case_exact=false,
1050 $regex=TSQ_REGEX_AUTO)
1052 $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
1060 function seek($pos) {
1065 return $this->pos == count($this->tokens);
1069 * TODO: support more regex styles, esp. prefer the forced ones over auto
1072 function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
1074 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
1075 while (!empty($buf)) {
1076 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
1077 $val = strtolower($m[1]);
1078 $type = TSQ_TOK_BINOP;
1080 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
1081 $val = strtolower($m[1]);
1082 $type = TSQ_TOK_NOT;
1084 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
1086 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
1090 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1091 and preg_match('/^\*\s*/', $buf, $m)) {
1093 $type = TSQ_TOK_ALL;
1096 elseif ($regex & (TSQ_REGEX_PCRE)
1097 and preg_match('/^\.\*\s*/', $buf, $m)) {
1099 $type = TSQ_TOK_ALL;
1102 elseif ($regex & (TSQ_REGEX_SQL)
1103 and preg_match('/^%\s*/', $buf, $m)) {
1105 $type = TSQ_TOK_ALL;
1109 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1110 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
1112 $type = TSQ_TOK_STARTS_WITH;
1115 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1116 and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
1118 $type = TSQ_TOK_STARTS_WITH;
1121 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1122 and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
1124 $type = TSQ_TOK_ENDS_WITH;
1127 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1128 and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
1130 $type = TSQ_TOK_ENDS_WITH;
1133 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1134 and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
1136 $type = TSQ_TOK_EXACT;
1140 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
1141 $val = str_replace('""', '"', $m[1]);
1142 $type = TSQ_TOK_WORD;
1145 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
1146 $val = str_replace("''", "'", $m[1]);
1147 $type = TSQ_TOK_WORD;
1150 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
1152 $type = TSQ_TOK_WORD;
1155 assert(empty($buf));
1158 $buf = substr($buf, strlen($m[0]));
1160 /* refine the simple parsing from above: bla*bla, bla?bla, ...
1161 if ($regex and $type == TSQ_TOK_WORD) {
1162 if (substr($val,0,1) == "^")
1163 $type = TSQ_TOK_STARTS_WITH;
1164 elseif (substr($val,0,1) == "*")
1165 $type = TSQ_TOK_ENDS_WITH;
1166 elseif (substr($val,-1,1) == "*")
1167 $type = TSQ_TOK_STARTS_WITH;
1170 $tokens[] = array($type, $val);
1175 function get($accept) {
1176 if ($this->pos >= count($this->tokens))
1179 list ($type, $val) = $this->tokens[$this->pos];
1180 if (($type & $accept) == 0)
1188 // $Log: not supported by cvs2svn $
1189 // Revision 1.31 2007/09/12 19:36:47 rurban
1190 // Fix Bug#1792170: Handle " ( " or "(test" without closing ")" as plain word. Allow single string token "0"
1192 // Revision 1.30 2007/07/14 12:31:00 rurban
1193 // fix bug#1752172 undefined method TextSearchQuery_node_or::_sql_quote()
1195 // Revision 1.29 2007/07/14 12:03:38 rurban
1196 // support ranked search: simple score() function
1198 // Revision 1.28 2007/03/18 17:35:26 rurban
1201 // Revision 1.27 2007/01/21 23:27:32 rurban
1202 // Fix ->_backend->qstr()
1204 // Revision 1.26 2007/01/04 16:41:52 rurban
1205 // Improve error description. Fix the function parser for illegal functions, when the tokenizer cannot be used.
1207 // Revision 1.25 2007/01/03 21:22:34 rurban
1208 // add getType(). NumericSearchQuery::check Improve hacker detection using token_get_all(). Better support for multiple attributes. Add getVars().
1210 // Revision 1.24 2007/01/02 13:19:05 rurban
1211 // add NumericSearchQuery. change on pcre: no parsing done, detect modifiers
1213 // Revision 1.23 2006/04/13 19:30:44 rurban
1214 // make TextSearchQuery->_stoplist localizable and overridable within config.ini
1220 // c-basic-offset: 4
1221 // c-hanging-comment-ender-p: nil
1222 // indent-tabs-mode: nil