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