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->_regex_modifier = ($case_exact?'':'i').'sS';
116 $this->_case_exact = $case_exact;
117 if ($regex != 'pcre') {
118 $parser = new TextSearchQuery_Parser;
119 $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex);
120 $this->_optimize(); // broken under certain circumstances: "word -word -word"
121 if (defined("FULLTEXTSEARCH_STOPLIST"))
122 $this->_stoplist = FULLTEXTSEARCH_STOPLIST;
123 else // default stoplist, localizable.
124 $this->_stoplist = _("(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)");
127 $this->_tree = new TextSearchQuery_node_regex_pcre($search_query);
128 if (preg_match("/^\/(.*)\/(\w*)$/", $search_query, $m)) {
129 $this->_tree->word = $m[1];
130 $this->_regex_modifier = $m[2]; // overrides case_exact
135 function getType() { return 'text'; }
137 function _optimize() {
138 $this->_tree = $this->_tree->optimize();
142 * Get a PCRE regexp which matches the query.
144 function asRegexp() {
145 if (!isset($this->_regexp)) {
146 if (!isset($this->_regex_modifier))
147 $this->_regex_modifier = ($this->_case_exact?'':'i').'sS';
149 $this->_regexp = '/' . $this->_tree->regexp() . '/'.$this->_regex_modifier;
151 $this->_regexp = '/^' . $this->_tree->regexp() . '/'.$this->_regex_modifier;
153 return $this->_regexp;
157 * Match query against string.
158 * EXACT ("Term") ignores the case_exact setting.
160 * @param $string string The string to match.
161 * @return boolean True if the string matches the query.
163 function match($string) {
164 if ($this->_tree->_op == TSQ_TOK_ALL) return true;
165 if ($this->_tree->_op == TSQ_TOK_EXACT) return $this->_tree->word == $string;
166 return preg_match($this->asRegexp(), $string);
169 /* How good does it match? Returns a number */
170 function score($string) {
173 foreach (array_unique($this->_tree->highlight_words()) as $word) {
174 if ($nummatch = preg_match_all("/".preg_quote($word, '/')."/".
175 $this->_regex_modifier,
177 $score += ($i-- * $nummatch);
179 return min(1.0, $score / 10.0);
184 * Get a regular expression suitable for highlighting matched words.
186 * This returns a PCRE regular expression which matches any non-negated
189 * @return string The PCRE regexp.
191 function getHighlightRegexp() {
192 if (!isset($this->_hilight_regexp)) {
193 $words = array_unique($this->_tree->highlight_words());
195 $this->_hilight_regexp = false;
197 foreach ($words as $key => $word)
198 $words[$key] = preg_quote($word, '/');
199 $this->_hilight_regexp = '(?'.($this->_case_exact?'':'i').':'
200 . join('|', $words) . ')';
203 return $this->_hilight_regexp;
207 * Make an SQL clause which matches the query.
208 * Deprecated, use makeSqlClauseObj instead.
210 * @param $make_sql_clause_cb WikiCallback
211 * A callback which takes a single word as an argument and
212 * returns an SQL clause which will match exactly those records
213 * containing the word. The word passed to the callback will always
214 * be in all lower case.
216 * Support db-specific extensions, like MATCH AGAINST or REGEX
217 * mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
218 * by using makeSqlClauseObj
222 * function sql_title_match($word) {
223 * return sprintf("LOWER(title) like '%s'",
224 * addslashes($word));
229 * $query = new TextSearchQuery("wiki -page");
230 * $cb = new WikiFunctionCb('sql_title_match');
231 * $sql_clause = $query->makeSqlClause($cb);
233 * This will result in $sql_clause containing something like
234 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
236 * @return string The SQL clause.
238 function makeSqlClause($sql_clause_cb) {
239 $this->_sql_clause_cb = $sql_clause_cb;
240 return $this->_sql_clause($this->_tree);
242 // deprecated: use _sql_clause_obj now.
243 function _sql_clause($node) {
244 switch ($node->_op) {
245 case TSQ_TOK_WORD: // word => %word%
246 return $this->_sql_clause_cb->call($node->word);
248 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
250 $subclauses = array();
251 foreach ($node->leaves as $leaf)
252 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
253 return join(" $node->op ", $subclauses);
255 assert($node->_op == TSQ_TOK_VOID);
260 /** Get away with the callback and use a db-specific search class instead.
261 * @see WikiDB_backend_PearDB_search
263 function makeSqlClauseObj(&$sql_search_cb) {
264 $this->_sql_clause_cb = $sql_search_cb;
265 return $this->_sql_clause_obj($this->_tree);
268 function _sql_clause_obj($node) {
269 switch ($node->_op) {
271 return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
273 $subclauses = array();
274 foreach ($node->leaves as $leaf)
275 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
276 return join(" $node->op ", $subclauses);
282 return $this->_sql_clause_cb->call($node);
287 postgresql tsearch2 uses no WHERE operators, just & | and ! in the searchstring
289 function makeTsearch2SqlClauseObj(&$sql_search_cb) {
290 $this->_sql_clause_cb = $sql_search_cb;
291 return $this->_Tsearch2Sql_clause_obj($this->_tree);
294 function _Tsearch2Sql_clause_obj($node) {
295 // TODO: "such a phrase"
296 switch ($node->_op) {
298 return "!" . $node->leaves[0];
300 $subclauses = array();
301 foreach ($node->leaves as $leaf)
302 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
303 return join($node->_op == 'AND' ? "&" : "|", $subclauses);
309 return $this->_sql_clause_cb->call($node);
313 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
316 * Get printable representation of the parse tree.
318 * This is for debugging only.
319 * @return string Printable parse tree.
321 function asString() {
322 return $this->_as_string($this->_tree);
325 function _as_string($node, $indent = '') {
326 switch ($node->_op) {
328 return $indent . "WORD: $node->word";
330 return $indent . "VOID";
332 return $indent . "ALL";
334 $lines = array($indent . $node->op . ":");
336 foreach ($node->leaves as $leaf)
337 $lines[] = $this->_as_string($leaf, $indent);
338 return join("\n", $lines);
344 * This is a TextSearchQuery which matches nothing.
346 class NullTextSearchQuery extends TextSearchQuery {
348 * Create a new query.
350 * @see TextSearchQuery
352 function NullTextSearchQuery() {}
353 function asRegexp() { return '/^(?!a)a/x'; }
354 function match($string) { return false; }
355 function getHighlightRegexp() { return ""; }
356 function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
357 function asString() { return "NullTextSearchQuery"; }
361 * A simple algebraic matcher for numeric attributes.
362 * NumericSearchQuery can do ("population < 20000 and area > 1000000", array("population", "area"))
363 * ->match(array('population' => 100000, 'area' => 10000000))
365 * Supports all mathematical PHP comparison operators, plus ':=' for equality.
366 * "(x < 2000000 and x >= 10000) or (x >= 100 and x < 2000)"
367 * "x := 100000" is the same as "x == 100000"
369 * Since this is basic numerics only, we simply try to get away with
370 * replacing the variable values at the right positions and do an eval then.
372 * @package NumericSearchQuery
373 * @author Reini Urban
374 * @see SemanticAttributeSearchQuery
376 class NumericSearchQuery
379 * Create a new query.
380 * NumericSearchQuery("population > 20000 or population < 200", "population")
381 * NumericSearchQuery("population < 20000 and area > 1000000", array("population", "area"))
383 * With a single variable it is easy: The valid name must be matched elsewhere, just
384 * replace the given number in match in the query.
387 * With matching a struct we need strict names, no * as name is allowed.
388 * So always when the placeholder is an array, the names of the target struct must match
389 * and all vars be defined. Use the method can_match($struct) therefore.
392 * @param $search_query string A numerical query with placeholders as variable.
393 * @param $placeholders array or string All placeholders in the query must be defined
394 * here, and will be replaced by the matcher.
396 function NumericSearchQuery($search_query, $placeholders) {
397 // added some basic security checks against user input
398 $this->_query = $search_query;
399 $this->_placeholders = $placeholders;
401 // we should also allow the M_ constants
402 $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');
403 $this->_allowed_operators = explode(',', '-,<,<=,>,>=,==,!=,*,+,/,(,),%,and,or,xor,<<,>>,===,!==,&,^,|,&&,||');
404 $this->_parser_check = array();
405 // check should be fast, so make a hash
406 foreach ($this->_allowed_functions as $f)
407 $this->_parser_check[$f] = 1;
408 foreach ($this->_allowed_operators as $f)
409 $this->_parser_check[$f] = 1;
410 if (is_array($placeholders))
411 foreach ($placeholders as $f)
412 $this->_parser_check[$f] = 1;
413 else $this->_parser_check[$placeholders] = 1;
415 // This is a speciality: := looks like the attribute definition and is
416 // therefore a dummy check for this definition.
417 // php-4.2.2 has a problem with /\b:=\b/ matching "population := 1223400"
418 $this->_query = preg_replace("/:=/", "==", $this->_query);
419 $this->_query = $this->check_query($this->_query);
422 function getType() { return 'numeric'; }
425 * Check the symbolic definition query against unwanted functions and characters.
426 * "population < 20000 and area > 1000000" vs
427 * "area > 1000000 and mail($me,file("/etc/passwd"),...)"
428 * http://localhost/wikicvs/SemanticSearch?attribute=*&attr_op=<0 and find(1)>&s=-0.01&start_debug=1
430 function check_query ($query) {
431 $tmp = $query; // check for all function calls, in case the tokenizer is not available.
432 while (preg_match("/([a-z][a-z0-9]+)\s*\((.*)$/i", $tmp, $m)) {
433 if (!in_array($m[1], $this->_allowed_functions)
434 and !in_array($m[1], $this->_allowed_operators))
436 trigger_error("Illegal function in query: ".$m[1], E_USER_WARNING);
442 // Strictly check for illegal functions and operators, which are no placeholders.
443 if (function_exists('token_get_all')) {
444 $parsed = token_get_all("<?$query?>");
445 foreach ($parsed as $x) { // flat, non-recursive array
446 if (is_string($x) and !isset($this->_parser_check[$x])) {
447 // single char op or name
448 trigger_error("Illegal string or operator in query: \"$x\"", E_USER_WARNING);
451 elseif (is_array($x)) {
452 $n = token_name($x[0]);
453 if ($n == 'T_OPEN_TAG' or $n == 'T_WHITESPACE'
454 or $n == 'T_CLOSE_TAG' or $n == 'T_LNUMBER'
455 or $n == 'T_CONST' or $n == 'T_DNUMBER' ) continue;
456 if ($n == 'T_VARIABLE') { // but we do allow consts
457 trigger_error("Illegal variable in query: \"$x[1]\"", E_USER_WARNING);
460 if (is_string($x[1]) and !isset($this->_parser_check[$x[1]])) {
461 // multi-char char op or name
462 trigger_error("Illegal $n in query: \"$x[1]\"", E_USER_WARNING);
467 //echo "$query <br>";
468 //$this->_parse_token($parsed);
473 { T_OPEN_TAG "<?"} { T_STRING "_x"} { T_WHITESPACE " "} ">" { T_WHITESPACE " "} { T_LNUMBER "0"} { T_CLOSE_TAG "?>"}
474 Interesting: on-char ops, as ">" are not tokenized.
476 { T_OPEN_TAG "< ?" } { T_STRING "_x" } { T_WHITESPACE " " } { T_IS_SMALLER_OR_EQUAL "<=" } { T_WHITESPACE " " } { T_LNUMBER "0" } { T_CLOSE_TAG "?>" }
479 // Detect illegal characters besides nums, words and ops.
480 // So attribute names can not be utf-8
481 $c = "/([^\d\w.,\s".preg_quote(join("",$this->_allowed_operators),"/")."])/";
482 if (preg_match($c, $query, $m)) {
483 trigger_error("Illegal character in query: ".$m[1], E_USER_WARNING);
491 * Check the bound, numeric-only query against unwanted functions and sideeffects.
492 * "4560000 < 20000 and 1456022 > 1000000"
494 function _live_check () {
495 // TODO: check $this->_workquery again?
496 return !empty($this->_workquery);
500 * A numeric query can only operate with predefined variables. "x < 0 and y < 1"
502 * @return array The names as array of strings. => ('x', 'y') the placeholders.
505 if(is_array($this->_placeholders)) return $this->_placeholders;
506 else return array($this->_placeholders);
510 * Strip non-numeric chars from the variable (as the groupseperator) and replace
511 * it in the symbolic query for evaluation.
514 * @param $value number A numerical value: integer, float or string.
515 * @param $x string The variable name to be replaced in the query.
518 function _bind($value, $x) {
519 // TODO: check is_number, is_float, is_integer and do casting
520 $this->_bound[] = array('linkname' => $x,
521 'linkvalue' => $value);
522 $value = preg_replace("/[^-+0123456789.,]/", "", $value);
523 //$c = "/\b".preg_quote($x,"/")."\b/";
524 $this->_workquery = preg_replace("/\b".preg_quote($x,"/")."\b/", $value, $this->_workquery);
525 // FIXME: do again a final check. now only numbers and some operators are allowed.
526 return $this->_workquery;
529 /* array of successfully bound vars, and in case of success, the resulting vars
532 return $this->_bound;
536 * With an array of placeholders we need a hash to check against, if all required names are given.
537 * Purpose: Be silent about missing vars, just return false.
540 * @param $variable string or hash of name => value The keys must satisfy all placeholders in the definition.
541 * We want the full hash and not just the keys because a hash check is faster than the array of keys check.
544 function can_match(&$variables) {
545 if (empty($this->_query))
547 $p =& $this->_placeholders;
548 if (!is_array($variables) and !is_array($p))
549 return $variables == $p; // This was easy.
550 // Check if all placeholders have definitions. can be overdefined but not underdefined.
552 if (!isset($variables[$p])) return false;
555 if (!isset($variables[$x])) return false;
562 * We can match against a single variable or against a hash of variables.
563 * With one placeholder we need just a number.
564 * With an array of placeholders we need a hash.
567 * @param $variable number or array of name => value The keys must satisfy all placeholders in the definition.
570 function match(&$variable) {
571 $p =& $this->_placeholders;
572 $this->_workquery = $this->_query;
574 if (is_array($variable)) { // which var to match? we cannot decide this here
575 if (!isset($variable[$p]))
576 trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR);
577 $this->_bind($variable[$p], $p);
579 $this->_bind($variable, $p);
583 if (!isset($variable[$x]))
584 trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR);
585 $this->_bind($variable[$x], $x);
588 if (!$this->_live_check()) // check returned an error
590 $search = $this->_workquery;
592 //if (DEBUG & _DEBUG_VERBOSE)
593 // trigger_error("\$result = (boolean)($search);", E_USER_NOTICE);
594 // We might have a numerical problem:
595 // php-4.2.2 eval'ed as module: "9.636e+08 > 1000" false;
596 // php-5.1.2 cgi true, 4.2.2 cgi true
597 eval("\$result = (boolean)($search);");
598 if ($result and is_array($p)) {
599 return $this->_bound();
606 ////////////////////////////////////////////////////////////////
608 // Remaining classes are private.
610 ////////////////////////////////////////////////////////////////
612 * Virtual base class for nodes in a TextSearchQuery parse tree.
614 * Also serves as a 'VOID' (contentless) node.
616 class TextSearchQuery_node
622 * Optimize this node.
623 * @return object Optimized node.
625 function optimize() {
630 * @return regexp matching this node.
637 * @param bool True if this node has been negated (higher in the parse tree.)
638 * @return array A list of all non-negated words contained by this node.
640 function highlight_words($negated = false) {
644 function sql() { return $this->word; }
646 function _sql_quote() {
648 $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
649 return $request->_dbi->_backend->qstr($word);
654 * A word. exact or substring?
656 class TextSearchQuery_node_word
657 extends TextSearchQuery_node
660 var $_op = TSQ_TOK_WORD;
662 function TextSearchQuery_node_word($word) {
666 return '(?=.*\b' . preg_quote($this->word, '/') . '\b)';
668 function highlight_words ($negated = false) {
669 return $negated ? array() : array($this->word);
671 function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
674 class TextSearchQuery_node_all
675 extends TextSearchQuery_node {
677 var $_op = TSQ_TOK_ALL;
678 function regexp() { return '(?=.*)'; }
679 function sql() { return '%'; }
681 class TextSearchQuery_node_starts_with
682 extends TextSearchQuery_node_word {
683 var $op = "STARTS_WITH";
684 var $_op = TSQ_TOK_STARTS_WITH;
685 function regexp() { return '(?=.*\b' . preg_quote($this->word, '/') . ')'; }
686 function sql () { return $this->_sql_quote($this->word).'%'; }
689 class TextSearchQuery_node_ends_with
690 extends TextSearchQuery_node_word {
691 var $op = "ENDS_WITH";
692 var $_op = TSQ_TOK_ENDS_WITH;
693 function regexp() { return '(?=.*' . preg_quote($this->word, '/') . '\b)'; }
694 function sql () { return '%'.$this->_sql_quote($this->word); }
697 class TextSearchQuery_node_exact
698 extends TextSearchQuery_node_word {
700 var $_op = TSQ_TOK_EXACT;
701 function regexp() { return '(?=\b' . preg_quote($this->word, '/') . '\b)'; }
702 function sql () { return $this->_sql_squote($this->word); }
705 class TextSearchQuery_node_regex // posix regex. FIXME!
706 extends TextSearchQuery_node_word {
707 var $op = "REGEX"; // using REGEXP or ~ extension
708 var $_op = TSQ_TOK_REGEX;
709 function regexp() { return '(?=.*\b' . $this->word . '\b)'; }
710 function sql () { return $this->_sql_quote($this->word); }
713 class TextSearchQuery_node_regex_glob
714 extends TextSearchQuery_node_regex {
715 var $op = "REGEX_GLOB";
716 var $_op = TSQ_TOK_REGEX_GLOB;
717 function regexp() { return '(?=.*\b' . glob_to_pcre($this->word) . '\b)'; }
720 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
721 extends TextSearchQuery_node_regex {
722 var $op = "REGEX_PCRE";
723 var $_op = TSQ_TOK_REGEX_PCRE;
724 function regexp() { return $this->word; }
727 class TextSearchQuery_node_regex_sql
728 extends TextSearchQuery_node_regex {
729 var $op = "REGEX_SQL"; // using LIKE
730 var $_op = TSQ_TOK_REGEX_SQL;
731 function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
732 function sql() { return $this->word; }
738 class TextSearchQuery_node_not
739 extends TextSearchQuery_node
742 var $_op = TSQ_TOK_NOT;
744 function TextSearchQuery_node_not($leaf) {
745 $this->leaves = array($leaf);
748 function optimize() {
749 $leaf = &$this->leaves[0];
750 $leaf = $leaf->optimize();
751 if ($leaf->_op == TSQ_TOK_NOT)
752 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
757 $leaf = &$this->leaves[0];
758 return '(?!' . $leaf->regexp() . ')';
761 function highlight_words ($negated = false) {
762 return $this->leaves[0]->highlight_words(!$negated);
767 * Virtual base class for 'AND' and 'OR conjoins.
769 class TextSearchQuery_node_binop
770 extends TextSearchQuery_node
772 var $_op = TSQ_TOK_BINOP;
773 function TextSearchQuery_node_binop($leaves) {
774 $this->leaves = $leaves;
777 function _flatten() {
778 // This flattens e.g. (AND (AND a b) (OR c d) e)
779 // to (AND a b e (OR c d))
781 foreach ($this->leaves as $leaf) {
782 $leaf = $leaf->optimize();
783 if ($this->op == $leaf->op)
784 $flat = array_merge($flat, $leaf->leaves);
788 $this->leaves = $flat;
791 function optimize() {
793 assert(!empty($this->leaves));
794 if (count($this->leaves) == 1)
795 return $this->leaves[0]; // (AND x) -> x
799 function highlight_words($negated = false) {
801 foreach ($this->leaves as $leaf)
802 array_splice($words,0,0,
803 $leaf->highlight_words($negated));
809 * A (possibly multi-argument) 'AND' conjoin.
811 class TextSearchQuery_node_and
812 extends TextSearchQuery_node_binop
816 function optimize() {
819 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
820 // Since OR's are more efficient for regexp matching:
821 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
823 // Suck out the negated leaves.
825 foreach ($this->leaves as $key => $leaf) {
826 if ($leaf->_op == TSQ_TOK_NOT) {
827 $nots[] = $leaf->leaves[0];
828 unset($this->leaves[$key]);
832 // Combine the negated leaves into a single negated or.
834 $node = ( new TextSearchQuery_node_not
835 (new TextSearchQuery_node_or($nots)) );
836 array_unshift($this->leaves, $node->optimize());
839 assert(!empty($this->leaves));
840 if (count($this->leaves) == 1)
841 return $this->leaves[0]; // (AND x) -> x
846 * Either we need all combinations of all words to be position independent,
847 * or we have to use multiple match calls for each AND
848 * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
852 foreach ($this->leaves as $leaf)
853 $regexp .= $leaf->regexp();
859 * A (possibly multi-argument) 'OR' conjoin.
861 class TextSearchQuery_node_or
862 extends TextSearchQuery_node_binop
867 // We will combine any of our direct descendents which are WORDs
868 // into a single (?=.*(?:word1|word2|...)) regexp.
873 foreach ($this->leaves as $leaf) {
874 if ($leaf->op == TSQ_TOK_WORD)
875 $words[] = preg_quote($leaf->word, '/');
877 $regexps[] = $leaf->regexp();
881 array_unshift($regexps,
882 '(?=.*' . $this->_join($words) . ')');
884 return $this->_join($regexps);
887 function _join($regexps) {
888 assert(count($regexps) > 0);
890 if (count($regexps) > 1)
891 return '(?:' . join('|', $regexps) . ')';
898 ////////////////////////////////////////////////////////////////
901 // op's (and, or, not) are forced to lowercase in the tokenizer.
903 ////////////////////////////////////////////////////////////////
904 class TextSearchQuery_Parser
907 * This is a simple recursive descent parser, based on the following grammar:
922 * atom : '(' list ')'
927 * The terminal tokens are:
934 * /[^-()\s][^()\s]* WORD
945 function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
946 $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
947 $this->_regex = $regex;
948 $tree = $this->get_list('toplevel');
949 assert($this->lexer->eof());
954 function get_list ($is_toplevel = false) {
957 // token types we'll accept as words (and thus expr's) for the
958 // purpose of error recovery:
959 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
961 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
963 while ( ($expr = $this->get_expr())
964 || ($expr = $this->get_word($accept_as_words)) )
971 return new TextSearchQuery_node;
975 return new TextSearchQuery_node_and($list);
978 function get_expr () {
979 if ( ($expr = $this->get_atom()) === false ) // protect against '0'
982 $savedpos = $this->lexer->tell();
983 // Bug#1791564: allow string '0'
984 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) !== false) {
985 if ( ! ($right = $this->get_atom()) ) {
990 $expr = new TextSearchQuery_node_and(array($expr, $right));
993 $expr = new TextSearchQuery_node_or(array($expr, $right));
996 $savedpos = $this->lexer->tell();
998 $this->lexer->seek($savedpos);
1004 function get_atom() {
1005 if ($atom = $this->get_word(TSQ_ALLWORDS)) // Bug#1791564 not involved: '*'
1008 $savedpos = $this->lexer->tell();
1009 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
1010 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) ) {
1014 // Handle " ( " or "(test" without closing ")" as plain word
1015 $this->lexer->seek($savedpos);
1016 return new TextSearchQuery_node_word($this->lexer->get(-1));
1019 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
1020 if ( ($atom = $this->get_atom()) )
1021 return new TextSearchQuery_node_not($atom);
1023 $this->lexer->seek($savedpos);
1027 function get_word($accept = TSQ_ALLWORDS) {
1028 // Performance shortcut for ( and ). This is always false
1029 if (!empty($this->lexer->tokens[$this->lexer->pos])) {
1030 list ($type, $val) = $this->lexer->tokens[$this->lexer->pos];
1031 if ($type == TSQ_TOK_LPAREN or $type == TSQ_TOK_RPAREN)
1034 foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
1035 "REGEX","REGEX_GLOB","REGEX_PCRE","ALL") as $tok) {
1036 $const = constant("TSQ_TOK_".$tok);
1037 // Bug#1791564: allow word '0'
1038 if ( $accept & $const and
1039 (($word = $this->lexer->get($const)) !== false))
1041 $classname = "TextSearchQuery_node_".strtolower($tok);
1042 return new $classname($word);
1049 class TextSearchQuery_Lexer {
1050 function TextSearchQuery_Lexer ($query_str, $case_exact=false,
1051 $regex=TSQ_REGEX_AUTO)
1053 $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
1061 function seek($pos) {
1066 return $this->pos == count($this->tokens);
1070 * TODO: support more regex styles, esp. prefer the forced ones over auto
1073 function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
1075 $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
1076 while (!empty($buf)) {
1077 if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
1078 $val = strtolower($m[1]);
1079 $type = TSQ_TOK_BINOP;
1081 elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
1082 $val = strtolower($m[1]);
1083 $type = TSQ_TOK_NOT;
1085 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
1087 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
1091 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1092 and preg_match('/^\*\s*/', $buf, $m)) {
1094 $type = TSQ_TOK_ALL;
1097 elseif ($regex & (TSQ_REGEX_PCRE)
1098 and preg_match('/^\.\*\s*/', $buf, $m)) {
1100 $type = TSQ_TOK_ALL;
1103 elseif ($regex & (TSQ_REGEX_SQL)
1104 and preg_match('/^%\s*/', $buf, $m)) {
1106 $type = TSQ_TOK_ALL;
1110 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1111 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
1113 $type = TSQ_TOK_STARTS_WITH;
1116 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1117 and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
1119 $type = TSQ_TOK_STARTS_WITH;
1122 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1123 and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
1125 $type = TSQ_TOK_ENDS_WITH;
1128 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1129 and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
1131 $type = TSQ_TOK_ENDS_WITH;
1134 elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1135 and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
1137 $type = TSQ_TOK_EXACT;
1141 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
1142 $val = str_replace('""', '"', $m[1]);
1143 $type = TSQ_TOK_WORD;
1146 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
1147 $val = str_replace("''", "'", $m[1]);
1148 $type = TSQ_TOK_WORD;
1151 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
1153 $type = TSQ_TOK_WORD;
1156 assert(empty($buf));
1159 $buf = substr($buf, strlen($m[0]));
1161 /* refine the simple parsing from above: bla*bla, bla?bla, ...
1162 if ($regex and $type == TSQ_TOK_WORD) {
1163 if (substr($val,0,1) == "^")
1164 $type = TSQ_TOK_STARTS_WITH;
1165 elseif (substr($val,0,1) == "*")
1166 $type = TSQ_TOK_ENDS_WITH;
1167 elseif (substr($val,-1,1) == "*")
1168 $type = TSQ_TOK_STARTS_WITH;
1171 $tokens[] = array($type, $val);
1176 function get($accept) {
1177 if ($this->pos >= count($this->tokens))
1180 list ($type, $val) = $this->tokens[$this->pos];
1181 if (($type & $accept) == 0)
1192 // c-basic-offset: 4
1193 // c-hanging-comment-ender-p: nil
1194 // indent-tabs-mode: nil