1<?php 2 3namespace dokuwiki\Search; 4 5use dokuwiki\Extension\Event; 6use dokuwiki\Search\Collection\CollectionSearch; 7use dokuwiki\Search\Collection\PageFulltextCollection; 8use dokuwiki\Search\Exception\SearchException; 9use dokuwiki\Search\Query\QueryEvaluator; 10use dokuwiki\Search\Query\QueryParser; 11use dokuwiki\Utf8; 12 13/** 14 * DokuWiki Fulltext Search 15 * 16 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 17 * @author Andreas Gohr <andi@splitbrain.org> 18 */ 19class FulltextSearch 20{ 21 /** @var int Maximum number of results to generate snippets for */ 22 protected int $maxSnippets = 15; 23 24 /** 25 * @return int 26 */ 27 public function getMaxSnippets(): int 28 { 29 return $this->maxSnippets; 30 } 31 32 /** 33 * @param int $maxSnippets 34 */ 35 public function setMaxSnippets(int $maxSnippets): void 36 { 37 $this->maxSnippets = $maxSnippets; 38 } 39 40 /** 41 * The fulltext search 42 * 43 * Returns a list of matching documents for the given query 44 * 45 * @triggers SEARCH_QUERY_FULLPAGE 46 * 47 * @param string $query the search query string 48 * @param array $highlight will be filled with terms to highlight 49 * @param string $sort sort mode: 'hits' (default) or 'mtime' 50 * @param int|string $after only show results with mtime after this date, 51 * accepts timestamp or strtotime arguments 52 * @param int|string $before only show results with mtime before this date, 53 * accepts timestamp or strtotime arguments 54 * 55 * @return array matching documents as pageid => score 56 */ 57 public function pageSearch($query, &$highlight, $sort = null, $after = null, $before = null) 58 { 59 if ($sort === null) { 60 $sort = 'hits'; 61 } 62 $data = [ 63 'query' => $query, 64 'sort' => $sort, 65 'after' => $after, 66 'before' => $before 67 ]; 68 $data['highlight'] =& $highlight; 69 $action = [$this, 'pageSearchCallBack']; 70 return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, $action); 71 } 72 73 /** 74 * Returns a list of matching documents for the given query 75 * 76 * @author Andreas Gohr <andi@splitbrain.org> 77 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 78 * 79 * @param array $data event data 80 * @return array matching documents as pageid => score 81 */ 82 public function pageSearchCallBack(&$data) 83 { 84 // parse the given query 85 $q = (new QueryParser)->convert($data['query']); 86 $data['highlight'] = $q['highlight']; 87 88 if (empty($q['parsed_ary'])) return []; 89 90 // look up all words via CollectionSearch 91 $collection = new PageFulltextCollection(); 92 $search = new CollectionSearch($collection); 93 foreach ($q['words'] as $word) { 94 try { 95 $search->addTerm($word); 96 } catch (SearchException $e) { 97 // term too short or invalid, skip 98 } 99 } 100 $terms = $search->execute(); 101 102 // evaluate the query 103 $evaluator = new QueryEvaluator($q['parsed_ary'], $terms); 104 $docs = $evaluator->evaluate(); 105 106 if (empty($docs)) return []; 107 108 // filter by visibility, acls, existence, and time range 109 $docs = MetadataSearch::filterPages($docs, false, $data['after'], $data['before']); 110 111 if ($data['sort'] === 'mtime') { 112 uksort($docs, static function ($a, $b) { 113 return filemtime(wikiFN($b)) - filemtime(wikiFN($a)); 114 }); 115 } else { 116 arsort($docs); 117 } 118 119 return $docs; 120 } 121 122 /** 123 * Creates a snippet extract 124 * 125 * @author Andreas Gohr <andi@splitbrain.org> 126 * @triggers FULLTEXT_SNIPPET_CREATE 127 * 128 * @param string $id page id 129 * @param array $highlight 130 * @return mixed 131 */ 132 public function snippet($id, $highlight) 133 { 134 $text = rawWiki($id); 135 $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens 136 $evdata = array( 137 'id' => $id, 138 'text' => &$text, 139 'highlight' => &$highlight, 140 'snippet' => '', 141 ); 142 143 $evt = new Event('FULLTEXT_SNIPPET_CREATE', $evdata); 144 if ($evt->advise_before()) { 145 $match = array(); 146 $snippets = array(); 147 $utf8_offset = $offset = $end = 0; 148 $len = Utf8\PhpString::strlen($text); 149 150 // build a regexp from the phrases to highlight 151 $re1 = '(' . 152 join( 153 '|', 154 array_map( 155 [$this, 'snippetRePreprocess'], 156 array_map( 157 'preg_quote_cb', 158 array_filter((array) $highlight) 159 ) 160 ) 161 ) . 162 ')'; 163 $re2 = "$re1.{0,75}(?!\\1)$re1"; 164 $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1"; 165 166 for ($cnt=4; $cnt--;) { 167 if (0) { 168 } elseif (preg_match('/'.$re3.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) { 169 } elseif (preg_match('/'.$re2.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) { 170 } elseif (preg_match('/'.$re1.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) { 171 } else { 172 break; 173 } 174 175 list($str, $idx) = $match[0]; 176 177 // convert $idx (a byte offset) into a utf8 character offset 178 $utf8_idx = Utf8\PhpString::strlen(substr($text, 0, $idx)); 179 $utf8_len = Utf8\PhpString::strlen($str); 180 181 // establish context, 100 bytes surrounding the match string 182 // first look to see if we can go 100 either side, 183 // then drop to 50 adding any excess if the other side can't go to 50, 184 $pre = min($utf8_idx - $utf8_offset, 100); 185 $post = min($len - $utf8_idx - $utf8_len, 100); 186 187 if ($pre > 50 && $post > 50) { 188 $pre = $post = 50; 189 } elseif ($pre > 50) { 190 $pre = min($pre, 100 - $post); 191 } elseif ($post > 50) { 192 $post = min($post, 100 - $pre); 193 } elseif ($offset == 0) { 194 // both are less than 50, means the context is the whole string 195 // make it so and break out of this loop - there is no need for the 196 // complex snippet calculations 197 $snippets = array($text); 198 break; 199 } 200 201 // establish context start and end points, try to append to previous 202 // context if possible 203 $start = $utf8_idx - $pre; 204 $append = ($start < $end) ? $end : false; // still the end of the previous context snippet 205 $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context 206 207 if ($append) { 208 $snippets[count($snippets)-1] .= Utf8\PhpString::substr($text, $append, $end-$append); 209 } else { 210 $snippets[] = Utf8\PhpString::substr($text, $start, $end-$start); 211 } 212 213 // set $offset for next match attempt 214 // continue matching after the current match 215 // if the current match is not the longest possible match starting at the current offset 216 // this prevents further matching of this snippet but for possible matches of length 217 // smaller than match length + context (at least 50 characters) this match is part of the context 218 $utf8_offset = $utf8_idx + $utf8_len; 219 $offset = $idx + strlen(Utf8\PhpString::substr($text, $utf8_idx, $utf8_len)); 220 $offset = Utf8\Clean::correctIdx($text, $offset); 221 } 222 223 $m = "\1"; 224 $snippets = preg_replace('/'.$re1.'/iu', $m.'$1'.$m, $snippets); 225 $snippet = preg_replace( 226 '/' . $m . '([^' . $m . ']*?)' . $m . '/iu', 227 '<strong class="search_hit">$1</strong>', 228 hsc(join('... ', $snippets)) 229 ); 230 231 $evdata['snippet'] = $snippet; 232 } 233 $evt->advise_after(); 234 unset($evt); 235 236 return $evdata['snippet']; 237 } 238 239 /** 240 * Wraps a search term in regex boundary checks. 241 * 242 * @param string $term 243 * @return string 244 */ 245 public function snippetRePreprocess($term) 246 { 247 // do not process asian terms where word boundaries are not explicit 248 if (Utf8\Asian::isAsianWords($term)) return $term; 249 250 if (UTF8_PROPERTYSUPPORT) { 251 // unicode word boundaries 252 // see http://stackoverflow.com/a/2449017/172068 253 $BL = '(?<!\pL)'; 254 $BR = '(?!\pL)'; 255 } else { 256 // not as correct as above, but at least won't break 257 $BL = '\b'; 258 $BR = '\b'; 259 } 260 261 if (substr($term, 0, 2) == '\\*') { 262 $term = substr($term, 2); 263 } else { 264 $term = $BL.$term; 265 } 266 267 if (substr($term, -2, 2) == '\\*') { 268 $term = substr($term, 0, -2); 269 } else { 270 $term = $term.$BR; 271 } 272 273 if ($term == $BL || $term == $BR || $term == $BL.$BR) { 274 $term = ''; 275 } 276 return $term; 277 } 278} 279