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