1<?php 2/** 3 * DokuWiki fulltextsearch functions using the index 4 * 5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) 6 * @author Andreas Gohr <andi@splitbrain.org> 7 */ 8 9use dokuwiki\Extension\Event; 10use dokuwiki\Utf8\Sort; 11 12/** 13 * create snippets for the first few results only 14 */ 15if(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15); 16 17/** 18 * The fulltext search 19 * 20 * Returns a list of matching documents for the given query 21 * 22 * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event() 23 * 24 * @param string $query 25 * @param array $highlight 26 * @param string $sort 27 * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments 28 * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments 29 * 30 * @return array 31 */ 32function ft_pageSearch($query,&$highlight, $sort = null, $after = null, $before = null){ 33 34 if ($sort === null) { 35 $sort = 'hits'; 36 } 37 $data = [ 38 'query' => $query, 39 'sort' => $sort, 40 'after' => $after, 41 'before' => $before 42 ]; 43 $data['highlight'] =& $highlight; 44 45 return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch'); 46} 47 48/** 49 * Returns a list of matching documents for the given query 50 * 51 * @author Andreas Gohr <andi@splitbrain.org> 52 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 53 * 54 * @param array $data event data 55 * @return array matching documents 56 */ 57function _ft_pageSearch(&$data) { 58 $Indexer = idx_get_indexer(); 59 60 // parse the given query 61 $q = ft_queryParser($Indexer, $data['query']); 62 $data['highlight'] = $q['highlight']; 63 64 if (empty($q['parsed_ary'])) return array(); 65 66 // lookup all words found in the query 67 $lookup = $Indexer->lookup($q['words']); 68 69 // get all pages in this dokuwiki site (!: includes nonexistent pages) 70 $pages_all = array(); 71 foreach ($Indexer->getPages() as $id) { 72 $pages_all[$id] = 0; // base: 0 hit 73 } 74 75 // process the query 76 $stack = array(); 77 foreach ($q['parsed_ary'] as $token) { 78 switch (substr($token, 0, 3)) { 79 case 'W+:': 80 case 'W-:': 81 case 'W_:': // word 82 $word = substr($token, 3); 83 if(isset($lookup[$word])) { 84 $stack[] = (array)$lookup[$word]; 85 } 86 break; 87 case 'P+:': 88 case 'P-:': // phrase 89 $phrase = substr($token, 3); 90 // since phrases are always parsed as ((W1)(W2)...(P)), 91 // the end($stack) always points the pages that contain 92 // all words in this phrase 93 $pages = end($stack); 94 $pages_matched = array(); 95 foreach(array_keys($pages) as $id){ 96 $evdata = array( 97 'id' => $id, 98 'phrase' => $phrase, 99 'text' => rawWiki($id) 100 ); 101 $evt = new Event('FULLTEXT_PHRASE_MATCH',$evdata); 102 if ($evt->advise_before() && $evt->result !== true) { 103 $text = \dokuwiki\Utf8\PhpString::strtolower($evdata['text']); 104 if (strpos($text, $phrase) !== false) { 105 $evt->result = true; 106 } 107 } 108 $evt->advise_after(); 109 if ($evt->result === true) { 110 $pages_matched[$id] = 0; // phrase: always 0 hit 111 } 112 } 113 $stack[] = $pages_matched; 114 break; 115 case 'N+:': 116 case 'N-:': // namespace 117 $ns = cleanID(substr($token, 3)) . ':'; 118 $pages_matched = array(); 119 foreach (array_keys($pages_all) as $id) { 120 if (strpos($id, $ns) === 0) { 121 $pages_matched[$id] = 0; // namespace: always 0 hit 122 } 123 } 124 $stack[] = $pages_matched; 125 break; 126 case 'AND': // and operation 127 list($pages1, $pages2) = array_splice($stack, -2); 128 $stack[] = ft_resultCombine(array($pages1, $pages2)); 129 break; 130 case 'OR': // or operation 131 list($pages1, $pages2) = array_splice($stack, -2); 132 $stack[] = ft_resultUnite(array($pages1, $pages2)); 133 break; 134 case 'NOT': // not operation (unary) 135 $pages = array_pop($stack); 136 $stack[] = ft_resultComplement(array($pages_all, $pages)); 137 break; 138 } 139 } 140 $docs = array_pop($stack); 141 142 if (empty($docs)) return array(); 143 144 // check: settings, acls, existence 145 foreach (array_keys($docs) as $id) { 146 if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) { 147 unset($docs[$id]); 148 } 149 } 150 151 $docs = _ft_filterResultsByTime($docs, $data['after'], $data['before']); 152 153 if ($data['sort'] === 'mtime') { 154 uksort($docs, 'ft_pagemtimesorter'); 155 } else { 156 // sort docs by count 157 uksort($docs, 'ft_pagesorter'); 158 arsort($docs); 159 } 160 161 return $docs; 162} 163 164/** 165 * Returns the backlinks for a given page 166 * 167 * Uses the metadata index. 168 * 169 * @param string $id The id for which links shall be returned 170 * @param bool $ignore_perms Ignore the fact that pages are hidden or read-protected 171 * @return array The pages that contain links to the given page 172 */ 173function ft_backlinks($id, $ignore_perms = false){ 174 $result = idx_get_indexer()->lookupKey('relation_references', $id); 175 176 if(!count($result)) return $result; 177 178 // check ACL permissions 179 foreach(array_keys($result) as $idx){ 180 if(($ignore_perms !== true && ( 181 isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 182 )) || !page_exists($result[$idx], '', false)){ 183 unset($result[$idx]); 184 } 185 } 186 187 Sort::sort($result); 188 return $result; 189} 190 191/** 192 * Returns the pages that use a given media file 193 * 194 * Uses the relation media metadata property and the metadata index. 195 * 196 * Note that before 2013-07-31 the second parameter was the maximum number of results and 197 * permissions were ignored. That's why the parameter is now checked to be explicitely set 198 * to true (with type bool) in order to be compatible with older uses of the function. 199 * 200 * @param string $id The media id to look for 201 * @param bool $ignore_perms Ignore hidden pages and acls (optional, default: false) 202 * @return array A list of pages that use the given media file 203 */ 204function ft_mediause($id, $ignore_perms = false){ 205 $result = idx_get_indexer()->lookupKey('relation_media', $id); 206 207 if(!count($result)) return $result; 208 209 // check ACL permissions 210 foreach(array_keys($result) as $idx){ 211 if(($ignore_perms !== true && ( 212 isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 213 )) || !page_exists($result[$idx], '', false)){ 214 unset($result[$idx]); 215 } 216 } 217 218 Sort::sort($result); 219 return $result; 220} 221 222 223/** 224 * Quicksearch for pagenames 225 * 226 * By default it only matches the pagename and ignores the 227 * namespace. This can be changed with the second parameter. 228 * The third parameter allows to search in titles as well. 229 * 230 * The function always returns titles as well 231 * 232 * @triggers SEARCH_QUERY_PAGELOOKUP 233 * @author Andreas Gohr <andi@splitbrain.org> 234 * @author Adrian Lang <lang@cosmocode.de> 235 * 236 * @param string $id page id 237 * @param bool $in_ns match against namespace as well? 238 * @param bool $in_title search in title? 239 * @param int|string $after only show results with mtime after this date, accepts timestap or strtotime arguments 240 * @param int|string $before only show results with mtime before this date, accepts timestap or strtotime arguments 241 * 242 * @return string[] 243 */ 244function ft_pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null){ 245 $data = [ 246 'id' => $id, 247 'in_ns' => $in_ns, 248 'in_title' => $in_title, 249 'after' => $after, 250 'before' => $before 251 ]; 252 $data['has_titles'] = true; // for plugin backward compatibility check 253 return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup'); 254} 255 256/** 257 * Returns list of pages as array(pageid => First Heading) 258 * 259 * @param array &$data event data 260 * @return string[] 261 */ 262function _ft_pageLookup(&$data){ 263 // split out original parameters 264 $id = $data['id']; 265 $Indexer = idx_get_indexer(); 266 $parsedQuery = ft_queryParser($Indexer, $id); 267 if (count($parsedQuery['ns']) > 0) { 268 $ns = cleanID($parsedQuery['ns'][0]) . ':'; 269 $id = implode(' ', $parsedQuery['highlight']); 270 } 271 272 $in_ns = $data['in_ns']; 273 $in_title = $data['in_title']; 274 $cleaned = cleanID($id); 275 276 $Indexer = idx_get_indexer(); 277 $page_idx = $Indexer->getPages(); 278 279 $pages = array(); 280 if ($id !== '' && $cleaned !== '') { 281 foreach ($page_idx as $p_id) { 282 if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) { 283 if (!isset($pages[$p_id])) 284 $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 285 } 286 } 287 if ($in_title) { 288 foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) { 289 if (!isset($pages[$p_id])) 290 $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 291 } 292 } 293 } 294 295 if (isset($ns)) { 296 foreach (array_keys($pages) as $p_id) { 297 if (strpos($p_id, $ns) !== 0) { 298 unset($pages[$p_id]); 299 } 300 } 301 } 302 303 // discard hidden pages 304 // discard nonexistent pages 305 // check ACL permissions 306 foreach(array_keys($pages) as $idx){ 307 if(!isVisiblePage($idx) || !page_exists($idx) || 308 auth_quickaclcheck($idx) < AUTH_READ) { 309 unset($pages[$idx]); 310 } 311 } 312 313 $pages = _ft_filterResultsByTime($pages, $data['after'], $data['before']); 314 315 uksort($pages,'ft_pagesorter'); 316 return $pages; 317} 318 319 320/** 321 * @param array $results search results in the form pageid => value 322 * @param int|string $after only returns results with mtime after this date, accepts timestap or strtotime arguments 323 * @param int|string $before only returns results with mtime after this date, accepts timestap or strtotime arguments 324 * 325 * @return array 326 */ 327function _ft_filterResultsByTime(array $results, $after, $before) { 328 if ($after || $before) { 329 $after = is_int($after) ? $after : strtotime($after); 330 $before = is_int($before) ? $before : strtotime($before); 331 332 foreach ($results as $id => $value) { 333 $mTime = filemtime(wikiFN($id)); 334 if ($after && $after > $mTime) { 335 unset($results[$id]); 336 continue; 337 } 338 if ($before && $before < $mTime) { 339 unset($results[$id]); 340 } 341 } 342 } 343 344 return $results; 345} 346 347/** 348 * Tiny helper function for comparing the searched title with the title 349 * from the search index. This function is a wrapper around stripos with 350 * adapted argument order and return value. 351 * 352 * @param string $search searched title 353 * @param string $title title from index 354 * @return bool 355 */ 356function _ft_pageLookupTitleCompare($search, $title) { 357 return stripos($title, $search) !== false; 358} 359 360/** 361 * Sort pages based on their namespace level first, then on their string 362 * values. This makes higher hierarchy pages rank higher than lower hierarchy 363 * pages. 364 * 365 * @param string $a 366 * @param string $b 367 * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal. 368 */ 369function ft_pagesorter($a, $b){ 370 $ac = count(explode(':',$a)); 371 $bc = count(explode(':',$b)); 372 if($ac < $bc){ 373 return -1; 374 }elseif($ac > $bc){ 375 return 1; 376 } 377 return Sort::strcmp($a,$b); 378} 379 380/** 381 * Sort pages by their mtime, from newest to oldest 382 * 383 * @param string $a 384 * @param string $b 385 * 386 * @return int Returns < 0 if $a is newer than $b, > 0 if $b is newer than $a and 0 if they are of the same age 387 */ 388function ft_pagemtimesorter($a, $b) { 389 $mtimeA = filemtime(wikiFN($a)); 390 $mtimeB = filemtime(wikiFN($b)); 391 return $mtimeB - $mtimeA; 392} 393 394/** 395 * Creates a snippet extract 396 * 397 * @author Andreas Gohr <andi@splitbrain.org> 398 * @triggers FULLTEXT_SNIPPET_CREATE 399 * 400 * @param string $id page id 401 * @param array $highlight 402 * @return mixed 403 */ 404function ft_snippet($id,$highlight){ 405 $text = rawWiki($id); 406 $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens 407 $evdata = array( 408 'id' => $id, 409 'text' => &$text, 410 'highlight' => &$highlight, 411 'snippet' => '', 412 ); 413 414 $evt = new Event('FULLTEXT_SNIPPET_CREATE',$evdata); 415 if ($evt->advise_before()) { 416 $match = array(); 417 $snippets = array(); 418 $utf8_offset = $offset = $end = 0; 419 $len = \dokuwiki\Utf8\PhpString::strlen($text); 420 421 // build a regexp from the phrases to highlight 422 $re1 = '(' . 423 join( 424 '|', 425 array_map( 426 'ft_snippet_re_preprocess', 427 array_map( 428 'preg_quote_cb', 429 array_filter((array) $highlight) 430 ) 431 ) 432 ) . 433 ')'; 434 $re2 = "$re1.{0,75}(?!\\1)$re1"; 435 $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1"; 436 437 for ($cnt=4; $cnt--;) { 438 if (0) { 439 } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 440 } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 441 } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 442 } else { 443 break; 444 } 445 446 list($str,$idx) = $match[0]; 447 448 // convert $idx (a byte offset) into a utf8 character offset 449 $utf8_idx = \dokuwiki\Utf8\PhpString::strlen(substr($text,0,$idx)); 450 $utf8_len = \dokuwiki\Utf8\PhpString::strlen($str); 451 452 // establish context, 100 bytes surrounding the match string 453 // first look to see if we can go 100 either side, 454 // then drop to 50 adding any excess if the other side can't go to 50, 455 $pre = min($utf8_idx-$utf8_offset,100); 456 $post = min($len-$utf8_idx-$utf8_len,100); 457 458 if ($pre>50 && $post>50) { 459 $pre = $post = 50; 460 } else if ($pre>50) { 461 $pre = min($pre,100-$post); 462 } else if ($post>50) { 463 $post = min($post, 100-$pre); 464 } else if ($offset == 0) { 465 // both are less than 50, means the context is the whole string 466 // make it so and break out of this loop - there is no need for the 467 // complex snippet calculations 468 $snippets = array($text); 469 break; 470 } 471 472 // establish context start and end points, try to append to previous 473 // context if possible 474 $start = $utf8_idx - $pre; 475 $append = ($start < $end) ? $end : false; // still the end of the previous context snippet 476 $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context 477 478 if ($append) { 479 $snippets[count($snippets)-1] .= \dokuwiki\Utf8\PhpString::substr($text,$append,$end-$append); 480 } else { 481 $snippets[] = \dokuwiki\Utf8\PhpString::substr($text,$start,$end-$start); 482 } 483 484 // set $offset for next match attempt 485 // continue matching after the current match 486 // if the current match is not the longest possible match starting at the current offset 487 // this prevents further matching of this snippet but for possible matches of length 488 // smaller than match length + context (at least 50 characters) this match is part of the context 489 $utf8_offset = $utf8_idx + $utf8_len; 490 $offset = $idx + strlen(\dokuwiki\Utf8\PhpString::substr($text,$utf8_idx,$utf8_len)); 491 $offset = \dokuwiki\Utf8\Clean::correctIdx($text,$offset); 492 } 493 494 $m = "\1"; 495 $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets); 496 $snippet = preg_replace( 497 '/' . $m . '([^' . $m . ']*?)' . $m . '/iu', 498 '<strong class="search_hit">$1</strong>', 499 hsc(join('... ', $snippets)) 500 ); 501 502 $evdata['snippet'] = $snippet; 503 } 504 $evt->advise_after(); 505 unset($evt); 506 507 return $evdata['snippet']; 508} 509 510/** 511 * Wraps a search term in regex boundary checks. 512 * 513 * @param string $term 514 * @return string 515 */ 516function ft_snippet_re_preprocess($term) { 517 // do not process asian terms where word boundaries are not explicit 518 if(\dokuwiki\Utf8\Asian::isAsianWords($term)) return $term; 519 520 if (UTF8_PROPERTYSUPPORT) { 521 // unicode word boundaries 522 // see http://stackoverflow.com/a/2449017/172068 523 $BL = '(?<!\pL)'; 524 $BR = '(?!\pL)'; 525 } else { 526 // not as correct as above, but at least won't break 527 $BL = '\b'; 528 $BR = '\b'; 529 } 530 531 if(substr($term,0,2) == '\\*'){ 532 $term = substr($term,2); 533 }else{ 534 $term = $BL.$term; 535 } 536 537 if(substr($term,-2,2) == '\\*'){ 538 $term = substr($term,0,-2); 539 }else{ 540 $term = $term.$BR; 541 } 542 543 if($term == $BL || $term == $BR || $term == $BL.$BR) $term = ''; 544 return $term; 545} 546 547/** 548 * Combine found documents and sum up their scores 549 * 550 * This function is used to combine searched words with a logical 551 * AND. Only documents available in all arrays are returned. 552 * 553 * based upon PEAR's PHP_Compat function for array_intersect_key() 554 * 555 * @param array $args An array of page arrays 556 * @return array 557 */ 558function ft_resultCombine($args){ 559 $array_count = count($args); 560 if($array_count == 1){ 561 return $args[0]; 562 } 563 564 $result = array(); 565 if ($array_count > 1) { 566 foreach ($args[0] as $key => $value) { 567 $result[$key] = $value; 568 for ($i = 1; $i !== $array_count; $i++) { 569 if (!isset($args[$i][$key])) { 570 unset($result[$key]); 571 break; 572 } 573 $result[$key] += $args[$i][$key]; 574 } 575 } 576 } 577 return $result; 578} 579 580/** 581 * Unites found documents and sum up their scores 582 * 583 * based upon ft_resultCombine() function 584 * 585 * @param array $args An array of page arrays 586 * @return array 587 * 588 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 589 */ 590function ft_resultUnite($args) { 591 $array_count = count($args); 592 if ($array_count === 1) { 593 return $args[0]; 594 } 595 596 $result = $args[0]; 597 for ($i = 1; $i !== $array_count; $i++) { 598 foreach (array_keys($args[$i]) as $id) { 599 $result[$id] += $args[$i][$id]; 600 } 601 } 602 return $result; 603} 604 605/** 606 * Computes the difference of documents using page id for comparison 607 * 608 * nearly identical to PHP5's array_diff_key() 609 * 610 * @param array $args An array of page arrays 611 * @return array 612 * 613 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 614 */ 615function ft_resultComplement($args) { 616 $array_count = count($args); 617 if ($array_count === 1) { 618 return $args[0]; 619 } 620 621 $result = $args[0]; 622 foreach (array_keys($result) as $id) { 623 for ($i = 1; $i !== $array_count; $i++) { 624 if (isset($args[$i][$id])) unset($result[$id]); 625 } 626 } 627 return $result; 628} 629 630/** 631 * Parses a search query and builds an array of search formulas 632 * 633 * @author Andreas Gohr <andi@splitbrain.org> 634 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 635 * 636 * @param dokuwiki\Search\Indexer $Indexer 637 * @param string $query search query 638 * @return array of search formulas 639 */ 640function ft_queryParser($Indexer, $query){ 641 /** 642 * parse a search query and transform it into intermediate representation 643 * 644 * in a search query, you can use the following expressions: 645 * 646 * words: 647 * include 648 * -exclude 649 * phrases: 650 * "phrase to be included" 651 * -"phrase you want to exclude" 652 * namespaces: 653 * @include:namespace (or ns:include:namespace) 654 * ^exclude:namespace (or -ns:exclude:namespace) 655 * groups: 656 * () 657 * -() 658 * operators: 659 * and ('and' is the default operator: you can always omit this) 660 * or (or pipe symbol '|', lower precedence than 'and') 661 * 662 * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain 663 * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'". 664 * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ] 665 * as long as you don't mind hit counts. 666 * 667 * intermediate representation consists of the following parts: 668 * 669 * ( ) - group 670 * AND - logical and 671 * OR - logical or 672 * NOT - logical not 673 * W+:, W-:, W_: - word (underscore: no need to highlight) 674 * P+:, P-: - phrase (minus sign: logically in NOT group) 675 * N+:, N-: - namespace 676 */ 677 $parsed_query = ''; 678 $parens_level = 0; 679 $terms = preg_split('/(-?".*?")/u', \dokuwiki\Utf8\PhpString::strtolower($query), 680 -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 681 682 foreach ($terms as $term) { 683 $parsed = ''; 684 if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) { 685 // phrase-include and phrase-exclude 686 $not = $matches[1] ? 'NOT' : ''; 687 $parsed = $not.ft_termParser($Indexer, $matches[2], false, true); 688 } else { 689 // fix incomplete phrase 690 $term = str_replace('"', ' ', $term); 691 692 // fix parentheses 693 $term = str_replace(')' , ' ) ', $term); 694 $term = str_replace('(' , ' ( ', $term); 695 $term = str_replace('- (', ' -(', $term); 696 697 // treat pipe symbols as 'OR' operators 698 $term = str_replace('|', ' or ', $term); 699 700 // treat ideographic spaces (U+3000) as search term separators 701 // FIXME: some more separators? 702 $term = preg_replace('/[ \x{3000}]+/u', ' ', $term); 703 $term = trim($term); 704 if ($term === '') continue; 705 706 $tokens = explode(' ', $term); 707 foreach ($tokens as $token) { 708 if ($token === '(') { 709 // parenthesis-include-open 710 $parsed .= '('; 711 ++$parens_level; 712 } elseif ($token === '-(') { 713 // parenthesis-exclude-open 714 $parsed .= 'NOT('; 715 ++$parens_level; 716 } elseif ($token === ')') { 717 // parenthesis-any-close 718 if ($parens_level === 0) continue; 719 $parsed .= ')'; 720 $parens_level--; 721 } elseif ($token === 'and') { 722 // logical-and (do nothing) 723 } elseif ($token === 'or') { 724 // logical-or 725 $parsed .= 'OR'; 726 } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) { 727 // namespace-exclude 728 $parsed .= 'NOT(N+:'.$matches[1].')'; 729 } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) { 730 // namespace-include 731 $parsed .= '(N+:'.$matches[1].')'; 732 } elseif (preg_match('/^-(.+)$/', $token, $matches)) { 733 // word-exclude 734 $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')'; 735 } else { 736 // word-include 737 $parsed .= ft_termParser($Indexer, $token); 738 } 739 } 740 } 741 $parsed_query .= $parsed; 742 } 743 744 // cleanup (very sensitive) 745 $parsed_query .= str_repeat(')', $parens_level); 746 do { 747 $parsed_query_old = $parsed_query; 748 $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query); 749 } while ($parsed_query !== $parsed_query_old); 750 $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query); 751 $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query); 752 $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query); 753 $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query); 754 $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query); 755 756 // adjustment: make highlightings right 757 $parens_level = 0; 758 $notgrp_levels = array(); 759 $parsed_query_new = ''; 760 $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 761 foreach ($tokens as $token) { 762 if ($token === 'NOT(') { 763 $notgrp_levels[] = ++$parens_level; 764 } elseif ($token === '(') { 765 ++$parens_level; 766 } elseif ($token === ')') { 767 if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels); 768 } elseif (count($notgrp_levels) % 2 === 1) { 769 // turn highlight-flag off if terms are logically in "NOT" group 770 $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token); 771 } 772 $parsed_query_new .= $token; 773 } 774 $parsed_query = $parsed_query_new; 775 776 /** 777 * convert infix notation string into postfix (Reverse Polish notation) array 778 * by Shunting-yard algorithm 779 * 780 * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation 781 * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm 782 */ 783 $parsed_ary = array(); 784 $ope_stack = array(); 785 $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5); 786 $ope_regex = '/([()]|OR|AND|NOT)/u'; 787 788 $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 789 foreach ($tokens as $token) { 790 if (preg_match($ope_regex, $token)) { 791 // operator 792 $last_ope = end($ope_stack); 793 while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') { 794 $parsed_ary[] = array_pop($ope_stack); 795 $last_ope = end($ope_stack); 796 } 797 if ($token == ')') { 798 array_pop($ope_stack); // this array_pop always deletes '(' 799 } else { 800 $ope_stack[] = $token; 801 } 802 } else { 803 // operand 804 $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token); 805 $parsed_ary[] = $token_decoded; 806 } 807 } 808 $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack))); 809 810 // cleanup: each double "NOT" in RPN array actually does nothing 811 $parsed_ary_count = count($parsed_ary); 812 for ($i = 1; $i < $parsed_ary_count; ++$i) { 813 if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') { 814 unset($parsed_ary[$i], $parsed_ary[$i - 1]); 815 } 816 } 817 $parsed_ary = array_values($parsed_ary); 818 819 // build return value 820 $q = array(); 821 $q['query'] = $query; 822 $q['parsed_str'] = $parsed_query; 823 $q['parsed_ary'] = $parsed_ary; 824 825 foreach ($q['parsed_ary'] as $token) { 826 if ($token[2] !== ':') continue; 827 $body = substr($token, 3); 828 829 switch (substr($token, 0, 3)) { 830 case 'N+:': 831 $q['ns'][] = $body; // for backward compatibility 832 break; 833 case 'N-:': 834 $q['notns'][] = $body; // for backward compatibility 835 break; 836 case 'W_:': 837 $q['words'][] = $body; 838 break; 839 case 'W-:': 840 $q['words'][] = $body; 841 $q['not'][] = $body; // for backward compatibility 842 break; 843 case 'W+:': 844 $q['words'][] = $body; 845 $q['highlight'][] = $body; 846 $q['and'][] = $body; // for backward compatibility 847 break; 848 case 'P-:': 849 $q['phrases'][] = $body; 850 break; 851 case 'P+:': 852 $q['phrases'][] = $body; 853 $q['highlight'][] = $body; 854 break; 855 } 856 } 857 foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) { 858 $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key])); 859 } 860 861 return $q; 862} 863 864/** 865 * Transforms given search term into intermediate representation 866 * 867 * This function is used in ft_queryParser() and not for general purpose use. 868 * 869 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 870 * 871 * @param dokuwiki\Search\Indexer $Indexer 872 * @param string $term 873 * @param bool $consider_asian 874 * @param bool $phrase_mode 875 * @return string 876 */ 877function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) { 878 $parsed = ''; 879 if ($consider_asian) { 880 // successive asian characters need to be searched as a phrase 881 $words = \dokuwiki\Utf8\Asian::splitAsianWords($term); 882 foreach ($words as $word) { 883 $phrase_mode = $phrase_mode ? true : \dokuwiki\Utf8\Asian::isAsianWords($word); 884 $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode); 885 } 886 } else { 887 $term_noparen = str_replace(array('(', ')'), ' ', $term); 888 $words = $Indexer->tokenizer($term_noparen, true); 889 890 // W_: no need to highlight 891 if (empty($words)) { 892 $parsed = '()'; // important: do not remove 893 } elseif ($words[0] === $term) { 894 $parsed = '(W+:'.$words[0].')'; 895 } elseif ($phrase_mode) { 896 $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term); 897 $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))'; 898 } else { 899 $parsed = '((W+:'.implode(')(W+:', $words).'))'; 900 } 901 } 902 return $parsed; 903} 904 905/** 906 * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches 907 * 908 * @param array $and 909 * @param array $not 910 * @param array $phrases 911 * @param array $ns 912 * @param array $notns 913 * 914 * @return string 915 */ 916function ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) { 917 $query = implode(' ', $and); 918 if (!empty($not)) { 919 $query .= ' -' . implode(' -', $not); 920 } 921 922 if (!empty($phrases)) { 923 $query .= ' "' . implode('" "', $phrases) . '"'; 924 } 925 926 if (!empty($ns)) { 927 $query .= ' @' . implode(' @', $ns); 928 } 929 930 if (!empty($notns)) { 931 $query .= ' ^' . implode(' ^', $notns); 932 } 933 934 return $query; 935} 936 937//Setup VIM: ex: et ts=4 : 938