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