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 9if(!defined('DOKU_INC')) die('meh.'); 10 11/** 12 * create snippets for the first few results only 13 */ 14if(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15); 15 16/** 17 * The fulltext search 18 * 19 * Returns a list of matching documents for the given query 20 * 21 * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event() 22 * 23 */ 24function ft_pageSearch($query,&$highlight){ 25 26 $data['query'] = $query; 27 $data['highlight'] =& $highlight; 28 29 return trigger_event('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch'); 30} 31 32/** 33 * Returns a list of matching documents for the given query 34 * 35 * @author Andreas Gohr <andi@splitbrain.org> 36 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 37 */ 38function _ft_pageSearch(&$data) { 39 // parse the given query 40 $q = ft_queryParser($data['query']); 41 $data['highlight'] = $q['highlight']; 42 43 if (empty($q['parsed_ary'])) return array(); 44 45 // lookup all words found in the query 46 $lookup = idx_lookup($q['words']); 47 48 // get all pages in this dokuwiki site (!: includes nonexistent pages) 49 $pages_all = array(); 50 foreach (idx_getIndex('page', '') as $id) { 51 $pages_all[trim($id)] = 0; // base: 0 hit 52 } 53 54 // process the query 55 $stack = array(); 56 foreach ($q['parsed_ary'] as $token) { 57 switch (substr($token, 0, 3)) { 58 case 'W+:': 59 case 'W-:': 60 case 'W_:': // word 61 $word = substr($token, 3); 62 $stack[] = (array) $lookup[$word]; 63 break; 64 case 'P+:': 65 case 'P-:': // phrase 66 $phrase = substr($token, 3); 67 // since phrases are always parsed as ((W1)(W2)...(P)), 68 // the end($stack) always points the pages that contain 69 // all words in this phrase 70 $pages = end($stack); 71 $pages_matched = array(); 72 foreach(array_keys($pages) as $id){ 73 $text = utf8_strtolower(rawWiki($id)); 74 if (strpos($text, $phrase) !== false) { 75 $pages_matched[$id] = 0; // phrase: always 0 hit 76 } 77 } 78 $stack[] = $pages_matched; 79 break; 80 case 'N+:': 81 case 'N-:': // namespace 82 $ns = substr($token, 3); 83 $pages_matched = array(); 84 foreach (array_keys($pages_all) as $id) { 85 if (strpos($id, $ns) === 0) { 86 $pages_matched[$id] = 0; // namespace: always 0 hit 87 } 88 } 89 $stack[] = $pages_matched; 90 break; 91 case 'AND': // and operation 92 list($pages1, $pages2) = array_splice($stack, -2); 93 $stack[] = ft_resultCombine(array($pages1, $pages2)); 94 break; 95 case 'OR': // or operation 96 list($pages1, $pages2) = array_splice($stack, -2); 97 $stack[] = ft_resultUnite(array($pages1, $pages2)); 98 break; 99 case 'NOT': // not operation (unary) 100 $pages = array_pop($stack); 101 $stack[] = ft_resultComplement(array($pages_all, $pages)); 102 break; 103 } 104 } 105 $docs = array_pop($stack); 106 107 if (empty($docs)) return array(); 108 109 // check: settings, acls, existence 110 foreach (array_keys($docs) as $id) { 111 if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) { 112 unset($docs[$id]); 113 } 114 } 115 116 // sort docs by count 117 arsort($docs); 118 119 return $docs; 120} 121 122/** 123 * Returns the backlinks for a given page 124 * 125 * Does a quick lookup with the fulltext index, then 126 * evaluates the instructions of the found pages 127 */ 128function ft_backlinks($id){ 129 global $conf; 130 $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 131 $stopwords = @file_exists($swfile) ? file($swfile) : array(); 132 133 $result = array(); 134 135 // quick lookup of the pagename 136 $page = noNS($id); 137 $matches = idx_lookup(idx_tokenizer($page,$stopwords)); // pagename may contain specials (_ or .) 138 $docs = array_keys(ft_resultCombine(array_values($matches))); 139 $docs = array_filter($docs,'isVisiblePage'); // discard hidden pages 140 if(!count($docs)) return $result; 141 142 // check metadata for matching links 143 foreach($docs as $match){ 144 // metadata relation reference links are already resolved 145 $links = p_get_metadata($match,'relation references'); 146 if (isset($links[$id])) $result[] = $match; 147 } 148 149 if(!count($result)) return $result; 150 151 // check ACL permissions 152 foreach(array_keys($result) as $idx){ 153 if(auth_quickaclcheck($result[$idx]) < AUTH_READ){ 154 unset($result[$idx]); 155 } 156 } 157 158 sort($result); 159 return $result; 160} 161 162/** 163 * Returns the pages that use a given media file 164 * 165 * Does a quick lookup with the fulltext index, then 166 * evaluates the instructions of the found pages 167 * 168 * Aborts after $max found results 169 */ 170function ft_mediause($id,$max){ 171 global $conf; 172 $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 173 $stopwords = @file_exists($swfile) ? file($swfile) : array(); 174 175 if(!$max) $max = 1; // need to find at least one 176 177 $result = array(); 178 179 // quick lookup of the mediafile 180 $media = noNS($id); 181 $matches = idx_lookup(idx_tokenizer($media,$stopwords)); 182 $docs = array_keys(ft_resultCombine(array_values($matches))); 183 if(!count($docs)) return $result; 184 185 // go through all found pages 186 $found = 0; 187 $pcre = preg_quote($media,'/'); 188 foreach($docs as $doc){ 189 $ns = getNS($doc); 190 preg_match_all('/\{\{([^|}]*'.$pcre.'[^|}]*)(|[^}]+)?\}\}/i',rawWiki($doc),$matches); 191 foreach($matches[1] as $img){ 192 $img = trim($img); 193 if(preg_match('/^https?:\/\//i',$img)) continue; // skip external images 194 list($img) = explode('?',$img); // remove any parameters 195 resolve_mediaid($ns,$img,$exists); // resolve the possibly relative img 196 197 if($img == $id){ // we have a match 198 $result[] = $doc; 199 $found++; 200 break; 201 } 202 } 203 if($found >= $max) break; 204 } 205 206 sort($result); 207 return $result; 208} 209 210 211 212/** 213 * Quicksearch for pagenames 214 * 215 * By default it only matches the pagename and ignores the 216 * namespace. This can be changed with the second parameter. 217 * The third parameter allows to search in titles as well. 218 * 219 * The function always returns titles as well 220 * 221 * @triggers SEARCH_QUERY_PAGELOOKUP 222 * @author Andreas Gohr <andi@splitbrain.org> 223 * @author Adrian Lang <lang@cosmocode.de> 224 */ 225function ft_pageLookup($id, $in_ns=false, $in_title=false){ 226 $data = compact('id', 'in_ns', 'in_title'); 227 $data['has_titles'] = true; // for plugin backward compatibility check 228 return trigger_event('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup'); 229} 230 231function _ft_pageLookup(&$data){ 232 // split out original parameters 233 $id = $data['id']; 234 if (preg_match('/(?:^| )@(\w+)/', $id, $matches)) { 235 $ns = cleanID($matches[1]) . ':'; 236 $id = str_replace($matches[0], '', $id); 237 } 238 239 $in_ns = $data['in_ns']; 240 $in_title = $data['in_title']; 241 242 $pages = array_map('rtrim', idx_getIndex('page', '')); 243 $titles = array_map('rtrim', idx_getIndex('title', '')); 244 $pages = array_combine($pages, $titles); 245 246 if($id !== '' && cleanID($id) !== '') { 247 $cleaned = cleanID($id); 248 $matched_pages = array(); 249 foreach ($pages as $p_id => $p_title) { 250 if (((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false) || 251 ($in_title && stripos($p_title, $id) !== false)) && 252 (!isset($ns) || strpos($p_id, $ns) === 0)) { 253 $matched_pages[$p_id] = $p_title; 254 } 255 } 256 $pages = $matched_pages; 257 } 258 259 // discard hidden pages 260 // discard nonexistent pages 261 // check ACL permissions 262 foreach(array_keys($pages) as $idx){ 263 if(!isVisiblePage($idx) || !page_exists($idx) || 264 auth_quickaclcheck($idx) < AUTH_READ) { 265 unset($pages[$idx]); 266 } 267 } 268 269 uasort($pages,'ft_pagesorter'); 270 return $pages; 271} 272 273/** 274 * Sort pages based on their namespace level first, then on their string 275 * values. This makes higher hierarchy pages rank higher than lower hierarchy 276 * pages. 277 */ 278function ft_pagesorter($a, $b){ 279 $ac = count(explode(':',$a)); 280 $bc = count(explode(':',$b)); 281 if($ac < $bc){ 282 return -1; 283 }elseif($ac > $bc){ 284 return 1; 285 } 286 return strcmp ($a,$b); 287} 288 289/** 290 * Creates a snippet extract 291 * 292 * @author Andreas Gohr <andi@splitbrain.org> 293 * @triggers FULLTEXT_SNIPPET_CREATE 294 */ 295function ft_snippet($id,$highlight){ 296 $text = rawWiki($id); 297 $evdata = array( 298 'id' => $id, 299 'text' => &$text, 300 'highlight' => &$highlight, 301 'snippet' => '', 302 ); 303 304 $evt = new Doku_Event('FULLTEXT_SNIPPET_CREATE',$evdata); 305 if ($evt->advise_before()) { 306 $match = array(); 307 $snippets = array(); 308 $utf8_offset = $offset = $end = 0; 309 $len = utf8_strlen($text); 310 311 // build a regexp from the phrases to highlight 312 $re1 = '('.join('|',array_map('preg_quote_cb',array_filter((array) $highlight))).')'; 313 $re2 = "$re1.{0,75}(?!\\1)$re1"; 314 $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1"; 315 316 for ($cnt=4; $cnt--;) { 317 if (0) { 318 } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 319 } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 320 } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 321 } else { 322 break; 323 } 324 325 list($str,$idx) = $match[0]; 326 327 // convert $idx (a byte offset) into a utf8 character offset 328 $utf8_idx = utf8_strlen(substr($text,0,$idx)); 329 $utf8_len = utf8_strlen($str); 330 331 // establish context, 100 bytes surrounding the match string 332 // first look to see if we can go 100 either side, 333 // then drop to 50 adding any excess if the other side can't go to 50, 334 $pre = min($utf8_idx-$utf8_offset,100); 335 $post = min($len-$utf8_idx-$utf8_len,100); 336 337 if ($pre>50 && $post>50) { 338 $pre = $post = 50; 339 } else if ($pre>50) { 340 $pre = min($pre,100-$post); 341 } else if ($post>50) { 342 $post = min($post, 100-$pre); 343 } else { 344 // both are less than 50, means the context is the whole string 345 // make it so and break out of this loop - there is no need for the 346 // complex snippet calculations 347 $snippets = array($text); 348 break; 349 } 350 351 // establish context start and end points, try to append to previous 352 // context if possible 353 $start = $utf8_idx - $pre; 354 $append = ($start < $end) ? $end : false; // still the end of the previous context snippet 355 $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context 356 357 if ($append) { 358 $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append); 359 } else { 360 $snippets[] = utf8_substr($text,$start,$end-$start); 361 } 362 363 // set $offset for next match attempt 364 // substract strlen to avoid splitting a potential search success, 365 // this is an approximation as the search pattern may match strings 366 // of varying length and it will fail if the context snippet 367 // boundary breaks a matching string longer than the current match 368 $utf8_offset = $utf8_idx + $post; 369 $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$post)); 370 $offset = utf8_correctIdx($text,$offset); 371 } 372 373 $m = "\1"; 374 $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets); 375 $snippet = preg_replace('/'.$m.'([^'.$m.']*?)'.$m.'/iu','<strong class="search_hit">$1</strong>',hsc(join('... ',$snippets))); 376 377 $evdata['snippet'] = $snippet; 378 } 379 $evt->advise_after(); 380 unset($evt); 381 382 return $evdata['snippet']; 383} 384 385/** 386 * Combine found documents and sum up their scores 387 * 388 * This function is used to combine searched words with a logical 389 * AND. Only documents available in all arrays are returned. 390 * 391 * based upon PEAR's PHP_Compat function for array_intersect_key() 392 * 393 * @param array $args An array of page arrays 394 */ 395function ft_resultCombine($args){ 396 $array_count = count($args); 397 if($array_count == 1){ 398 return $args[0]; 399 } 400 401 $result = array(); 402 if ($array_count > 1) { 403 foreach ($args[0] as $key => $value) { 404 $result[$key] = $value; 405 for ($i = 1; $i !== $array_count; $i++) { 406 if (!isset($args[$i][$key])) { 407 unset($result[$key]); 408 break; 409 } 410 $result[$key] += $args[$i][$key]; 411 } 412 } 413 } 414 return $result; 415} 416 417/** 418 * Unites found documents and sum up their scores 419 * 420 * based upon ft_resultCombine() function 421 * 422 * @param array $args An array of page arrays 423 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 424 */ 425function ft_resultUnite($args) { 426 $array_count = count($args); 427 if ($array_count === 1) { 428 return $args[0]; 429 } 430 431 $result = $args[0]; 432 for ($i = 1; $i !== $array_count; $i++) { 433 foreach (array_keys($args[$i]) as $id) { 434 $result[$id] += $args[$i][$id]; 435 } 436 } 437 return $result; 438} 439 440/** 441 * Computes the difference of documents using page id for comparison 442 * 443 * nearly identical to PHP5's array_diff_key() 444 * 445 * @param array $args An array of page arrays 446 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 447 */ 448function ft_resultComplement($args) { 449 $array_count = count($args); 450 if ($array_count === 1) { 451 return $args[0]; 452 } 453 454 $result = $args[0]; 455 foreach (array_keys($result) as $id) { 456 for ($i = 1; $i !== $array_count; $i++) { 457 if (isset($args[$i][$id])) unset($result[$id]); 458 } 459 } 460 return $result; 461} 462 463/** 464 * Parses a search query and builds an array of search formulas 465 * 466 * @author Andreas Gohr <andi@splitbrain.org> 467 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 468 */ 469function ft_queryParser($query){ 470 global $conf; 471 $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt'; 472 $stopwords = @file_exists($swfile) ? file($swfile) : array(); 473 474 /** 475 * parse a search query and transform it into intermediate representation 476 * 477 * in a search query, you can use the following expressions: 478 * 479 * words: 480 * include 481 * -exclude 482 * phrases: 483 * "phrase to be included" 484 * -"phrase you want to exclude" 485 * namespaces: 486 * @include:namespace (or ns:include:namespace) 487 * ^exclude:namespace (or -ns:exclude:namespace) 488 * groups: 489 * () 490 * -() 491 * operators: 492 * and ('and' is the default operator: you can always omit this) 493 * or (or pipe symbol '|', lower precedence than 'and') 494 * 495 * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain 496 * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'". 497 * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ] 498 * as long as you don't mind hit counts. 499 * 500 * intermediate representation consists of the following parts: 501 * 502 * ( ) - group 503 * AND - logical and 504 * OR - logical or 505 * NOT - logical not 506 * W+:, W-:, W_: - word (underscore: no need to highlight) 507 * P+:, P-: - phrase (minus sign: logically in NOT group) 508 * N+:, N-: - namespace 509 */ 510 $parsed_query = ''; 511 $parens_level = 0; 512 $terms = preg_split('/(-?".*?")/u', utf8_strtolower($query), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 513 514 foreach ($terms as $term) { 515 $parsed = ''; 516 if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) { 517 // phrase-include and phrase-exclude 518 $not = $matches[1] ? 'NOT' : ''; 519 $parsed = $not.ft_termParser($matches[2], $stopwords, false, true); 520 } else { 521 // fix incomplete phrase 522 $term = str_replace('"', ' ', $term); 523 524 // fix parentheses 525 $term = str_replace(')' , ' ) ', $term); 526 $term = str_replace('(' , ' ( ', $term); 527 $term = str_replace('- (', ' -(', $term); 528 529 // treat pipe symbols as 'OR' operators 530 $term = str_replace('|', ' or ', $term); 531 532 // treat ideographic spaces (U+3000) as search term separators 533 // FIXME: some more separators? 534 $term = preg_replace('/[ \x{3000}]+/u', ' ', $term); 535 $term = trim($term); 536 if ($term === '') continue; 537 538 $tokens = explode(' ', $term); 539 foreach ($tokens as $token) { 540 if ($token === '(') { 541 // parenthesis-include-open 542 $parsed .= '('; 543 ++$parens_level; 544 } elseif ($token === '-(') { 545 // parenthesis-exclude-open 546 $parsed .= 'NOT('; 547 ++$parens_level; 548 } elseif ($token === ')') { 549 // parenthesis-any-close 550 if ($parens_level === 0) continue; 551 $parsed .= ')'; 552 $parens_level--; 553 } elseif ($token === 'and') { 554 // logical-and (do nothing) 555 } elseif ($token === 'or') { 556 // logical-or 557 $parsed .= 'OR'; 558 } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) { 559 // namespace-exclude 560 $parsed .= 'NOT(N+:'.$matches[1].')'; 561 } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) { 562 // namespace-include 563 $parsed .= '(N+:'.$matches[1].')'; 564 } elseif (preg_match('/^-(.+)$/', $token, $matches)) { 565 // word-exclude 566 $parsed .= 'NOT('.ft_termParser($matches[1], $stopwords).')'; 567 } else { 568 // word-include 569 $parsed .= ft_termParser($token, $stopwords); 570 } 571 } 572 } 573 $parsed_query .= $parsed; 574 } 575 576 // cleanup (very sensitive) 577 $parsed_query .= str_repeat(')', $parens_level); 578 do { 579 $parsed_query_old = $parsed_query; 580 $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query); 581 } while ($parsed_query !== $parsed_query_old); 582 $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query); 583 $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query); 584 $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query); 585 $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query); 586 $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query); 587 588 // adjustment: make highlightings right 589 $parens_level = 0; 590 $notgrp_levels = array(); 591 $parsed_query_new = ''; 592 $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 593 foreach ($tokens as $token) { 594 if ($token === 'NOT(') { 595 $notgrp_levels[] = ++$parens_level; 596 } elseif ($token === '(') { 597 ++$parens_level; 598 } elseif ($token === ')') { 599 if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels); 600 } elseif (count($notgrp_levels) % 2 === 1) { 601 // turn highlight-flag off if terms are logically in "NOT" group 602 $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token); 603 } 604 $parsed_query_new .= $token; 605 } 606 $parsed_query = $parsed_query_new; 607 608 /** 609 * convert infix notation string into postfix (Reverse Polish notation) array 610 * by Shunting-yard algorithm 611 * 612 * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation 613 * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm 614 */ 615 $parsed_ary = array(); 616 $ope_stack = array(); 617 $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5); 618 $ope_regex = '/([()]|OR|AND|NOT)/u'; 619 620 $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 621 foreach ($tokens as $token) { 622 if (preg_match($ope_regex, $token)) { 623 // operator 624 $last_ope = end($ope_stack); 625 while ($ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') { 626 $parsed_ary[] = array_pop($ope_stack); 627 $last_ope = end($ope_stack); 628 } 629 if ($token == ')') { 630 array_pop($ope_stack); // this array_pop always deletes '(' 631 } else { 632 $ope_stack[] = $token; 633 } 634 } else { 635 // operand 636 $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token); 637 $parsed_ary[] = $token_decoded; 638 } 639 } 640 $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack))); 641 642 // cleanup: each double "NOT" in RPN array actually does nothing 643 $parsed_ary_count = count($parsed_ary); 644 for ($i = 1; $i < $parsed_ary_count; ++$i) { 645 if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') { 646 unset($parsed_ary[$i], $parsed_ary[$i - 1]); 647 } 648 } 649 $parsed_ary = array_values($parsed_ary); 650 651 // build return value 652 $q = array(); 653 $q['query'] = $query; 654 $q['parsed_str'] = $parsed_query; 655 $q['parsed_ary'] = $parsed_ary; 656 657 foreach ($q['parsed_ary'] as $token) { 658 if ($token[2] !== ':') continue; 659 $body = substr($token, 3); 660 661 switch (substr($token, 0, 3)) { 662 case 'N+:': 663 $q['ns'][] = $body; // for backward compatibility 664 break; 665 case 'N-:': 666 $q['notns'][] = $body; // for backward compatibility 667 break; 668 case 'W_:': 669 $q['words'][] = $body; 670 break; 671 case 'W-:': 672 $q['words'][] = $body; 673 $q['not'][] = $body; // for backward compatibility 674 break; 675 case 'W+:': 676 $q['words'][] = $body; 677 $q['highlight'][] = str_replace('*', '', $body); 678 $q['and'][] = $body; // for backward compatibility 679 break; 680 case 'P-:': 681 $q['phrases'][] = $body; 682 break; 683 case 'P+:': 684 $q['phrases'][] = $body; 685 $q['highlight'][] = str_replace('*', '', $body); 686 break; 687 } 688 } 689 foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) { 690 $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key])); 691 } 692 693 return $q; 694} 695 696/** 697 * Transforms given search term into intermediate representation 698 * 699 * This function is used in ft_queryParser() and not for general purpose use. 700 * 701 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 702 */ 703function ft_termParser($term, &$stopwords, $consider_asian = true, $phrase_mode = false) { 704 $parsed = ''; 705 if ($consider_asian) { 706 // successive asian characters need to be searched as a phrase 707 $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 708 foreach ($words as $word) { 709 if (preg_match('/'.IDX_ASIAN.'/u', $word)) $phrase_mode = true; 710 $parsed .= ft_termParser($word, $stopwords, false, $phrase_mode); 711 } 712 } else { 713 $term_noparen = str_replace(array('(', ')'), ' ', $term); 714 $words = idx_tokenizer($term_noparen, $stopwords, true); 715 716 // W_: no need to highlight 717 if (empty($words)) { 718 $parsed = '()'; // important: do not remove 719 } elseif ($words[0] === $term) { 720 $parsed = '(W+:'.$words[0].')'; 721 } elseif ($phrase_mode) { 722 $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term); 723 $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))'; 724 } else { 725 $parsed = '((W+:'.implode(')(W+:', $words).'))'; 726 } 727 } 728 return $parsed; 729} 730 731//Setup VIM: ex: et ts=4 enc=utf-8 : 732