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