5 * This represents "Google-like" text search queries like:
8 * <dd> Match strings containing the substring 'wiki', and not containing the
10 * <dt> wiki word or page
11 * <dd> Match strings containing the substring 'wiki' and either the substring
12 * 'word' or the substring 'page'.
15 * The full query syntax, in order of precedence, is roughly:
17 * The unary 'NOT' or '-' operator (they are equivalent) negates the
18 * following search clause.
20 * Search clauses may be joined with the (left-associative) binary operators
23 * Two adjoining search clauses are joined with an implicit 'AND'. This has
24 * lower precedence than either an explicit 'AND' or 'OR', so "a b OR c"
25 * parses as "a AND ( b OR c )", while "a AND b OR c" parses as
26 * "( a AND b ) OR c" (due to the left-associativity of 'AND' and 'OR'.)
28 * Search clauses can be grouped with parentheses.
30 * Phrases (or other things which don't look like words) can be forced to
31 * be interpreted as words by quoting them, either with single (') or double (")
32 * quotes. If you wan't to include the quote character within a quoted string,
33 * double-up on the quote character: 'I''m hungry' is equivalent to
36 class TextSearchQuery {
40 * @param $search_query string The query. Syntax is as described above.
41 * Note that an empty $search_query will match anything.
42 * @see TextSearchQuery
44 function TextSearchQuery($search_query) {
45 $parser = new TextSearchQuery_Parser;
46 $this->_tree = $parser->parse($search_query);
50 function _optimize() {
51 $this->_tree = $this->_tree->optimize();
55 * Get a regexp which matches the query.
58 if (!isset($this->_regexp))
59 $this->_regexp = '/^' . $this->_tree->regexp() . '/isS';
60 return $this->_regexp;
64 * Match query against string.
66 * @param $string string The string to match.
67 * @return boolean True if the string matches the query.
69 function match($string) {
70 return preg_match($this->asRegexp(), $string);
75 * Get a regular expression suitable for highlighting matched words.
77 * This returns a PCRE regular expression which matches any non-negated
80 * @return string The PCRE regexp.
82 function getHighlightRegexp() {
83 if (!isset($this->_hilight_regexp)) {
84 $words = array_unique($this->_tree->highlight_words());
86 $this->_hilight_regexp = false;
89 foreach ($words as $key => $word)
90 $words[$key] = preg_quote($word, '/');
91 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
94 return $this->_hilight_regexp;
98 * Make an SQL clause which matches the query.
100 * @param $make_sql_clause_cb WikiCallback
101 * A callback which takes a single word as an argument and
102 * returns an SQL clause which will match exactly those records
103 * containing the word. The word passed to the callback will always
104 * be in all lower case.
108 * function sql_title_match($word) {
109 * return sprintf("LOWER(title) like '%s'",
110 * addslashes($word));
115 * $query = new TextSearchQuery("wiki -page");
116 * $cb = new WikiFunctionCb('sql_title_match');
117 * $sql_clause = $query->makeSqlClause($cb);
119 * This will result in $sql_clause containing something like
120 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
122 * @return string The PCRE regexp.
124 function makeSqlClause($make_sql_clause_cb) {
125 $this->_sql_clause_cb = $make_sql_clause_cb;
126 return $this->_sql_clause($this->_tree);
129 function _sql_clause($node) {
132 return $this->_sql_clause_cb->call($node->word);
134 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
137 $subclauses = array();
138 foreach ($node->leaves as $leaf)
139 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
140 return join(" $node->op ", $subclauses);
142 assert($node->op == 'VOID');
148 * Get printable representation of the parse tree.
150 * This is for debugging only.
151 * @return string Printable parse tree.
153 function asString() {
154 return $this->_as_string($this->_tree);
157 function _as_string($node, $indent = '') {
160 return $indent . "WORD: $node->word";
162 return $indent . "VOID";
164 $lines = array($indent . $node->op . ":");
166 foreach ($node->leaves as $leaf)
167 $lines[] = $this->_as_string($leaf, $indent);
168 return join("\n", $lines);
174 ////////////////////////////////////////////////////////////////
176 // Remaining classes are private.
178 ////////////////////////////////////////////////////////////////
180 * Virtual base class for nodes in a TextSearchQuery parse tree.
182 * Also servers as a 'VOID' (contentless) node.
184 class TextSearchQuery_node
189 * Optimize this node.
190 * @return object Optimized node.
192 function optimize() {
197 * @return regexp matching this node.
204 * @param bool True if this node has been negated (higher in the parse tree.)
205 * @return array A list of all non-negated words contained by this node.
207 function highlight_words($negated = false) {
215 class TextSearchQuery_node_word
216 extends TextSearchQuery_node
220 function TextSearchQuery_node_word($word) {
225 return '(?=.*' . preg_quote($this->word, '/') . ')';
228 function highlight_words($negated = false) {
229 return $negated ? array() : array($this->word);
237 class TextSearchQuery_node_not
238 extends TextSearchQuery_node
242 function TextSearchQuery_node_not($leaf) {
243 $this->leaves = array($leaf);
246 function optimize() {
247 $leaf = &$this->leaves[0];
248 $leaf = $leaf->optimize();
249 if ($leaf->op == 'NOT')
250 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
255 $leaf = &$this->leaves[0];
256 return '(?!' . $leaf->regexp() . ')';
259 function highlight_words($negated = false) {
260 return $this->leaves[0]->highlight_words(!$negated);
265 * Virtual base class for 'AND' and 'OR conjoins.
267 class TextSearchQuery_node_binop
268 extends TextSearchQuery_node
270 function TextSearchQuery_node_binop($leaves) {
271 $this->leaves = $leaves;
274 function _flatten() {
275 // This flattens e.g. (AND (AND a b) (OR c d) e)
276 // to (AND a b e (OR c d))
278 foreach ($this->leaves as $leaf) {
279 $leaf = $leaf->optimize();
280 if ($this->op == $leaf->op)
281 $flat = array_merge($flat, $leaf->leaves);
285 $this->leaves = $flat;
288 function optimize() {
290 assert(!empty($this->leaves));
291 if (count($this->leaves) == 1)
292 return $this->leaves[0]; // (AND x) -> x
296 function highlight_words($negated = false) {
298 foreach ($this->leaves as $leaf)
299 array_splice($words,0,0,
300 $leaf->highlight_words($negated));
306 * A (possibly multi-argument) 'AND' conjoin.
308 class TextSearchQuery_node_and
309 extends TextSearchQuery_node_binop
313 function optimize() {
316 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
317 // Since OR's are more efficient for regexp matching:
318 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
320 // Suck out the negated leaves.
322 foreach ($this->leaves as $key => $leaf) {
323 if ($leaf->op == 'NOT') {
324 $nots[] = $leaf->leaves[0];
325 unset($this->leaves[$key]);
329 // Combine the negated leaves into a single negated or.
331 $node = ( new TextSearchQuery_node_not
332 (new TextSearchQuery_node_or($nots)) );
333 array_unshift($this->leaves, $node->optimize());
336 assert(!empty($this->leaves));
337 if (count($this->leaves) == 1)
338 return $this->leaves[0]; // (AND x) -> x
344 foreach ($this->leaves as $leaf)
345 $regexp .= $leaf->regexp();
351 * A (possibly multi-argument) 'OR' conjoin.
353 class TextSearchQuery_node_or
354 extends TextSearchQuery_node_binop
359 // We will combine any of our direct descendents which are WORDs
360 // into a single (?=.*(?:word1|word2|...)) regexp.
365 foreach ($this->leaves as $leaf) {
366 if ($leaf->op == 'WORD')
367 $words[] = preg_quote($leaf->word, '/');
369 $regexps[] = $leaf->regexp();
373 array_unshift($regexps,
374 '(?=.*' . $this->_join($words) . ')');
376 return $this->_join($regexps);
379 function _join($regexps) {
380 assert(count($regexps) > 0);
382 if (count($regexps) > 1)
383 return '(?:' . join('|', $regexps) . ')';
390 ////////////////////////////////////////////////////////////////
394 ////////////////////////////////////////////////////////////////
395 define ('TSQ_TOK_WORD', 1);
396 define ('TSQ_TOK_BINOP', 2);
397 define ('TSQ_TOK_NOT', 4);
398 define ('TSQ_TOK_LPAREN', 8);
399 define ('TSQ_TOK_RPAREN', 16);
401 class TextSearchQuery_Parser
404 * This is a simple recursive descent parser, based on the following grammar:
419 * atom : '(' list ')'
424 * The terminal tokens are:
431 * [^-()\s][^()\s]* WORD
436 function parse ($search_expr) {
437 $this->lexer = new TextSearchQuery_Lexer($search_expr);
438 $tree = $this->get_list('toplevel');
439 assert($this->lexer->eof());
444 function get_list ($is_toplevel = false) {
447 // token types we'll accept as words (and thus expr's) for the
448 // purpose of error recovery:
449 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
451 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
453 while ( ($expr = $this->get_expr())
454 || ($expr = $this->get_word($accept_as_words)) ) {
461 return new TextSearchQuery_node;
465 return new TextSearchQuery_node_and($list);
468 function get_expr () {
469 if ( !($expr = $this->get_atom()) )
472 $savedpos = $this->lexer->tell();
473 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
474 if ( ! ($right = $this->get_atom()) ) {
479 $expr = new TextSearchQuery_node_and(array($expr, $right));
482 $expr = new TextSearchQuery_node_or(array($expr, $right));
485 $savedpos = $this->lexer->tell();
487 $this->lexer->seek($savedpos);
493 function get_atom() {
494 if ($word = $this->get_word())
497 $savedpos = $this->lexer->tell();
498 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
499 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
502 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
503 if ( ($atom = $this->get_atom()) )
504 return new TextSearchQuery_node_not($atom);
506 $this->lexer->seek($savedpos);
510 function get_word($accept = TSQ_TOK_WORD) {
511 if ( ($word = $this->lexer->get($accept)) )
512 return new TextSearchQuery_node_word($word);
517 class TextSearchQuery_Lexer {
518 function TextSearchQuery_Lexer ($query_str) {
519 $this->tokens = $this->tokenize($query_str);
527 function seek($pos) {
532 return $this->pos == count($this->tokens);
535 function tokenize($string) {
537 $buf = strtolower(ltrim($string));
538 while (!empty($buf)) {
539 if (preg_match('/^(and|or)\s*/', $buf, $m)) {
541 $type = TSQ_TOK_BINOP;
543 elseif (preg_match('/^(-|not)\s*/', $buf, $m)) {
547 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
549 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
551 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
552 $val = str_replace('""', '"', $m[1]);
553 $type = TSQ_TOK_WORD;
555 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
556 $val = str_replace("''", "'", $m[1]);
557 $type = TSQ_TOK_WORD;
559 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
561 $type = TSQ_TOK_WORD;
567 $buf = substr($buf, strlen($m[0]));
568 $tokens[] = array($type, $val);
573 function get($accept) {
574 if ($this->pos >= count($this->tokens))
577 list ($type, $val) = $this->tokens[$this->pos];
578 if (($type & $accept) == 0)
590 // c-hanging-comment-ender-p: nil
591 // indent-tabs-mode: nil