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