]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/TextSearchQuery.php
use And by default; cleanup
[SourceForge/phpwiki.git] / lib / TextSearchQuery.php
1 <?php
2 /**
3  * A text search query, converting queries to PCRE and SQL matchers.
4  *
5  * This represents an enhanced "Google-like" text search query:
6  * <dl>
7  * <dt> default: case-insensitive glob-style search with special operators OR AND NOT -
8  * <dt> wiki -test
9  *   <dd> Match strings containing the substring 'wiki', and NOT containing the
10  *        substring 'test'.
11  * <dt> wiki word or page
12  *   <dd> Match strings containing the substring 'wiki' AND either the substring
13  *        'word' OR the substring 'page'.
14  * <dt> auto-detect regex hints, glob-style or regex-style, and converts them
15  *      to PCRE and SQL matchers:
16  *   <dd> "^word$" => EXACT(phrase)
17  *   <dd> "^word"  => STARTS_WITH(phrase)
18  *   <dd> "word$"  => ENDS_WITH(phrase)
19  *   <dd> "^word" ... => STARTS_WITH(word)
20  *   <dd> "word$" ... => ENDS_WITH(word)
21  *   <dd> "word*"  => STARTS_WITH(word)
22  *   <dd> "*word"  => ENDS_WITH(word)
23  *   <dd> "/^word.* /" => REGEX(^word.*)
24  *   <dd> "word*word" => REGEX(word.*word)
25  * </dl>
26  *
27  * The full query syntax, in order of precedence, is roughly:
28  *
29  * The unary 'NOT' or '-' operator (they are equivalent) negates the
30  * following search clause.
31  *
32  * Search clauses may be joined with the (left-associative) binary operators
33  * 'AND' and 'OR'. (case-insensitive)
34  *
35  * Two adjoining search clauses are joined with an implicit 'AND'.  This has
36  * lower precedence than either an explicit 'AND' or 'OR', so "a b OR c"
37  * parses as "a AND ( b OR c )", while "a AND b OR c" parses as
38  * "( a AND b ) OR c" (due to the left-associativity of 'AND' and 'OR'.)
39  *
40  * Search clauses can be grouped with parentheses.
41  *
42  * Phrases (or other things which don't look like words) can be forced to
43  * be interpreted as words by quoting them, either with single (') or double (")
44  * quotes.  If you wan't to include the quote character within a quoted string,
45  * double-up on the quote character: 'I''m hungry' is equivalent to
46  * "I'm hungry".
47  *
48  * Force regex on "re:word" => posix-style, "/word/" => pcre-style
49  * or use regex='glob' to use file wildcard-like matching. (not yet)
50  *
51  * The parsed tree is then converted to the needed PCRE (highlight,
52  * simple backends) or SQL functions.
53  *
54  * @author: Jeff Dairiki
55  * @author: Reini Urban (case and regex detection, enhanced sql callbacks)
56  */
57
58 // regex-style: 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
59 define ('TSQ_REGEX_NONE', 0);
60 define ('TSQ_REGEX_AUTO', 1);
61 define ('TSQ_REGEX_POSIX', 2);
62 define ('TSQ_REGEX_GLOB', 4);
63 define ('TSQ_REGEX_PCRE', 8);
64 define ('TSQ_REGEX_SQL', 16);
65
66 define ('TSQ_TOK_VOID', 0);
67 define ('TSQ_TOK_BINOP', 1);
68 define ('TSQ_TOK_NOT', 2);
69 define ('TSQ_TOK_LPAREN', 4);
70 define ('TSQ_TOK_RPAREN', 8);
71 define ('TSQ_TOK_WORD', 16);
72 define ('TSQ_TOK_STARTS_WITH', 32);
73 define ('TSQ_TOK_ENDS_WITH', 64);
74 define ('TSQ_TOK_EXACT', 128);
75 define ('TSQ_TOK_REGEX', 256);
76 define ('TSQ_TOK_REGEX_GLOB', 512);
77 define ('TSQ_TOK_REGEX_PCRE', 1024);
78 define ('TSQ_TOK_REGEX_SQL', 2048);
79 define ('TSQ_TOK_ALL', 4096);
80 // all bits from word to the last.
81 define ('TSQ_ALLWORDS', (4096 * 2) - 1 - (16 - 1));
82
83 class TextSearchQuery
84 {
85     private $sql_clause_cb;
86     private $word;
87
88     /**
89      * Create a new query.
90      *
91      * @param $search_query string The query.  Syntax is as described above.
92      * Note that an empty $search_query will match anything.
93      * @param $case_exact boolean
94      * @param $regex string one of 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
95      * @see TextSearchQuery
96      */
97     function TextSearchQuery($search_query, $case_exact = false, $regex = 'auto')
98     {
99         if ($regex == 'none' or !$regex)
100             $this->_regex = 0;
101         elseif (defined("TSQ_REGEX_" . strtoupper($regex)))
102             $this->_regex = constant("TSQ_REGEX_" . strtoupper($regex)); else {
103             trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex));
104             $this->_regex = 0;
105         }
106         $this->_regex_modifier = ($case_exact ? '' : 'i') . 'sS';
107         $this->_case_exact = $case_exact;
108         if ($regex != 'pcre') {
109             $parser = new TextSearchQuery_Parser;
110             $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex);
111             $this->optimize(); // broken under certain circumstances: "word -word -word"
112             if (defined("FULLTEXTSEARCH_STOPLIST"))
113                 $this->_stoplist = FULLTEXTSEARCH_STOPLIST;
114             else // default stoplist, localizable.
115                 $this->_stoplist = _("(A|An|And|But|By|For|From|In|Is|It|Of|On|Or|The|To|With)");
116         } else {
117             $this->_tree = new TextSearchQuery_node_regex_pcre($search_query);
118             if (preg_match("/^\/(.*)\/(\w*)$/", $search_query, $m)) {
119                 $this->_tree->word = $m[1];
120                 $this->_regex_modifier = $m[2]; // overrides case_exact
121             }
122         }
123     }
124
125     function getType()
126     {
127         return 'text';
128     }
129
130     private function optimize()
131     {
132         $this->_tree = $this->_tree->optimize();
133     }
134
135     /**
136      * Get a PCRE regexp which matches the query.
137      */
138     function asRegexp()
139     {
140         if (!isset($this->_regexp)) {
141             if (!isset($this->_regex_modifier))
142                 $this->_regex_modifier = ($this->_case_exact ? '' : 'i') . 'sS';
143             if ($this->_regex)
144                 $this->_regexp = '/' . $this->_tree->regexp() . '/' . $this->_regex_modifier;
145             else
146                 $this->_regexp = '/^' . $this->_tree->regexp() . '/' . $this->_regex_modifier;
147         }
148         return $this->_regexp;
149     }
150
151     /**
152      * Match query against string.
153      * EXACT ("Term") ignores the case_exact setting.
154      *
155      * @param $string string The string to match.
156      * @return boolean True if the string matches the query.
157      */
158     function match($string)
159     {
160         if ($this->_tree->_op == TSQ_TOK_ALL) return true;
161         if ($this->_tree->_op == TSQ_TOK_EXACT) return $this->_tree->word == $string;
162         return preg_match($this->asRegexp(), $string);
163     }
164
165     /* How good does it match? Returns a number */
166     function score($string)
167     {
168         $score = 0.0;
169         $i = 10;
170         foreach (array_unique($this->_tree->highlight_words()) as $word) {
171             if ($nummatch = preg_match_all("/" . preg_quote($word, '/') . "/" .
172                     $this->_regex_modifier,
173                 $string, $out)
174             )
175                 $score += ($i-- * $nummatch);
176         }
177         return min(1.0, $score / 10.0);
178     }
179
180     /**
181      * Get a regular expression suitable for highlighting matched words.
182      *
183      * This returns a PCRE regular expression which matches any non-negated
184      * word in the query.
185      *
186      * @return string The PCRE regexp.
187      */
188     function getHighlightRegexp()
189     {
190         if (!isset($this->_hilight_regexp)) {
191             $words = array_unique($this->_tree->highlight_words());
192             if (!$words) {
193                 $this->_hilight_regexp = false;
194             } else {
195                 foreach ($words as $key => $word)
196                     $words[$key] = preg_quote($word, '/');
197                 $this->_hilight_regexp = '(?' . ($this->_case_exact ? '' : 'i') . ':'
198                     . join('|', $words) . ')';
199             }
200         }
201         return $this->_hilight_regexp;
202     }
203
204     /** Get away with the callback and use a db-specific search class instead.
205      * @see WikiDB_backend_PearDB_search
206      */
207     function makeSqlClauseObj(&$sql_search_cb)
208     {
209         $this->sql_clause_cb = $sql_search_cb;
210         return $this->sql_clause_obj($this->_tree);
211     }
212
213     private function sql_clause_obj($node)
214     {
215         switch ($node->_op) {
216             case TSQ_TOK_NOT:
217                 return "NOT (" . $this->sql_clause_cb->call($node->leaves[0]) . ")";
218             case TSQ_TOK_BINOP:
219                 $subclauses = array();
220                 foreach ($node->leaves as $leaf)
221                     $subclauses[] = "(" . $this->sql_clause_obj($leaf) . ")";
222                 return join(" $node->op ", $subclauses);
223             case TSQ_TOK_VOID:
224                 return '0=1';
225             case TSQ_TOK_ALL:
226                 return '1=1';
227             default:
228                 return $this->sql_clause_cb->call($node);
229         }
230     }
231
232     /*
233      postgresql tsearch2 uses no WHERE operators, just & | and ! in the searchstring
234      */
235     function makeTsearch2SqlClauseObj(&$sql_search_cb)
236     {
237         $this->sql_clause_cb = $sql_search_cb;
238         return $this->Tsearch2Sql_clause_obj($this->_tree);
239     }
240
241     private function Tsearch2Sql_clause_obj($node)
242     {
243         // TODO: "such a phrase"
244         switch ($node->_op) {
245             case TSQ_TOK_NOT:
246                 return "!" . $node->leaves[0];
247             case TSQ_TOK_BINOP:
248                 $subclauses = array();
249                 foreach ($node->leaves as $leaf)
250                     $subclauses[] = $this->Tsearch2Sql_clause_obj($leaf);
251                 return join($node->_op == 'OR' ? "|" : "&", $subclauses);
252             case TSQ_TOK_VOID:
253                 return '';
254             case TSQ_TOK_ALL:
255                 return '1';
256             default:
257                 return $this->sql_clause_cb->call($node);
258         }
259     }
260
261     function sql()
262     {
263         return '%' . $this->_sql_quote($this->word) . '%';
264     }
265
266     /**
267      * Get printable representation of the parse tree.
268      *
269      * This is for debugging only.
270      * @return string Printable parse tree.
271      */
272     function asString()
273     {
274         return $this->as_string($this->_tree);
275     }
276
277     private function as_string($node, $indent = '')
278     {
279         switch ($node->_op) {
280             case TSQ_TOK_WORD:
281                 return $indent . "WORD: $node->word";
282             case TSQ_TOK_VOID:
283                 return $indent . "VOID";
284             case TSQ_TOK_ALL:
285                 return $indent . "ALL";
286             default:
287                 $lines = array($indent . $node->op . ":");
288                 $indent .= "  ";
289                 foreach ($node->leaves as $leaf)
290                     $lines[] = $this->as_string($leaf, $indent);
291                 return join("\n", $lines);
292         }
293     }
294 }
295
296 /**
297  * This is a TextSearchQuery which matches nothing.
298  */
299 class NullTextSearchQuery extends TextSearchQuery
300 {
301     /**
302      * Create a new query.
303      *
304      * @see TextSearchQuery
305      */
306     function NullTextSearchQuery()
307     {
308     }
309
310     function asRegexp()
311     {
312         return '/^(?!a)a/x';
313     }
314
315     function match($string)
316     {
317         return false;
318     }
319
320     function getHighlightRegexp()
321     {
322         return "";
323     }
324
325     function asString()
326     {
327         return "NullTextSearchQuery";
328     }
329 }
330
331 /**
332  * A simple algebraic matcher for numeric attributes.
333  *  NumericSearchQuery can do ("population < 20000 and area > 1000000", array("population", "area"))
334  *  ->match(array('population' => 100000, 'area' => 10000000))
335  *
336  * Supports all mathematical PHP comparison operators, plus ':=' for equality.
337  *   "(x < 2000000 and x >= 10000) or (x >= 100 and x < 2000)"
338  *   "x := 100000" is the same as "x == 100000"
339  *
340  * Since this is basic numerics only, we simply try to get away with
341  * replacing the variable values at the right positions and do an eval then.
342  *
343  * @package NumericSearchQuery
344  * @author Reini Urban
345  * @see SemanticAttributeSearchQuery
346  */
347 class NumericSearchQuery
348 {
349     protected $bound;
350     protected $workquery;
351
352     /**
353      * Create a new query.
354      *   NumericSearchQuery("population > 20000 or population < 200", "population")
355      *   NumericSearchQuery("population < 20000 and area > 1000000", array("population", "area"))
356      *
357      * With a single variable it is easy: The valid name must be matched elsewhere, just
358      * replace the given number in match in the query.
359      *   ->match(2000)
360      *
361      * With matching a struct we need strict names, no * as name is allowed.
362      * So always when the placeholder is an array, the names of the target struct must match
363      * and all vars be defined. Use the method can_match($struct) therefore.
364      *
365      * @access public
366      * @param $search_query string   A numerical query with placeholders as variable.
367      * @param $placeholders array or string  All placeholders in the query must be defined
368      *     here, and will be replaced by the matcher.
369      */
370     function NumericSearchQuery($search_query, $placeholders)
371     {
372         // added some basic security checks against user input
373         $this->_query = $search_query;
374         $this->_placeholders = $placeholders;
375
376         // we should also allow the M_ constants
377         $this->_allowed_functions = explode(':', 'abs:acos:acosh:asin:asinh:atan2:atan:atanh:base_convert:bindec:ceil:cos:cosh:decbin:dechex:decoct:deg2rad:exp:expm1:floor:fmod:getrandmax:hexdec:hypot:is_finite:is_infinite:is_nan:lcg_value:log10:log1p:log:max:min:mt_getrandmax:mt_rand:mt_srand:octdec:pi:pow:rad2deg:rand:round:sin:sinh:sqrt:srand:tan:tanh');
378         $this->_allowed_operators = explode(',', '-,<,<=,>,>=,==,!=,*,+,/,(,),%,and,or,xor,<<,>>,===,!==,&,^,|,&&,||');
379         $this->_parser_check = array();
380         // check should be fast, so make a hash
381         foreach ($this->_allowed_functions as $f)
382             $this->_parser_check[$f] = 1;
383         foreach ($this->_allowed_operators as $f)
384             $this->_parser_check[$f] = 1;
385         if (is_array($placeholders))
386             foreach ($placeholders as $f)
387                 $this->_parser_check[$f] = 1;
388         else $this->_parser_check[$placeholders] = 1;
389
390         // This is a speciality: := looks like the attribute definition and is
391         // therefore a dummy check for this definition.
392         // php-4.2.2 has a problem with /\b:=\b/ matching "population := 1223400"
393         $this->_query = preg_replace("/:=/", "==", $this->_query);
394         $this->_query = $this->check_query($this->_query);
395     }
396
397     function getType()
398     {
399         return 'numeric';
400     }
401
402     /**
403      * Check the symbolic definition query against unwanted functions and characters.
404      * "population < 20000 and area > 1000000" vs
405      *   "area > 1000000 and mail($me,file("/etc/passwd"),...)"
406      * http://localhost/wikicvs/SemanticSearch?attribute=*&attr_op=<0 and find(1)>&s=-0.01&start_debug=1
407      */
408     function check_query($query)
409     {
410         $tmp = $query; // check for all function calls, in case the tokenizer is not available.
411         while (preg_match("/([a-z][a-z0-9]+)\s*\((.*)$/i", $tmp, $m)) {
412             if (!in_array($m[1], $this->_allowed_functions)
413                 and !in_array($m[1], $this->_allowed_operators)
414             ) {
415                 trigger_error("Illegal function in query: " . $m[1], E_USER_WARNING);
416                 return '';
417             }
418             $tmp = $m[2];
419         }
420
421         // Strictly check for illegal functions and operators, which are no placeholders.
422         if (function_exists('token_get_all')) {
423             $parsed = token_get_all("<?$query?>");
424             foreach ($parsed as $x) { // flat, non-recursive array
425                 if (is_string($x) and !isset($this->_parser_check[$x])) {
426                     // single char op or name
427                     trigger_error("Illegal string or operator in query: \"$x\"", E_USER_WARNING);
428                     $query = '';
429                 } elseif (is_array($x)) {
430                     $n = token_name($x[0]);
431                     if ($n == 'T_OPEN_TAG' or $n == 'T_WHITESPACE'
432                         or $n == 'T_CLOSE_TAG' or $n == 'T_LNUMBER'
433                         or $n == 'T_CONST' or $n == 'T_DNUMBER'
434                     ) continue;
435                     if ($n == 'T_VARIABLE') { // but we do allow consts
436                         trigger_error("Illegal variable in query: \"$x[1]\"", E_USER_WARNING);
437                         $query = '';
438                     }
439                     if (is_string($x[1]) and !isset($this->_parser_check[$x[1]])) {
440                         // multi-char char op or name
441                         trigger_error("Illegal $n in query: \"$x[1]\"", E_USER_WARNING);
442                         $query = '';
443                     }
444                 }
445             }
446             //echo "$query <br>";
447             //$this->_parse_token($parsed);
448             //echo "<br>\n";
449             //var_dump($parsed);
450             /*
451     "_x > 0" =>
452     { T_OPEN_TAG "<?"} { T_STRING "_x"} { T_WHITESPACE " "} ">" { T_WHITESPACE " "} { T_LNUMBER "0"} { T_CLOSE_TAG "?>"}
453         Interesting: on-char ops, as ">" are not tokenized.
454     "_x <= 0"
455     { T_OPEN_TAG "< ?" } { T_STRING "_x" } { T_WHITESPACE " " } { T_IS_SMALLER_OR_EQUAL "<=" } { T_WHITESPACE " " } { T_LNUMBER "0" } { T_CLOSE_TAG "?>" }
456              */
457         } else {
458             // Detect illegal characters besides nums, words and ops.
459             // So attribute names can not be utf-8
460             $c = "/([^\d\w.,\s" . preg_quote(join("", $this->_allowed_operators), "/") . "])/";
461             if (preg_match($c, $query, $m)) {
462                 trigger_error("Illegal character in query: " . $m[1], E_USER_WARNING);
463                 return '';
464             }
465         }
466         return $query;
467     }
468
469     /**
470      * Check the bound, numeric-only query against unwanted functions and sideeffects.
471      * "4560000 < 20000 and 1456022 > 1000000"
472      */
473     private function live_check()
474     {
475         // TODO: check $this->_workquery again?
476         return !empty($this->workquery);
477     }
478
479     /**
480      * A numeric query can only operate with predefined variables. "x < 0 and y < 1"
481      *
482      * @return array The names as array of strings. => ('x', 'y') the placeholders.
483      */
484     function getVars()
485     {
486         if (is_array($this->_placeholders)) return $this->_placeholders;
487         else return array($this->_placeholders);
488     }
489
490     /**
491      * Strip non-numeric chars from the variable (as the groupseperator) and replace
492      * it in the symbolic query for evaluation.
493      *
494      * @access private
495      * @param $value number   A numerical value: integer, float or string.
496      * @param $x string       The variable name to be replaced in the query.
497      * @return string
498      */
499     private function bind($value, $x)
500     {
501         // TODO: check is_number, is_float, is_integer and do casting
502         $this->bound[] = array('linkname' => $x,
503             'linkvalue' => $value);
504         $value = preg_replace("/[^-+0123456789.,]/", "", $value);
505         //$c = "/\b".preg_quote($x,"/")."\b/";
506         $this->workquery = preg_replace("/\b" . preg_quote($x, "/") . "\b/", $value, $this->workquery);
507         // FIXME: do again a final check. now only numbers and some operators are allowed.
508         return $this->workquery;
509     }
510
511     /* array of successfully bound vars, and in case of success, the resulting vars
512      */
513     private function bound()
514     {
515         return $this->bound;
516     }
517
518     /**
519      * With an array of placeholders we need a hash to check against, if all required names are given.
520      * Purpose: Be silent about missing vars, just return false.
521     `*
522      * @access public
523      * @param string $variables string or hash of name => value  The keys must satisfy all placeholders in the definition.
524      * We want the full hash and not just the keys because a hash check is faster than the array of keys check.
525      * @return boolean
526      */
527     function can_match(&$variables)
528     {
529         if (empty($this->_query))
530             return false;
531         $p =& $this->_placeholders;
532         if (!is_array($variables) and !is_array($p))
533             return $variables == $p; // This was easy.
534         // Check if all placeholders have definitions. can be overdefined but not underdefined.
535         if (!is_array($p)) {
536             if (!isset($variables[$p])) return false;
537         } else {
538             foreach ($p as $x) {
539                 if (!isset($variables[$x])) return false;
540             }
541         }
542         return true;
543     }
544
545     /**
546      * We can match against a single variable or against a hash of variables.
547      * With one placeholder we need just a number.
548      * With an array of placeholders we need a hash.
549      *
550      * @access public
551      * @param $variable number or array of name => value  The keys must satisfy all placeholders in the definition.
552      * @return boolean
553      */
554     function match(&$variable)
555     {
556         $p =& $this->_placeholders;
557         $this->workquery = $this->_query;
558         if (!is_array($p)) {
559             if (is_array($variable)) { // which var to match? we cannot decide this here
560                 if (!isset($variable[$p]))
561                     trigger_error("Required NumericSearchQuery->match variable $p not defined.", E_USER_ERROR);
562                 $this->bind($variable[$p], $p);
563             } else {
564                 $this->bind($variable, $p);
565             }
566         } else {
567             foreach ($p as $x) {
568                 if (!isset($variable[$x]))
569                     trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR);
570                 $this->bind($variable[$x], $x);
571             }
572         }
573         if (!$this->live_check()) // check returned an error
574             return false;
575         $search = $this->workquery;
576         $result = false;
577         //if (DEBUG & _DEBUG_VERBOSE)
578         //    trigger_error("\$result = (boolean)($search);", E_USER_NOTICE);
579         // We might have a numerical problem:
580         // php-4.2.2 eval'ed as module: "9.636e+08 > 1000" false;
581         // php-5.1.2 cgi true, 4.2.2 cgi true
582         eval("\$result = (boolean)($search);");
583         if ($result and is_array($p)) {
584             return $this->bound();
585         }
586         return $result;
587     }
588 }
589
590 ////////////////////////////////////////////////////////////////
591 //
592 // Remaining classes are private.
593 //
594 ////////////////////////////////////////////////////////////////
595 /**
596  * Virtual base class for nodes in a TextSearchQuery parse tree.
597  *
598  * Also serves as a 'VOID' (contentless) node.
599  */
600 class TextSearchQuery_node
601 {
602     public $op = 'VOID';
603     public $_op = 0;
604     public $word;
605
606     /**
607      * Optimize this node.
608      * @return object Optimized node.
609      */
610     function optimize()
611     {
612         return $this;
613     }
614
615     /**
616      * @return string regexp matching this node.
617      */
618     function regexp()
619     {
620         return '';
621     }
622
623     /**
624      * @param bool $negated True if this node has been negated (higher in the parse tree.)
625      * @return array A list of all non-negated words contained by this node.
626      */
627     function highlight_words($negated = false)
628     {
629         return array();
630     }
631
632     function sql()
633     {
634         return $this->word;
635     }
636
637     protected function sql_quote()
638     {
639         global $request;
640         $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
641         return $request->_dbi->_backend->qstr($word);
642     }
643 }
644
645 /**
646  * A word. Exact or substring?
647  */
648 class TextSearchQuery_node_word
649     extends TextSearchQuery_node
650 {
651     public $op = "WORD";
652     public $_op = TSQ_TOK_WORD;
653
654     function TextSearchQuery_node_word($word)
655     {
656         $this->word = $word;
657     }
658
659     function regexp()
660     {
661         return '(?=.*\b' . preg_quote($this->word, '/') . '\b)';
662     }
663
664     function highlight_words($negated = false)
665     {
666         return $negated ? array() : array($this->word);
667     }
668
669     function sql()
670     {
671         return '%' . $this->sql_quote($this->word) . '%';
672     }
673 }
674
675 class TextSearchQuery_node_all
676     extends TextSearchQuery_node
677 {
678     public $op = "ALL";
679     public $_op = TSQ_TOK_ALL;
680
681     function regexp()
682     {
683         return '(?=.*)';
684     }
685
686     function sql()
687     {
688         return '%';
689     }
690 }
691
692 class TextSearchQuery_node_starts_with
693     extends TextSearchQuery_node_word
694 {
695     public $op = "STARTS_WITH";
696     public $_op = TSQ_TOK_STARTS_WITH;
697
698     function regexp()
699     {
700         return '(?=.*\b' . preg_quote($this->word, '/') . ')';
701     }
702
703     function sql()
704     {
705         return $this->sql_quote($this->word) . '%';
706     }
707 }
708
709 // ^word: full phrase starts with
710 class TextSearchQuery_phrase_starts_with
711     extends TextSearchQuery_node_starts_with
712 {
713     function regexp()
714     {
715         return '(?=^' . preg_quote($this->word, '/') . ')';
716     }
717 }
718
719 class TextSearchQuery_node_ends_with
720     extends TextSearchQuery_node_word
721 {
722     public $op = "ENDS_WITH";
723     public $_op = TSQ_TOK_ENDS_WITH;
724
725     function regexp()
726     {
727         return '(?=.*' . preg_quote($this->word, '/') . '\b)';
728     }
729
730     function sql()
731     {
732         return '%' . $this->sql_quote($this->word);
733     }
734 }
735
736 // word$: full phrase ends with
737 class TextSearchQuery_phrase_ends_with
738     extends TextSearchQuery_node_ends_with
739 {
740     function regexp()
741     {
742         return '(?=' . preg_quote($this->word, '/') . '$)';
743     }
744 }
745
746 class TextSearchQuery_node_exact
747     extends TextSearchQuery_node_word
748 {
749     public $op = "EXACT";
750     public $_op = TSQ_TOK_EXACT;
751
752     function regexp()
753     {
754         return '(?=\b' . preg_quote($this->word, '/') . '\b)';
755     }
756
757     function sql()
758     {
759         return $this->_sql_squote($this->word);
760     }
761 }
762
763 class TextSearchQuery_node_regex // posix regex. FIXME!
764     extends TextSearchQuery_node_word
765 {
766     public $op = "REGEX"; // using REGEXP or ~ extension
767     public $_op = TSQ_TOK_REGEX;
768
769     function regexp()
770     {
771         return '(?=.*\b' . $this->word . '\b)';
772     }
773
774     function sql()
775     {
776         return $this->sql_quote($this->word);
777     }
778 }
779
780 class TextSearchQuery_node_regex_glob
781     extends TextSearchQuery_node_regex
782 {
783     public $op = "REGEX_GLOB";
784     public $_op = TSQ_TOK_REGEX_GLOB;
785
786     function regexp()
787     {
788         return '(?=.*\b' . glob_to_pcre($this->word) . '\b)';
789     }
790 }
791
792 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
793     extends TextSearchQuery_node_regex
794 {
795     public $op = "REGEX_PCRE";
796     public $_op = TSQ_TOK_REGEX_PCRE;
797
798     function regexp()
799     {
800         return $this->word;
801     }
802 }
803
804 class TextSearchQuery_node_regex_sql
805     extends TextSearchQuery_node_regex
806 {
807     public $op = "REGEX_SQL"; // using LIKE
808     public $_op = TSQ_TOK_REGEX_SQL;
809
810     function regexp()
811     {
812         return str_replace(array("/%/", "/_/"), array(".*", "."), $this->word);
813     }
814
815     function sql()
816     {
817         return $this->word;
818     }
819 }
820
821 /**
822  * A negated clause.
823  */
824 class TextSearchQuery_node_not
825     extends TextSearchQuery_node
826 {
827     public $op = "NOT";
828     public $_op = TSQ_TOK_NOT;
829
830     function TextSearchQuery_node_not($leaf)
831     {
832         $this->leaves = array($leaf);
833     }
834
835     function optimize()
836     {
837         $leaf = &$this->leaves[0];
838         $leaf = $leaf->optimize();
839         if ($leaf->_op == TSQ_TOK_NOT)
840             return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
841         return $this;
842     }
843
844     function regexp()
845     {
846         $leaf = &$this->leaves[0];
847         return '(?!' . $leaf->regexp() . ')';
848     }
849
850     function highlight_words($negated = false)
851     {
852         return $this->leaves[0]->highlight_words(!$negated);
853     }
854 }
855
856 /**
857  * Virtual base class for 'AND' and 'OR conjoins.
858  */
859 class TextSearchQuery_node_binop
860     extends TextSearchQuery_node
861 {
862     public $_op = TSQ_TOK_BINOP;
863
864     function TextSearchQuery_node_binop($leaves)
865     {
866         $this->leaves = $leaves;
867     }
868
869     protected function flatten()
870     {
871         // This flattens e.g. (AND (AND a b) (OR c d) e)
872         //        to (AND a b e (OR c d))
873         $flat = array();
874         foreach ($this->leaves as $leaf) {
875             $leaf = $leaf->optimize();
876             if ($this->op == $leaf->op)
877                 $flat = array_merge($flat, $leaf->leaves);
878             else
879                 $flat[] = $leaf;
880         }
881         $this->leaves = $flat;
882     }
883
884     function optimize()
885     {
886         $this->flatten();
887         assert(!empty($this->leaves));
888         if (count($this->leaves) == 1)
889             return $this->leaves[0]; // (AND x) -> x
890         return $this;
891     }
892
893     function highlight_words($negated = false)
894     {
895         $words = array();
896         foreach ($this->leaves as $leaf)
897             array_splice($words, 0, 0,
898                 $leaf->highlight_words($negated));
899         return $words;
900     }
901 }
902
903 /**
904  * A (possibly multi-argument) 'AND' conjoin.
905  */
906 class TextSearchQuery_node_and
907     extends TextSearchQuery_node_binop
908 {
909     public $op = "AND";
910
911     function optimize()
912     {
913         $this->flatten();
914
915         // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
916         // Since OR's are more efficient for regexp matching:
917         //   (?!.*a)(?!.*b)  vs   (?!.*(?:a|b))
918
919         // Suck out the negated leaves.
920         $nots = array();
921         foreach ($this->leaves as $key => $leaf) {
922             if ($leaf->_op == TSQ_TOK_NOT) {
923                 $nots[] = $leaf->leaves[0];
924                 unset($this->leaves[$key]);
925             }
926         }
927
928         // Combine the negated leaves into a single negated or.
929         if ($nots) {
930             $node = (new TextSearchQuery_node_not
931             (new TextSearchQuery_node_or($nots)));
932             array_unshift($this->leaves, $node->optimize());
933         }
934
935         assert(!empty($this->leaves));
936         if (count($this->leaves) == 1)
937             return $this->leaves[0]; // (AND x) -> x
938         return $this;
939     }
940
941     /* FIXME!
942      * Either we need all combinations of all words to be position independent,
943      * or we have to use multiple match calls for each AND
944      * (AND x y) => /(?(:x)(:y))|(?(:y)(:x))/
945      */
946     function regexp()
947     {
948         $regexp = '';
949         foreach ($this->leaves as $leaf)
950             $regexp .= $leaf->regexp();
951         return $regexp;
952     }
953 }
954
955 /**
956  * A (possibly multi-argument) 'OR' conjoin.
957  */
958 class TextSearchQuery_node_or
959     extends TextSearchQuery_node_binop
960 {
961     public $op = "OR";
962
963     function regexp()
964     {
965         // We will combine any of our direct descendents which are WORDs
966         // into a single (?=.*(?:word1|word2|...)) regexp.
967
968         $regexps = array();
969         $words = array();
970
971         foreach ($this->leaves as $leaf) {
972             if ($leaf->op == TSQ_TOK_WORD)
973                 $words[] = preg_quote($leaf->word, '/');
974             else
975                 $regexps[] = $leaf->regexp();
976         }
977
978         if ($words)
979             array_unshift($regexps,
980                 '(?=.*' . $this->join($words) . ')');
981
982         return $this->join($regexps);
983     }
984
985     private function join($regexps)
986     {
987         assert(count($regexps) > 0);
988
989         if (count($regexps) > 1)
990             return '(?:' . join('|', $regexps) . ')';
991         else
992             return $regexps[0];
993     }
994 }
995
996 ////////////////////////////////////////////////////////////////
997 //
998 // Parser:
999 //   op's (and, or, not) are forced to lowercase in the tokenizer.
1000 //
1001 ////////////////////////////////////////////////////////////////
1002 class TextSearchQuery_Parser
1003 {
1004     /*
1005      * This is a simple recursive descent parser, based on the following grammar:
1006      *
1007      * toplist    :
1008      *        | toplist expr
1009      *        ;
1010      *
1011      *
1012      * list    : expr
1013      *        | list expr
1014      *        ;
1015      *
1016      * expr    : atom
1017      *        | expr BINOP atom
1018      *        ;
1019      *
1020      * atom    : '(' list ')'
1021      *        | NOT atom
1022      *        | WORD
1023      *        ;
1024      *
1025      * The terminal tokens are:
1026      *
1027      *
1028      * and|or          BINOP
1029      * -|not          NOT
1030      * (          LPAREN
1031      * )          RPAREN
1032      * /[^-()\s][^()\s]*  WORD
1033      * /"[^"]*"/      WORD
1034      * /'[^']*'/      WORD
1035      *
1036      * ^WORD              TextSearchQuery_phrase_starts_with
1037      * WORD*              STARTS_WITH
1038      * *WORD              ENDS_WITH
1039      * ^WORD$             EXACT
1040      * *                  ALL
1041      */
1042
1043     public $lexer;
1044     private $regex;
1045
1046     function parse($search_expr, $case_exact = false, $regex = TSQ_REGEX_AUTO)
1047     {
1048         $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
1049         $this->regex = $regex;
1050         $tree = $this->get_list('toplevel');
1051         // Assert failure when using the following URL in debug mode.
1052         // /TitleSearch?action=FullTextSearch&s=WFXSSProbe'")/>&case_exact=1&regex=sql
1053         //        assert($this->lexer->eof());
1054         unset($this->lexer);
1055         return $tree;
1056     }
1057
1058     function get_list($is_toplevel = false)
1059     {
1060         $list = array();
1061
1062         // token types we'll accept as words (and thus expr's) for the
1063         // purpose of error recovery:
1064         $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
1065         if ($is_toplevel)
1066             $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
1067
1068         while (($expr = $this->get_expr())
1069             || ($expr = $this->get_word($accept_as_words))) {
1070             $list[] = $expr;
1071         }
1072
1073         if (!$list) {
1074             if ($is_toplevel)
1075                 return new TextSearchQuery_node;
1076             else
1077                 return false;
1078         }
1079         if ($is_toplevel and count($list) == 1) {
1080             if ($this->lexer->query_str[0] == '^')
1081                 return new TextSearchQuery_phrase_starts_with($list[0]->word);
1082             else
1083                 return $list[0];
1084         }
1085         return new TextSearchQuery_node_and($list);
1086     }
1087
1088     function get_expr()
1089     {
1090         if (($expr = $this->get_atom()) === false) // protect against '0'
1091             return false;
1092
1093         $savedpos = $this->lexer->tell();
1094         // Bug#1791564: allow string '0'
1095         while (($op = $this->lexer->get(TSQ_TOK_BINOP)) !== false) {
1096             if (!($right = $this->get_atom())) {
1097                 break;
1098             }
1099
1100             if ($op == 'and')
1101                 $expr = new TextSearchQuery_node_and(array($expr, $right));
1102             else {
1103                 assert($op == 'or');
1104                 $expr = new TextSearchQuery_node_or(array($expr, $right));
1105             }
1106
1107             $savedpos = $this->lexer->tell();
1108         }
1109         $this->lexer->seek($savedpos);
1110
1111         return $expr;
1112     }
1113
1114     function get_atom()
1115     {
1116         if ($atom = $this->get_word(TSQ_ALLWORDS)) // Bug#1791564 not involved: '*'
1117             return $atom;
1118
1119         $savedpos = $this->lexer->tell();
1120         if ($this->lexer->get(TSQ_TOK_LPAREN)) {
1121             if (($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN)) {
1122                 return $list;
1123             } else {
1124                 // Fix Bug#1792170
1125                 // Handle " ( " or "(test" without closing ")" as plain word
1126                 $this->lexer->seek($savedpos);
1127                 return new TextSearchQuery_node_word($this->lexer->get(-1));
1128             }
1129         } elseif ($this->lexer->get(TSQ_TOK_NOT)) {
1130             if (($atom = $this->get_atom()))
1131                 return new TextSearchQuery_node_not($atom);
1132         }
1133         $this->lexer->seek($savedpos);
1134         return false;
1135     }
1136
1137     function get_word($accept = TSQ_ALLWORDS)
1138     {
1139         // Performance shortcut for ( and ). This is always false
1140         if (!empty($this->lexer->tokens[$this->lexer->pos])) {
1141             list ($type, $val) = $this->lexer->tokens[$this->lexer->pos];
1142             if ($type == TSQ_TOK_LPAREN or $type == TSQ_TOK_RPAREN)
1143                 return false;
1144         }
1145         foreach (array("WORD", "STARTS_WITH", "ENDS_WITH", "EXACT",
1146                      "REGEX", "REGEX_GLOB", "REGEX_PCRE", "ALL") as $tok) {
1147             $const = constant("TSQ_TOK_" . $tok);
1148             // Bug#1791564: allow word '0'
1149             if ($accept & $const and
1150                 (($word = $this->lexer->get($const)) !== false)
1151             ) {
1152                 // phrase or word level?
1153                 if ($tok == 'STARTS_WITH' and $this->lexer->query_str[0] == '^')
1154                     $classname = "TextSearchQuery_phrase_" . strtolower($tok);
1155                 elseif ($tok == 'ENDS_WITH' and
1156                     string_ends_with($this->lexer->query_str, '$')
1157                 )
1158                     $classname = "TextSearchQuery_phrase_" . strtolower($tok); else
1159                     $classname = "TextSearchQuery_node_" . strtolower($tok);
1160                 return new $classname($word);
1161             }
1162         }
1163         return false;
1164     }
1165 }
1166
1167 class TextSearchQuery_Lexer
1168 {
1169     function TextSearchQuery_Lexer($query_str, $case_exact = false,
1170                                    $regex = TSQ_REGEX_AUTO)
1171     {
1172         $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
1173         $this->query_str = $query_str;
1174         $this->pos = 0;
1175     }
1176
1177     function tell()
1178     {
1179         return $this->pos;
1180     }
1181
1182     function seek($pos)
1183     {
1184         $this->pos = $pos;
1185     }
1186
1187     function eof()
1188     {
1189         return $this->pos == count($this->tokens);
1190     }
1191
1192     /**
1193      * TODO: support more regex styles, esp. prefer the forced ones over auto
1194      * re: and // stuff
1195      */
1196     function tokenize($string, $case_exact = false, $regex = TSQ_REGEX_AUTO)
1197     {
1198         $tokens = array();
1199         $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
1200         while (!empty($buf)) {
1201             if (preg_match('/^([()])\s*/', $buf, $m)) {
1202                 $val = $m[1];
1203                 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
1204             } // * => ALL
1205             elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_GLOB)
1206                 and preg_match('/^\*\s*/', $buf, $m)
1207             ) {
1208                 $val = "*";
1209                 $type = TSQ_TOK_ALL;
1210             } // .* => ALL
1211             elseif ($regex & (TSQ_REGEX_PCRE)
1212                 and preg_match('/^\.\*\s*/', $buf, $m)
1213             ) {
1214                 $val = ".*";
1215                 $type = TSQ_TOK_ALL;
1216             } // % => ALL
1217             elseif ($regex & (TSQ_REGEX_SQL)
1218                 and preg_match('/^%\s*/', $buf, $m)
1219             ) {
1220                 $val = "%";
1221                 $type = TSQ_TOK_ALL;
1222             } // ^word
1223             elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_PCRE)
1224                 and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)
1225             ) {
1226                 $val = $m[1];
1227                 $type = TSQ_TOK_STARTS_WITH;
1228             } // word*
1229             elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_GLOB)
1230                 and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)
1231             ) {
1232                 $val = $m[1];
1233                 $type = TSQ_TOK_STARTS_WITH;
1234             } // *word
1235             elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_GLOB)
1236                 and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)
1237             ) {
1238                 $val = $m[1];
1239                 $type = TSQ_TOK_ENDS_WITH;
1240             } // word$
1241             elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_PCRE)
1242                 and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)
1243             ) {
1244                 $val = $m[1];
1245                 $type = TSQ_TOK_ENDS_WITH;
1246             } // ^word$
1247             elseif ($regex & (TSQ_REGEX_AUTO | TSQ_REGEX_POSIX | TSQ_REGEX_PCRE)
1248                 and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)
1249             ) {
1250                 $val = $m[1];
1251                 $type = TSQ_TOK_EXACT;
1252             } elseif (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
1253                 $val = strtolower($m[1]);
1254                 $type = TSQ_TOK_BINOP;
1255             } elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
1256                 $val = strtolower($m[1]);
1257                 $type = TSQ_TOK_NOT;
1258             } // "words "
1259             elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
1260                 $val = str_replace('""', '"', $m[1]);
1261                 $type = TSQ_TOK_WORD;
1262             } // 'words '
1263             elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
1264                 $val = str_replace("''", "'", $m[1]);
1265                 $type = TSQ_TOK_WORD;
1266             } // word
1267             elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
1268                 $val = $m[1];
1269                 $type = TSQ_TOK_WORD;
1270             } else {
1271                 assert(empty($buf));
1272                 break;
1273             }
1274             $buf = substr($buf, strlen($m[0]));
1275
1276             /* refine the simple parsing from above: bla*bla, bla?bla, ...
1277             if ($regex and $type == TSQ_TOK_WORD) {
1278                 if (substr($val,0,1) == "^")
1279                     $type = TSQ_TOK_STARTS_WITH;
1280                 elseif (substr($val,0,1) == "*")
1281                     $type = TSQ_TOK_ENDS_WITH;
1282                 elseif (substr($val,-1,1) == "*")
1283                     $type = TSQ_TOK_STARTS_WITH;
1284             }
1285             */
1286             $tokens[] = array($type, $val);
1287         }
1288         return $tokens;
1289     }
1290
1291     function get($accept)
1292     {
1293         if ($this->pos >= count($this->tokens))
1294             return false;
1295
1296         list ($type, $val) = $this->tokens[$this->pos];
1297         if (($type & $accept) == 0)
1298             return false;
1299
1300         $this->pos++;
1301         return $val;
1302     }
1303 }
1304
1305 // Local Variables:
1306 // mode: php
1307 // tab-width: 8
1308 // c-basic-offset: 4
1309 // c-hanging-comment-ender-p: nil
1310 // indent-tabs-mode: nil
1311 // End: