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