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