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