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