]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/TextSearchQuery.php
Remove history
[SourceForge/phpwiki.git] / lib / TextSearchQuery.php
1 <?php rcs_id('$Id$');
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(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)
22  * </dl>
23  *
24  * The full query syntax, in order of precedence, is roughly:
25  *
26  * The unary 'NOT' or '-' operator (they are equivalent) negates the
27  * following search clause.
28  *
29  * Search clauses may be joined with the (left-associative) binary operators
30  * 'AND' and 'OR'. (case-insensitive)
31  *
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'.)
36  *
37  * Search clauses can be grouped with parentheses.
38  *
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
43  * "I'm hungry".
44  *
45  * Force regex on "re:word" => posix-style, "/word/" => pcre-style 
46  * or use regex='glob' to use file wildcard-like matching. (not yet)
47  *
48  * The parsed tree is then converted to the needed PCRE (highlight, 
49  * simple backends) or SQL functions. 
50  *
51  * @author: Jeff Dairiki
52  * @author: Reini Urban (case and regex detection, enhanced sql callbacks)
53  */
54
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);
62
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));
79
80 /*
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);
93 */
94
95
96 class TextSearchQuery {
97     /**
98      * Create a new query.
99      *
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
105      */
106     function TextSearchQuery($search_query, $case_exact=false, $regex='auto') {
107         if ($regex == 'none' or !$regex) 
108             $this->_regex = 0;
109         elseif (defined("TSQ_REGEX_".strtoupper($regex)))
110             $this->_regex = constant("TSQ_REGEX_".strtoupper($regex));
111         else {
112             trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex));
113             $this->_regex = 0;
114         }
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)");
125         }
126         else {
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
131             }
132         }
133     }
134
135     function getType() { return 'text'; }
136
137     function _optimize() {
138         $this->_tree = $this->_tree->optimize();
139     }
140
141     /**
142      * Get a PCRE regexp which matches the query.
143      */
144     function asRegexp() {
145         if (!isset($this->_regexp)) {
146             if (!isset($this->_regex_modifier)) 
147                 $this->_regex_modifier = ($this->_case_exact?'':'i').'sS';
148             if ($this->_regex)
149                 $this->_regexp =  '/' . $this->_tree->regexp() . '/'.$this->_regex_modifier;
150             else
151                 $this->_regexp =  '/^' . $this->_tree->regexp() . '/'.$this->_regex_modifier;
152         }
153         return $this->_regexp;
154     }
155
156     /**
157      * Match query against string.
158      * EXACT ("Term") ignores the case_exact setting.
159      *
160      * @param $string string The string to match. 
161      * @return boolean True if the string matches the query.
162      */
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);
167     }
168
169     /* How good does it match? Returns a number */
170     function score($string) {
171         $score = 0.0;
172         $i = 10;
173         foreach (array_unique($this->_tree->highlight_words()) as $word) {
174             if ($nummatch = preg_match_all("/".preg_quote($word, '/')."/".
175                                                $this->_regex_modifier, 
176                                            $string, $out))
177                 $score += ($i-- * $nummatch);
178         }
179         return min(1.0, $score / 10.0);
180     }
181
182     
183     /**
184      * Get a regular expression suitable for highlighting matched words.
185      *
186      * This returns a PCRE regular expression which matches any non-negated
187      * word in the query.
188      *
189      * @return string The PCRE regexp.
190      */
191     function getHighlightRegexp() {
192         if (!isset($this->_hilight_regexp)) {
193             $words = array_unique($this->_tree->highlight_words());
194             if (!$words) {
195                 $this->_hilight_regexp = false;
196             } else {
197                 foreach ($words as $key => $word)
198                     $words[$key] = preg_quote($word, '/');
199                 $this->_hilight_regexp = '(?'.($this->_case_exact?'':'i').':' 
200                                              . join('|', $words) . ')';
201             }
202         }
203         return $this->_hilight_regexp;
204     }
205
206     /**
207      * Make an SQL clause which matches the query. 
208      * Deprecated, use makeSqlClauseObj instead.
209      *
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.
215      *
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
219      *
220      * Old example usage:
221      * <pre>
222      *     function sql_title_match($word) {
223      *         return sprintf("LOWER(title) like '%s'",
224      *                        addslashes($word));
225      *     }
226      *
227      *     ...
228      *
229      *     $query = new TextSearchQuery("wiki -page");
230      *     $cb = new WikiFunctionCb('sql_title_match');
231      *     $sql_clause = $query->makeSqlClause($cb);
232      * </pre>
233      * This will result in $sql_clause containing something like
234      * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
235      *
236      * @return string The SQL clause.
237      */
238     function makeSqlClause($sql_clause_cb) {
239         $this->_sql_clause_cb = $sql_clause_cb;
240         return $this->_sql_clause($this->_tree);
241     }
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);
247         case TSQ_TOK_NOT:
248             return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
249         case TSQ_TOK_BINOP:
250             $subclauses = array();
251             foreach ($node->leaves as $leaf)
252                 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
253             return join(" $node->op ", $subclauses);
254         default:
255             assert($node->_op == TSQ_TOK_VOID);
256             return '1=1';
257         }
258     }
259
260     /** Get away with the callback and use a db-specific search class instead.
261      * @see WikiDB_backend_PearDB_search
262      */
263     function makeSqlClauseObj(&$sql_search_cb) {
264         $this->_sql_clause_cb = $sql_search_cb;
265         return $this->_sql_clause_obj($this->_tree);
266     }
267
268     function _sql_clause_obj($node) {
269         switch ($node->_op) {
270         case TSQ_TOK_NOT:
271             return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
272         case TSQ_TOK_BINOP:
273             $subclauses = array();
274             foreach ($node->leaves as $leaf)
275                 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
276             return join(" $node->op ", $subclauses);
277         case TSQ_TOK_VOID:
278             return '0=1';
279         case TSQ_TOK_ALL:
280             return '1=1';
281         default:
282             return $this->_sql_clause_cb->call($node);
283         }
284     }
285
286     /*
287      postgresql tsearch2 uses no WHERE operators, just & | and ! in the searchstring
288      */
289     function makeTsearch2SqlClauseObj(&$sql_search_cb) {
290         $this->_sql_clause_cb = $sql_search_cb;
291         return $this->_Tsearch2Sql_clause_obj($this->_tree);
292     }
293
294     function _Tsearch2Sql_clause_obj($node) {
295         // TODO: "such a phrase"
296         switch ($node->_op) {
297         case TSQ_TOK_NOT:
298             return "!" . $node->leaves[0];
299         case TSQ_TOK_BINOP:
300             $subclauses = array();
301             foreach ($node->leaves as $leaf)
302                 $subclauses[] = $this->_Tsearch2Sql_clause_obj($leaf);
303             return join($node->_op == 'AND' ? "&" : "|", $subclauses);
304         case TSQ_TOK_VOID:
305             return '';
306         case TSQ_TOK_ALL:
307             return '1';
308         default:
309             return $this->_sql_clause_cb->call($node);
310         }
311     }
312
313     function sql() { return '%'.$this->_sql_quote($this->word).'%'; }
314
315     /**
316      * Get printable representation of the parse tree.
317      *
318      * This is for debugging only.
319      * @return string Printable parse tree.
320      */
321     function asString() {
322         return $this->_as_string($this->_tree);
323     }
324
325     function _as_string($node, $indent = '') {
326         switch ($node->_op) {
327         case TSQ_TOK_WORD:
328             return $indent . "WORD: $node->word";
329         case TSQ_TOK_VOID:
330             return $indent . "VOID";
331         case TSQ_TOK_ALL:
332             return $indent . "ALL";
333         default:
334             $lines = array($indent . $node->op . ":");
335             $indent .= "  ";
336             foreach ($node->leaves as $leaf)
337                 $lines[] = $this->_as_string($leaf, $indent);
338             return join("\n", $lines);
339         }
340     }
341 }
342
343 /**
344  * This is a TextSearchQuery which matches nothing.
345  */
346 class NullTextSearchQuery extends TextSearchQuery {
347     /**
348      * Create a new query.
349      *
350      * @see TextSearchQuery
351      */
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"; }
358 };
359
360 /**
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)) 
364  *
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"
368  *
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. 
371  *
372  * @package NumericSearchQuery
373  * @author Reini Urban
374  * @see SemanticAttributeSearchQuery
375  */
376 class NumericSearchQuery
377 {
378     /**
379      * Create a new query.
380      *   NumericSearchQuery("population > 20000 or population < 200", "population")
381      *   NumericSearchQuery("population < 20000 and area > 1000000", array("population", "area"))
382      *
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.
385      *   ->match(2000)
386      *
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.
390      *
391      * @access public
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.
395      */
396     function NumericSearchQuery($search_query, $placeholders) {
397         // added some basic security checks against user input
398         $this->_query = $search_query;
399         $this->_placeholders = $placeholders;
400
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;   
414
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);
420     }
421
422     function getType() { return 'numeric'; }
423
424     /**
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
429      */
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))
435             {
436                 trigger_error("Illegal function in query: ".$m[1], E_USER_WARNING);
437                 return '';
438             }
439             $tmp = $m[2];
440         }
441         
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);
449                     $query = '';
450                 }
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);
458                         $query = '';
459                     }    
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);
463                         $query = '';
464                     }
465                 }
466             }
467             //echo "$query <br>";
468             //$this->_parse_token($parsed);
469             //echo "<br>\n";
470             //var_dump($parsed);
471             /* 
472 "_x > 0" => 
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.
475 "_x <= 0"
476 { T_OPEN_TAG "< ?" } { T_STRING "_x" } { T_WHITESPACE " " } { T_IS_SMALLER_OR_EQUAL "<=" } { T_WHITESPACE " " } { T_LNUMBER "0" } { T_CLOSE_TAG "?>" }
477              */
478         } else {
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);
484                 return '';
485             }
486         }
487         return $query;
488     }
489
490     /**
491      * Check the bound, numeric-only query against unwanted functions and sideeffects.
492      * "4560000 < 20000 and 1456022 > 1000000"
493      */
494     function _live_check () {
495         // TODO: check $this->_workquery again?
496         return !empty($this->_workquery);
497     }
498
499     /**
500      * A numeric query can only operate with predefined variables. "x < 0 and y < 1"
501      *
502      * @return array The names as array of strings. => ('x', 'y') the placeholders.
503      */
504     function getVars() {
505         if(is_array($this->_placeholders)) return $this->_placeholders;
506         else return array($this->_placeholders);
507     }
508
509     /**
510      * Strip non-numeric chars from the variable (as the groupseperator) and replace 
511      * it in the symbolic query for evaluation.
512      *
513      * @access private
514      * @param $value number   A numerical value: integer, float or string.
515      * @param $x string       The variable name to be replaced in the query.
516      * @return string
517      */
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;
527     }
528     
529     /* array of successfully bound vars, and in case of success, the resulting vars
530      */
531     function _bound() {
532         return $this->_bound;
533     }
534
535     /** 
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.
538      `*
539      * @access public
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.
542      * @return boolean
543      */
544     function can_match(&$variables) {
545         if (empty($this->_query))
546             return false;
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.
551         if (!is_array($p)) {
552             if (!isset($variables[$p])) return false;
553         } else {
554             foreach ($p as $x) {
555                 if (!isset($variables[$x])) return false;
556             }
557         }
558         return true;
559     }
560
561     /**
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.
565      *
566      * @access public
567      * @param $variable number or array of name => value  The keys must satisfy all placeholders in the definition.
568      * @return boolean
569      */
570     function match(&$variable) {
571         $p =& $this->_placeholders;
572         $this->_workquery = $this->_query;
573         if (!is_array($p)) {
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);
578             } else {
579                 $this->_bind($variable, $p);
580             }
581         } else {
582             foreach ($p as $x) {
583                 if (!isset($variable[$x]))
584                     trigger_error("Required NumericSearchQuery->match variable $x not defined.", E_USER_ERROR);
585                 $this->_bind($variable[$x], $x);
586             }
587         }
588         if (!$this->_live_check()) // check returned an error
589             return false;
590         $search = $this->_workquery;
591         $result = false;
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();
600         }
601         return $result;
602     }
603 }
604
605
606 ////////////////////////////////////////////////////////////////
607 //
608 // Remaining classes are private.
609 //
610 ////////////////////////////////////////////////////////////////
611 /**
612  * Virtual base class for nodes in a TextSearchQuery parse tree.
613  *
614  * Also serves as a 'VOID' (contentless) node.
615  */
616 class TextSearchQuery_node
617 {
618     var $op = 'VOID';
619     var $_op = 0;
620
621     /**
622      * Optimize this node.
623      * @return object Optimized node.
624      */
625     function optimize() {
626         return $this;
627     }
628
629     /**
630      * @return regexp matching this node.
631      */
632     function regexp() {
633         return '';
634     }
635
636     /**
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.
639      */
640     function highlight_words($negated = false) {
641         return array();
642     }
643
644     function sql()    { return $this->word; }
645
646     function _sql_quote() {
647         global $request;
648         $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
649         return $request->_dbi->_backend->qstr($word);
650     }
651 }
652
653 /**
654  * A word. exact or substring?
655  */
656 class TextSearchQuery_node_word
657 extends TextSearchQuery_node
658 {
659     var $op = "WORD";
660     var $_op = TSQ_TOK_WORD;
661     
662     function TextSearchQuery_node_word($word) {
663         $this->word = $word;
664     }
665     function regexp() {
666         return '(?=.*\b' . preg_quote($this->word, '/') . '\b)';
667     }
668     function highlight_words ($negated = false) {
669         return $negated ? array() : array($this->word);
670     }
671     function sql()    { return '%'.$this->_sql_quote($this->word).'%'; }
672 }
673
674 class TextSearchQuery_node_all
675 extends TextSearchQuery_node {
676     var $op = "ALL";
677     var $_op = TSQ_TOK_ALL;
678     function regexp() { return '(?=.*)'; }
679     function sql()    { return '%'; }
680 }
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).'%'; }
687 }
688
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); }
695 }
696
697 class TextSearchQuery_node_exact
698 extends TextSearchQuery_node_word {
699     var $op = "EXACT";
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); }
703 }
704
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); }
711 }
712
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)'; }
718 }
719
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; }
725 }
726
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; }
733 }
734
735 /**
736  * A negated clause.
737  */
738 class TextSearchQuery_node_not
739 extends TextSearchQuery_node
740 {
741     var $op = "NOT";
742     var $_op = TSQ_TOK_NOT;
743     
744     function TextSearchQuery_node_not($leaf) {
745         $this->leaves = array($leaf);
746     }
747
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
753         return $this;
754     }
755     
756     function regexp() {
757         $leaf = &$this->leaves[0];
758         return '(?!' . $leaf->regexp() . ')';
759     }
760
761     function highlight_words ($negated = false) {
762         return $this->leaves[0]->highlight_words(!$negated);
763     }
764 }
765
766 /**
767  * Virtual base class for 'AND' and 'OR conjoins.
768  */
769 class TextSearchQuery_node_binop
770 extends TextSearchQuery_node
771 {
772     var $_op = TSQ_TOK_BINOP;
773     function TextSearchQuery_node_binop($leaves) {
774         $this->leaves = $leaves;
775     }
776
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))
780         $flat = array();
781         foreach ($this->leaves as $leaf) {
782             $leaf = $leaf->optimize();
783             if ($this->op == $leaf->op)
784                 $flat = array_merge($flat, $leaf->leaves);
785             else
786                 $flat[] = $leaf;
787         }
788         $this->leaves = $flat;
789     }
790
791     function optimize() {
792         $this->_flatten();
793         assert(!empty($this->leaves));
794         if (count($this->leaves) == 1)
795             return $this->leaves[0]; // (AND x) -> x
796         return $this;
797     }
798
799     function highlight_words($negated = false) {
800         $words = array();
801         foreach ($this->leaves as $leaf)
802             array_splice($words,0,0,
803                          $leaf->highlight_words($negated));
804         return $words;
805     }
806 }
807
808 /**
809  * A (possibly multi-argument) 'AND' conjoin.
810  */
811 class TextSearchQuery_node_and
812 extends TextSearchQuery_node_binop
813 {
814     var $op = "AND";
815     
816     function optimize() {
817         $this->_flatten();
818
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))
822
823         // Suck out the negated leaves.
824         $nots = array();
825         foreach ($this->leaves as $key => $leaf) {
826             if ($leaf->_op == TSQ_TOK_NOT) {
827                 $nots[] = $leaf->leaves[0];
828                 unset($this->leaves[$key]);
829             }
830         }
831
832         // Combine the negated leaves into a single negated or.
833         if ($nots) {
834             $node = ( new TextSearchQuery_node_not
835                       (new TextSearchQuery_node_or($nots)) );
836             array_unshift($this->leaves, $node->optimize());
837         }
838         
839         assert(!empty($this->leaves));
840         if (count($this->leaves) == 1)
841             return $this->leaves[0];  // (AND x) -> x
842         return $this;
843     }
844
845     /* FIXME!
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))/
849      */
850     function regexp() {
851         $regexp = '';
852         foreach ($this->leaves as $leaf)
853             $regexp .= $leaf->regexp();
854         return $regexp;
855     }
856 }
857
858 /**
859  * A (possibly multi-argument) 'OR' conjoin.
860  */
861 class TextSearchQuery_node_or
862 extends TextSearchQuery_node_binop
863 {
864     var $op = "OR";
865
866     function regexp() {
867         // We will combine any of our direct descendents which are WORDs
868         // into a single (?=.*(?:word1|word2|...)) regexp.
869         
870         $regexps = array();
871         $words = array();
872
873         foreach ($this->leaves as $leaf) {
874             if ($leaf->op == TSQ_TOK_WORD)
875                 $words[] = preg_quote($leaf->word, '/');
876             else
877                 $regexps[] = $leaf->regexp();
878         }
879
880         if ($words)
881             array_unshift($regexps,
882                           '(?=.*' . $this->_join($words) . ')');
883
884         return $this->_join($regexps);
885     }
886
887     function _join($regexps) {
888         assert(count($regexps) > 0);
889
890         if (count($regexps) > 1)
891             return '(?:' . join('|', $regexps) . ')';
892         else
893             return $regexps[0];
894     }
895 }
896
897
898 ////////////////////////////////////////////////////////////////
899 //
900 // Parser:
901 //   op's (and, or, not) are forced to lowercase in the tokenizer.
902 //
903 ////////////////////////////////////////////////////////////////
904 class TextSearchQuery_Parser 
905 {
906     /*
907      * This is a simple recursive descent parser, based on the following grammar:
908      *
909      * toplist  :
910      *          | toplist expr
911      *          ;
912      *
913      *
914      * list     : expr
915      *          | list expr
916      *          ;
917      *
918      * expr     : atom
919      *          | expr BINOP atom
920      *          ;
921      *
922      * atom     : '(' list ')'
923      *          | NOT atom
924      *          | WORD
925      *          ;
926      *
927      * The terminal tokens are:
928      *
929      *
930      * and|or             BINOP
931      * -|not              NOT
932      * (                  LPAREN
933      * )                  RPAREN
934      * /[^-()\s][^()\s]*  WORD
935      * /"[^"]*"/          WORD
936      * /'[^']*'/          WORD
937      *
938      * ^WORD              STARTS_WITH
939      * WORD*              STARTS_WITH
940      * *WORD              ENDS_WITH
941      * ^WORD$             EXACT
942      * *                  ALL
943      */
944
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());
950         unset($this->lexer);
951         return $tree;
952     }
953     
954     function get_list ($is_toplevel = false) {
955         $list = array();
956
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;
960         if ($is_toplevel)
961             $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
962         
963         while ( ($expr = $this->get_expr())
964                 || ($expr = $this->get_word($accept_as_words)) )
965         {
966             $list[] = $expr;
967         }
968
969         if (!$list) {
970             if ($is_toplevel)
971                 return new TextSearchQuery_node;
972             else
973                 return false;
974         }
975         return new TextSearchQuery_node_and($list);
976     }
977
978     function get_expr () {
979         if ( ($expr = $this->get_atom()) === false ) // protect against '0'
980             return false;
981         
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()) ) {
986                 break;
987             }
988             
989             if ($op == 'and')
990                 $expr = new TextSearchQuery_node_and(array($expr, $right));
991             else {
992                 assert($op == 'or');
993                 $expr = new TextSearchQuery_node_or(array($expr, $right));
994             }
995
996             $savedpos = $this->lexer->tell();
997         }
998         $this->lexer->seek($savedpos);
999
1000         return $expr;
1001     }
1002     
1003
1004     function get_atom() {
1005         if ($atom = $this->get_word(TSQ_ALLWORDS)) // Bug#1791564 not involved: '*'
1006             return $atom;
1007
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) ) {
1011                 return $list;
1012             } else {
1013                 // Fix Bug#1792170
1014                 // Handle " ( " or "(test" without closing ")" as plain word
1015                 $this->lexer->seek($savedpos);
1016                 return new TextSearchQuery_node_word($this->lexer->get(-1));
1017             }
1018         }
1019         elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
1020             if ( ($atom = $this->get_atom()) )
1021                 return new TextSearchQuery_node_not($atom);
1022         }
1023         $this->lexer->seek($savedpos);
1024         return false;
1025     }
1026
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)
1032                 return false;
1033         }
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))
1040             {
1041                 $classname = "TextSearchQuery_node_".strtolower($tok);
1042                 return new $classname($word);
1043             }
1044         }
1045         return false;
1046     }
1047 }
1048
1049 class TextSearchQuery_Lexer {
1050     function TextSearchQuery_Lexer ($query_str, $case_exact=false, 
1051                                     $regex=TSQ_REGEX_AUTO) 
1052     {
1053         $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
1054         $this->pos = 0;
1055     }
1056
1057     function tell() {
1058         return $this->pos;
1059     }
1060
1061     function seek($pos) {
1062         $this->pos = $pos;
1063     }
1064
1065     function eof() {
1066         return $this->pos == count($this->tokens);
1067     }
1068     
1069     /**
1070      * TODO: support more regex styles, esp. prefer the forced ones over auto
1071      * re: and // stuff
1072      */
1073     function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
1074         $tokens = array();
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;
1080             }
1081             elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
1082                 $val = strtolower($m[1]);
1083                 $type = TSQ_TOK_NOT;
1084             }
1085             elseif (preg_match('/^([()])\s*/', $buf, $m)) {
1086                 $val = $m[1];
1087                 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
1088             }
1089             
1090             // * => ALL
1091             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1092                     and preg_match('/^\*\s*/', $buf, $m)) {
1093                 $val = "*";
1094                 $type = TSQ_TOK_ALL;
1095             }
1096             // .* => ALL
1097             elseif ($regex & (TSQ_REGEX_PCRE)
1098                     and preg_match('/^\.\*\s*/', $buf, $m)) {
1099                 $val = ".*";
1100                 $type = TSQ_TOK_ALL;
1101             }
1102             // % => ALL
1103             elseif ($regex & (TSQ_REGEX_SQL)
1104                     and preg_match('/^%\s*/', $buf, $m)) {
1105                 $val = "%";
1106                 $type = TSQ_TOK_ALL;
1107             }
1108             
1109             // ^word
1110             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1111                     and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
1112                 $val = $m[1];
1113                 $type = TSQ_TOK_STARTS_WITH;
1114             }
1115             // word*
1116             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1117                     and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
1118                 $val = $m[1];
1119                 $type = TSQ_TOK_STARTS_WITH;
1120             }
1121             // *word
1122             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_GLOB)
1123                     and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
1124                 $val = $m[1];
1125                 $type = TSQ_TOK_ENDS_WITH;
1126             }
1127             // word$
1128             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1129                     and preg_match('/^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
1130                 $val = $m[1];
1131                 $type = TSQ_TOK_ENDS_WITH;
1132             }
1133             // ^word$
1134             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
1135                     and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
1136                 $val = $m[1];
1137                 $type = TSQ_TOK_EXACT;
1138             }
1139             
1140             // "words "
1141             elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
1142                 $val = str_replace('""', '"', $m[1]);
1143                 $type = TSQ_TOK_WORD;
1144             }
1145             // 'words '
1146             elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
1147                 $val = str_replace("''", "'", $m[1]);
1148                 $type = TSQ_TOK_WORD;
1149             }
1150             // word
1151             elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
1152                 $val = $m[1];
1153                 $type = TSQ_TOK_WORD;
1154             }
1155             else {
1156                 assert(empty($buf));
1157                 break;
1158             }
1159             $buf = substr($buf, strlen($m[0]));
1160
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;
1169             }
1170             */
1171             $tokens[] = array($type, $val);
1172         }
1173         return $tokens;
1174     }
1175     
1176     function get($accept) {
1177         if ($this->pos >= count($this->tokens))
1178             return false;
1179         
1180         list ($type, $val) = $this->tokens[$this->pos];
1181         if (($type & $accept) == 0)
1182             return false;
1183         
1184         $this->pos++;
1185         return $val;
1186     }
1187 }
1188
1189 // Local Variables:
1190 // mode: php
1191 // tab-width: 8
1192 // c-basic-offset: 4
1193 // c-hanging-comment-ender-p: nil
1194 // indent-tabs-mode: nil
1195 // End:   
1196 ?>