From 865c268791a99fa57aa818528c6f2473b26d954f Mon Sep 17 00:00:00 2001 From: Kazutaka Miyasaka Date: Sun, 20 Sep 2009 14:11:16 +0200 Subject: enhanced full-text search function Ignore-this: cb05f50ca4de12e1cdf3a6cfb0e1b8bc - better search experience in Asian language - sophisticated search query syntax (OR, grouping, etc.) darcs-hash:20090920121116-9b77a-2718be7a043374669037b10d94101fc70efb95e3.gz --- inc/fulltext.php | 465 ++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 339 insertions(+), 126 deletions(-) (limited to 'inc/fulltext.php') diff --git a/inc/fulltext.php b/inc/fulltext.php index a1b8a1541..636eb3f76 100644 --- a/inc/fulltext.php +++ b/inc/fulltext.php @@ -25,105 +25,89 @@ function ft_pageSearch($query,&$highlight){ return trigger_event('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch'); } -function _ft_pageSearch(&$data){ - // split out original parameters - $query = $data['query']; - $highlight =& $data['highlight']; - $q = ft_queryParser($query); - - $highlight = array(); +/** + * Returns a list of matching documents for the given query + * + * @author Andreas Gohr + * @author Kazutaka Miyasaka + */ +function _ft_pageSearch(&$data) { + // parse the given query + $q = ft_queryParser($data['query']); + $data['highlight'] = $q['highlight']; - // remember for hilighting later - foreach($q['words'] as $wrd){ - $highlight[] = str_replace('*','',$wrd); - } + if (empty($q['parsed_ary'])) return array(); // lookup all words found in the query - $words = array_merge($q['and'],$q['not']); - if(!count($words)) return array(); - $result = idx_lookup($words); - if(!count($result)) return array(); - - // merge search results with query - foreach($q['and'] as $pos => $w){ - $q['and'][$pos] = $result[$w]; - } - // create a list of unwanted docs - $not = array(); - foreach($q['not'] as $pos => $w){ - $not = array_merge($not,array_keys($result[$w])); - } + $lookup = idx_lookup($q['words']); - // combine and-words - if(count($q['and']) > 1){ - $docs = ft_resultCombine($q['and']); - }else{ - $docs = $q['and'][0]; - } - if(!count($docs)) return array(); - - // create a list of hidden pages in the result - $hidden = array(); - $hidden = array_filter(array_keys($docs),'isHiddenPage'); - $not = array_merge($not,$hidden); - - // filter unmatched namespaces - if(!empty($q['ns'])) { - $pattern = implode('|^',$q['ns']); - foreach($docs as $key => $val) { - if(!preg_match('/^'.$pattern.'/',$key)) { - unset($docs[$key]); - } - } + // get all pages in this dokuwiki site (!: includes nonexistent pages) + $pages_all = array(); + foreach (idx_getIndex('page', '') as $id) { + $pages_all[trim($id)] = 0; // base: 0 hit } - // filter unwanted namespaces - if(!empty($q['notns'])) { - $pattern = implode('|^',$q['notns']); - foreach($docs as $key => $val) { - if(preg_match('/^'.$pattern.'/',$key)) { - unset($docs[$key]); - } - } - } - - // remove negative matches - foreach($not as $n){ - unset($docs[$n]); - } - - if(!count($docs)) return array(); - // handle phrases - if(count($q['phrases'])){ - $q['phrases'] = array_map('utf8_strtolower',$q['phrases']); - // use this for higlighting later: - $highlight = array_merge($highlight,$q['phrases']); - $q['phrases'] = array_map('preg_quote_cb',$q['phrases']); - // check the source of all documents for the exact phrases - foreach(array_keys($docs) as $id){ - $text = utf8_strtolower(rawWiki($id)); - foreach($q['phrases'] as $phrase){ - if(!preg_match('/'.$phrase.'/usi',$text)){ - unset($docs[$id]); // no hit - remove - break; + // process the query + $stack = array(); + foreach ($q['parsed_ary'] as $token) { + switch (substr($token, 0, 3)) { + case 'W+:': + case 'W-:': // word + $word = substr($token, 3); + $stack[] = (array) $lookup[$word]; + break; + case 'P_:': // phrase + $phrase = substr($token, 3); + // since phrases are always parsed as ((W1)(W2)...(P)), + // the end($stack) always points the pages that contain + // all words in this phrase + $pages = end($stack); + $pages_matched = array(); + foreach(array_keys($pages) as $id){ + $text = utf8_strtolower(rawWiki($id)); + if (strpos($text, $phrase) !== false) { + $pages_matched[$id] = 0; // phrase: always 0 hit + } } - } + $stack[] = $pages_matched; + break; + case 'N_:': // namespace + $ns = substr($token, 3); + $pages_matched = array(); + foreach (array_keys($pages_all) as $id) { + if (strpos($id, $ns) === 0) { + $pages_matched[$id] = 0; // namespace: always 0 hit + } + } + $stack[] = $pages_matched; + break; + case 'AND': // and operation + list($pages1, $pages2) = array_splice($stack, -2); + $stack[] = ft_resultCombine(array($pages1, $pages2)); + break; + case 'OR': // or operation + list($pages1, $pages2) = array_splice($stack, -2); + $stack[] = ft_resultUnite(array($pages1, $pages2)); + break; + case 'NOT': // not operation (unary) + $pages = array_pop($stack); + $stack[] = ft_resultComplement(array($pages_all, $pages)); + break; } } + $docs = array_pop($stack); - if(!count($docs)) return array(); + if (empty($docs)) return array(); - // check ACL permissions - foreach(array_keys($docs) as $doc){ - if(auth_quickaclcheck($doc) < AUTH_READ){ - unset($docs[$doc]); + // check: settings, acls, existence + foreach (array_keys($docs) as $id) { + if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) { + unset($docs[$id]); } } - if(!count($docs)) return array(); - - // if there are any hits left, sort them by count + // sort docs by count arsort($docs); return $docs; @@ -404,61 +388,290 @@ function ft_resultCombine($args){ } /** - * Builds an array of search words from a query + * Unites found documents and sum up their scores + * + * based upon ft_resultCombine() function * - * @todo support OR and parenthesises? + * @param array $args An array of page arrays + * @author Kazutaka Miyasaka */ -function ft_queryParser($query){ - global $conf; - $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; - if(@file_exists($swfile)){ - $stopwords = file($swfile); - }else{ - $stopwords = array(); +function ft_resultUnite($args) { + $array_count = count($args); + if ($array_count === 1) { + return $args[0]; } - $q = array(); - $q['query'] = $query; - $q['ns'] = array(); - $q['notns'] = array(); - $q['phrases'] = array(); - $q['words'] = array(); - $q['and'] = array(); - $q['not'] = array(); - - // handle phrase searches - while(preg_match('/"(.*?)"/',$query,$match)){ - $q['phrases'][] = $match[1]; - $q['and'] = array_merge($q['and'], idx_tokenizer($match[0],$stopwords)); - $query = preg_replace('/"(.*?)"/','',$query,1); + $result = $args[0]; + for ($i = 1; $i !== $array_count; $i++) { + foreach (array_keys($args[$i]) as $id) { + $result[$id] += $args[$i][$id]; + } + } + return $result; +} + +/** + * Computes the difference of documents using page id for comparison + * + * nearly identical to PHP5's array_diff_key() + * + * @param array $args An array of page arrays + * @author Kazutaka Miyasaka + */ +function ft_resultComplement($args) { + $array_count = count($args); + if ($array_count === 1) { + return $args[0]; } - $words = explode(' ',$query); - foreach($words as $w){ - if($w{0} == '-'){ - $token = idx_tokenizer($w,$stopwords,true); - if(count($token)) $q['not'] = array_merge($q['not'],$token); - } else if ($w{0} == '@') { // Namespace to search? - $w = substr($w,1); - $q['ns'] = array_merge($q['ns'],(array)$w); - } else if ($w{0} == '^') { // Namespace not to search? - $w = substr($w,1); - $q['notns'] = array_merge($q['notns'],(array)$w); - }else{ - // asian "words" need to be searched as phrases - if(@preg_match_all('/(('.IDX_ASIAN.')+)/u',$w,$matches)){ - $q['phrases'] = array_merge($q['phrases'],$matches[1]); + $result = $args[0]; + foreach (array_keys($result) as $id) { + for ($i = 1; $i !== $array_count; $i++) { + if (isset($args[$i][$id])) unset($result[$id]); + } + } + return $result; +} +/** + * Parses a search query and builds an array of search formulas + * + * @author Andreas Gohr + * @author Kazutaka Miyasaka + */ +function ft_queryParser($query){ + global $conf; + $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; + $stopwords = @file_exists($swfile) ? file($swfile) : array(); + + /** + * parse a search query and transform it into intermediate representation + * + * in a search query, you can use the following expressions: + * + * words: + * include + * -exclude + * phrases: + * "phrase to be included" + * -"phrase you want to exclude" + * namespaces: + * @include:namespace (or ns:include:namespace) + * ^exclude:namespace (or -ns:exclude:namespace) + * groups: + * () + * -() + * operators: + * and ('and' is the default operator: you can always omit this) + * or (lower precedence than 'and') + * + * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain + * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'". + * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ] + * as long as you don't mind hit counts. + * + * intermediate representation consists of the following parts: + * + * ( ) - group + * AND - logical and + * OR - logical or + * NOT - logical not + * W+: - word (needs to be highlighted) + * W-: - word (no need to highlight) + * P_: - phrase + * N_: - namespace + */ + $parsed_query = ''; + $parens_level = 0; + $terms = preg_split('/(-?".*?")/u', utf8_strtolower($query), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + + foreach ($terms as $term) { + $parsed = ''; + if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) { + // phrase-include and phrase-exclude + $not = $matches[1] ? 'NOT' : ''; + $parsed = $not.ft_termParser($matches[2], $stopwords, false, true); + } else { + // fix incomplete phrase + $term = str_replace('"', ' ', $term); + + // fix parentheses + $term = str_replace(')' , ' ) ', $term); + $term = str_replace('(' , ' ( ', $term); + $term = str_replace('- (', ' -(', $term); + + // treat ideographic spaces (U+3000) as search term separators + // FIXME: some more separators? + $term = preg_replace('/[ \x{3000}]+/u', ' ', $term); + $term = trim($term); + if ($term === '') continue; + + $tokens = explode(' ', $term); + foreach ($tokens as $token) { + if ($token === '(') { + // parenthesis-include-open + $parsed .= '('; + ++$parens_level; + } elseif ($token === '-(') { + // parenthesis-exclude-open + $parsed .= 'NOT('; + ++$parens_level; + } elseif ($token === ')') { + // parenthesis-any-close + if ($parens_level === 0) continue; + $parsed .= ')'; + $parens_level--; + } elseif ($token === 'and') { + // logical-and (do nothing) + } elseif ($token === 'or') { + // logical-or + $parsed .= 'OR'; + } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) { + // namespace-exclude + $parsed .= 'NOT(N_:'.$matches[1].')'; + } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) { + // namespace-include + $parsed .= '(N_:'.$matches[1].')'; + } elseif (preg_match('/^-(.+)$/', $token, $matches)) { + // word-exclude + $parsed .= 'NOT('.ft_termParser($matches[1], $stopwords).')'; + } else { + // word-include + $parsed .= ft_termParser($token, $stopwords); + } } - $token = idx_tokenizer($w,$stopwords,true); - if(count($token)){ - $q['and'] = array_merge($q['and'],$token); - $q['words'] = array_merge($q['words'],$token); + } + $parsed_query .= $parsed; + } + + // cleanup (very sensitive) + $parsed_query .= str_repeat(')', $parens_level); + do { + $parsed_query_old = $parsed_query; + $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query); + } while ($parsed_query !== $parsed_query_old); + $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query); + $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query); + $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query); + $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query); + $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query); + + /** + * convert infix notation string into postfix (Reverse Polish notation) array + * by Shunting-yard algorithm + * + * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation + * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm + */ + $parsed_ary = array(); + $ope_stack = array(); + $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5); + $ope_regex = '/([()]|OR|AND|NOT)/u'; + + $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + foreach ($tokens as $token) { + if (preg_match($ope_regex, $token)) { + // operator + $last_ope = end($ope_stack); + while ($ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') { + $parsed_ary[] = array_pop($ope_stack); + $last_ope = end($ope_stack); + } + if ($token == ')') { + array_pop($ope_stack); // this array_pop always deletes '(' + } else { + $ope_stack[] = $token; } + } else { + // operand + $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token); + $parsed_ary[] = $token_decoded; } } + $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack))); + + // cleanup: each double "NOT" in RPN array actually does nothing + $parsed_ary_count = count($parsed_ary); + for ($i = 1; $i < $parsed_ary_count; ++$i) { + if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') { + unset($parsed_ary[$i], $parsed_ary[$i - 1]); + } + } + $parsed_ary = array_values($parsed_ary); + + // build return value + $q = array(); + $q['query'] = $query; + $q['parsed_str'] = $parsed_query; + $q['parsed_ary'] = $parsed_ary; + + foreach ($q['parsed_ary'] as $token) { + if ($token[2] !== ':') continue; + $body = substr($token, 3); + + switch (substr($token, 0, 3)) { + case 'N_:': + $q['ns'][] = $body; // for backward compatibility + break; + case 'W-:': + $q['words'][] = $body; + break; + case 'W+:': + $q['words'][] = $body; + $q['highlight'][] = str_replace('*', '', $body); + break; + case 'P_:': + $q['phrases'][] = $body; + $q['highlight'][] = str_replace('*', '', $body); + break; + } + } + foreach (array('words', 'phrases', 'highlight', 'ns') as $key) { + $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key])); + } + + // keep backward compatibility (to some extent) + // this part can be deleted if no plugins use ft_queryParser() directly + $q['and'] = $q['words']; + $q['not'] = array(); // difficult to set: imagine [ aaa -(bbb -ccc) ] + $q['notns'] = array(); // same as above return $q; } +/** + * Transforms given search term into intermediate representation + * + * This function is used in ft_queryParser() and not for general purpose use. + * + * @author Kazutaka Miyasaka + */ +function ft_termParser($term, &$stopwords, $consider_asian = true, $phrase_mode = false) { + $parsed = ''; + if ($consider_asian) { + // successive asian characters need to be searched as a phrase + $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); + foreach ($words as $word) { + if (preg_match('/'.IDX_ASIAN.'/u', $word)) $phrase_mode = true; + $parsed .= ft_termParser($word, $stopwords, false, $phrase_mode); + } + } else { + $term_noparen = str_replace(array('(', ')'), ' ', $term); + $words = idx_tokenizer($term_noparen, $stopwords, true); + + // W+: needs to be highlighted, W-: no need to highlight + if (empty($words)) { + $parsed = '()'; // important: do not remove + } elseif ($words[0] === $term) { + $parsed = '(W+:'.$words[0].')'; + } elseif ($phrase_mode) { + $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term); + $parsed = '((W-:'.implode(')(W-:', $words).')(P_:'.$term_encoded.'))'; + } else { + $parsed = '((W+:'.implode(')(W+:', $words).'))'; + } + } + return $parsed; +} + //Setup VIM: ex: et ts=4 enc=utf-8 : -- cgit v1.2.3