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