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(isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ || !page_exists($result[$idx], '', false)){ 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(media_isexternal($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, METADATA_DONT_RENDER); 234 } 235 } 236 if ($in_title) { 237 foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) { 238 if (!isset($pages[$p_id])) 239 $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 240 } 241 } 242 } 243 244 if (isset($ns)) { 245 foreach (array_keys($pages) as $p_id) { 246 if (strpos($p_id, $ns) !== 0) { 247 unset($pages[$p_id]); 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 * Tiny helper function for comparing the searched title with the title 268 * from the search index. This function is a wrapper around stripos with 269 * adapted argument order and return value. 270 */ 271function _ft_pageLookupTitleCompare($search, $title) { 272 return stripos($title, $search) !== false; 273} 274 275/** 276 * Sort pages based on their namespace level first, then on their string 277 * values. This makes higher hierarchy pages rank higher than lower hierarchy 278 * pages. 279 */ 280function ft_pagesorter($a, $b){ 281 $ac = count(explode(':',$a)); 282 $bc = count(explode(':',$b)); 283 if($ac < $bc){ 284 return -1; 285 }elseif($ac > $bc){ 286 return 1; 287 } 288 return strcmp ($a,$b); 289} 290 291/** 292 * Creates a snippet extract 293 * 294 * @author Andreas Gohr <andi@splitbrain.org> 295 * @triggers FULLTEXT_SNIPPET_CREATE 296 */ 297function ft_snippet($id,$highlight){ 298 $text = rawWiki($id); 299 $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens 300 $evdata = array( 301 'id' => $id, 302 'text' => &$text, 303 'highlight' => &$highlight, 304 'snippet' => '', 305 ); 306 307 $evt = new Doku_Event('FULLTEXT_SNIPPET_CREATE',$evdata); 308 if ($evt->advise_before()) { 309 $match = array(); 310 $snippets = array(); 311 $utf8_offset = $offset = $end = 0; 312 $len = utf8_strlen($text); 313 314 // build a regexp from the phrases to highlight 315 $re1 = '('.join('|',array_map('ft_snippet_re_preprocess', array_map('preg_quote_cb',array_filter((array) $highlight)))).')'; 316 $re2 = "$re1.{0,75}(?!\\1)$re1"; 317 $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1"; 318 319 for ($cnt=4; $cnt--;) { 320 if (0) { 321 } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 322 } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 323 } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) { 324 } else { 325 break; 326 } 327 328 list($str,$idx) = $match[0]; 329 330 // convert $idx (a byte offset) into a utf8 character offset 331 $utf8_idx = utf8_strlen(substr($text,0,$idx)); 332 $utf8_len = utf8_strlen($str); 333 334 // establish context, 100 bytes surrounding the match string 335 // first look to see if we can go 100 either side, 336 // then drop to 50 adding any excess if the other side can't go to 50, 337 $pre = min($utf8_idx-$utf8_offset,100); 338 $post = min($len-$utf8_idx-$utf8_len,100); 339 340 if ($pre>50 && $post>50) { 341 $pre = $post = 50; 342 } else if ($pre>50) { 343 $pre = min($pre,100-$post); 344 } else if ($post>50) { 345 $post = min($post, 100-$pre); 346 } else { 347 // both are less than 50, means the context is the whole string 348 // make it so and break out of this loop - there is no need for the 349 // complex snippet calculations 350 $snippets = array($text); 351 break; 352 } 353 354 // establish context start and end points, try to append to previous 355 // context if possible 356 $start = $utf8_idx - $pre; 357 $append = ($start < $end) ? $end : false; // still the end of the previous context snippet 358 $end = $utf8_idx + $utf8_len + $post; // now set it to the end of this context 359 360 if ($append) { 361 $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append); 362 } else { 363 $snippets[] = utf8_substr($text,$start,$end-$start); 364 } 365 366 // set $offset for next match attempt 367 // substract strlen to avoid splitting a potential search success, 368 // this is an approximation as the search pattern may match strings 369 // of varying length and it will fail if the context snippet 370 // boundary breaks a matching string longer than the current match 371 $utf8_offset = $utf8_idx + $post; 372 $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$post)); 373 $offset = utf8_correctIdx($text,$offset); 374 } 375 376 $m = "\1"; 377 $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets); 378 $snippet = preg_replace('/'.$m.'([^'.$m.']*?)'.$m.'/iu','<strong class="search_hit">$1</strong>',hsc(join('... ',$snippets))); 379 380 $evdata['snippet'] = $snippet; 381 } 382 $evt->advise_after(); 383 unset($evt); 384 385 return $evdata['snippet']; 386} 387 388/** 389 * Wraps a search term in regex boundary checks. 390 */ 391function ft_snippet_re_preprocess($term) { 392 // do not process asian terms where word boundaries are not explicit 393 if(preg_match('/'.IDX_ASIAN.'/u',$term)){ 394 return $term; 395 } 396 397 if (UTF8_PROPERTYSUPPORT) { 398 // unicode word boundaries 399 // see http://stackoverflow.com/a/2449017/172068 400 $BL = '(?<!\pL)'; 401 $BR = '(?!\pL)'; 402 } else { 403 // not as correct as above, but at least won't break 404 $BL = '\b'; 405 $BR = '\b'; 406 } 407 408 409 if(substr($term,0,2) == '\\*'){ 410 $term = substr($term,2); 411 }else{ 412 $term = $BL.$term; 413 } 414 415 if(substr($term,-2,2) == '\\*'){ 416 $term = substr($term,0,-2); 417 }else{ 418 $term = $term.$BR; 419 } 420 421 if($term == $BL || $term == $BR || $term == $BL.$BR) $term = ''; 422 return $term; 423} 424 425/** 426 * Combine found documents and sum up their scores 427 * 428 * This function is used to combine searched words with a logical 429 * AND. Only documents available in all arrays are returned. 430 * 431 * based upon PEAR's PHP_Compat function for array_intersect_key() 432 * 433 * @param array $args An array of page arrays 434 */ 435function ft_resultCombine($args){ 436 $array_count = count($args); 437 if($array_count == 1){ 438 return $args[0]; 439 } 440 441 $result = array(); 442 if ($array_count > 1) { 443 foreach ($args[0] as $key => $value) { 444 $result[$key] = $value; 445 for ($i = 1; $i !== $array_count; $i++) { 446 if (!isset($args[$i][$key])) { 447 unset($result[$key]); 448 break; 449 } 450 $result[$key] += $args[$i][$key]; 451 } 452 } 453 } 454 return $result; 455} 456 457/** 458 * Unites found documents and sum up their scores 459 * 460 * based upon ft_resultCombine() function 461 * 462 * @param array $args An array of page arrays 463 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 464 */ 465function ft_resultUnite($args) { 466 $array_count = count($args); 467 if ($array_count === 1) { 468 return $args[0]; 469 } 470 471 $result = $args[0]; 472 for ($i = 1; $i !== $array_count; $i++) { 473 foreach (array_keys($args[$i]) as $id) { 474 $result[$id] += $args[$i][$id]; 475 } 476 } 477 return $result; 478} 479 480/** 481 * Computes the difference of documents using page id for comparison 482 * 483 * nearly identical to PHP5's array_diff_key() 484 * 485 * @param array $args An array of page arrays 486 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 487 */ 488function ft_resultComplement($args) { 489 $array_count = count($args); 490 if ($array_count === 1) { 491 return $args[0]; 492 } 493 494 $result = $args[0]; 495 foreach (array_keys($result) as $id) { 496 for ($i = 1; $i !== $array_count; $i++) { 497 if (isset($args[$i][$id])) unset($result[$id]); 498 } 499 } 500 return $result; 501} 502 503/** 504 * Parses a search query and builds an array of search formulas 505 * 506 * @author Andreas Gohr <andi@splitbrain.org> 507 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 508 */ 509function ft_queryParser($Indexer, $query){ 510 /** 511 * parse a search query and transform it into intermediate representation 512 * 513 * in a search query, you can use the following expressions: 514 * 515 * words: 516 * include 517 * -exclude 518 * phrases: 519 * "phrase to be included" 520 * -"phrase you want to exclude" 521 * namespaces: 522 * @include:namespace (or ns:include:namespace) 523 * ^exclude:namespace (or -ns:exclude:namespace) 524 * groups: 525 * () 526 * -() 527 * operators: 528 * and ('and' is the default operator: you can always omit this) 529 * or (or pipe symbol '|', lower precedence than 'and') 530 * 531 * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain 532 * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'". 533 * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ] 534 * as long as you don't mind hit counts. 535 * 536 * intermediate representation consists of the following parts: 537 * 538 * ( ) - group 539 * AND - logical and 540 * OR - logical or 541 * NOT - logical not 542 * W+:, W-:, W_: - word (underscore: no need to highlight) 543 * P+:, P-: - phrase (minus sign: logically in NOT group) 544 * N+:, N-: - namespace 545 */ 546 $parsed_query = ''; 547 $parens_level = 0; 548 $terms = preg_split('/(-?".*?")/u', utf8_strtolower($query), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 549 550 foreach ($terms as $term) { 551 $parsed = ''; 552 if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) { 553 // phrase-include and phrase-exclude 554 $not = $matches[1] ? 'NOT' : ''; 555 $parsed = $not.ft_termParser($Indexer, $matches[2], false, true); 556 } else { 557 // fix incomplete phrase 558 $term = str_replace('"', ' ', $term); 559 560 // fix parentheses 561 $term = str_replace(')' , ' ) ', $term); 562 $term = str_replace('(' , ' ( ', $term); 563 $term = str_replace('- (', ' -(', $term); 564 565 // treat pipe symbols as 'OR' operators 566 $term = str_replace('|', ' or ', $term); 567 568 // treat ideographic spaces (U+3000) as search term separators 569 // FIXME: some more separators? 570 $term = preg_replace('/[ \x{3000}]+/u', ' ', $term); 571 $term = trim($term); 572 if ($term === '') continue; 573 574 $tokens = explode(' ', $term); 575 foreach ($tokens as $token) { 576 if ($token === '(') { 577 // parenthesis-include-open 578 $parsed .= '('; 579 ++$parens_level; 580 } elseif ($token === '-(') { 581 // parenthesis-exclude-open 582 $parsed .= 'NOT('; 583 ++$parens_level; 584 } elseif ($token === ')') { 585 // parenthesis-any-close 586 if ($parens_level === 0) continue; 587 $parsed .= ')'; 588 $parens_level--; 589 } elseif ($token === 'and') { 590 // logical-and (do nothing) 591 } elseif ($token === 'or') { 592 // logical-or 593 $parsed .= 'OR'; 594 } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) { 595 // namespace-exclude 596 $parsed .= 'NOT(N+:'.$matches[1].')'; 597 } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) { 598 // namespace-include 599 $parsed .= '(N+:'.$matches[1].')'; 600 } elseif (preg_match('/^-(.+)$/', $token, $matches)) { 601 // word-exclude 602 $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')'; 603 } else { 604 // word-include 605 $parsed .= ft_termParser($Indexer, $token); 606 } 607 } 608 } 609 $parsed_query .= $parsed; 610 } 611 612 // cleanup (very sensitive) 613 $parsed_query .= str_repeat(')', $parens_level); 614 do { 615 $parsed_query_old = $parsed_query; 616 $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query); 617 } while ($parsed_query !== $parsed_query_old); 618 $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query); 619 $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query); 620 $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query); 621 $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query); 622 $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query); 623 624 // adjustment: make highlightings right 625 $parens_level = 0; 626 $notgrp_levels = array(); 627 $parsed_query_new = ''; 628 $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 629 foreach ($tokens as $token) { 630 if ($token === 'NOT(') { 631 $notgrp_levels[] = ++$parens_level; 632 } elseif ($token === '(') { 633 ++$parens_level; 634 } elseif ($token === ')') { 635 if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels); 636 } elseif (count($notgrp_levels) % 2 === 1) { 637 // turn highlight-flag off if terms are logically in "NOT" group 638 $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token); 639 } 640 $parsed_query_new .= $token; 641 } 642 $parsed_query = $parsed_query_new; 643 644 /** 645 * convert infix notation string into postfix (Reverse Polish notation) array 646 * by Shunting-yard algorithm 647 * 648 * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation 649 * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm 650 */ 651 $parsed_ary = array(); 652 $ope_stack = array(); 653 $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5); 654 $ope_regex = '/([()]|OR|AND|NOT)/u'; 655 656 $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 657 foreach ($tokens as $token) { 658 if (preg_match($ope_regex, $token)) { 659 // operator 660 $last_ope = end($ope_stack); 661 while ($ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') { 662 $parsed_ary[] = array_pop($ope_stack); 663 $last_ope = end($ope_stack); 664 } 665 if ($token == ')') { 666 array_pop($ope_stack); // this array_pop always deletes '(' 667 } else { 668 $ope_stack[] = $token; 669 } 670 } else { 671 // operand 672 $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token); 673 $parsed_ary[] = $token_decoded; 674 } 675 } 676 $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack))); 677 678 // cleanup: each double "NOT" in RPN array actually does nothing 679 $parsed_ary_count = count($parsed_ary); 680 for ($i = 1; $i < $parsed_ary_count; ++$i) { 681 if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') { 682 unset($parsed_ary[$i], $parsed_ary[$i - 1]); 683 } 684 } 685 $parsed_ary = array_values($parsed_ary); 686 687 // build return value 688 $q = array(); 689 $q['query'] = $query; 690 $q['parsed_str'] = $parsed_query; 691 $q['parsed_ary'] = $parsed_ary; 692 693 foreach ($q['parsed_ary'] as $token) { 694 if ($token[2] !== ':') continue; 695 $body = substr($token, 3); 696 697 switch (substr($token, 0, 3)) { 698 case 'N+:': 699 $q['ns'][] = $body; // for backward compatibility 700 break; 701 case 'N-:': 702 $q['notns'][] = $body; // for backward compatibility 703 break; 704 case 'W_:': 705 $q['words'][] = $body; 706 break; 707 case 'W-:': 708 $q['words'][] = $body; 709 $q['not'][] = $body; // for backward compatibility 710 break; 711 case 'W+:': 712 $q['words'][] = $body; 713 $q['highlight'][] = $body; 714 $q['and'][] = $body; // for backward compatibility 715 break; 716 case 'P-:': 717 $q['phrases'][] = $body; 718 break; 719 case 'P+:': 720 $q['phrases'][] = $body; 721 $q['highlight'][] = $body; 722 break; 723 } 724 } 725 foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) { 726 $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key])); 727 } 728 729 return $q; 730} 731 732/** 733 * Transforms given search term into intermediate representation 734 * 735 * This function is used in ft_queryParser() and not for general purpose use. 736 * 737 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 738 */ 739function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) { 740 $parsed = ''; 741 if ($consider_asian) { 742 // successive asian characters need to be searched as a phrase 743 $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 744 foreach ($words as $word) { 745 $phrase_mode = $phrase_mode ? true : preg_match('/'.IDX_ASIAN.'/u', $word); 746 $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode); 747 } 748 } else { 749 $term_noparen = str_replace(array('(', ')'), ' ', $term); 750 $words = $Indexer->tokenizer($term_noparen, true); 751 752 // W_: no need to highlight 753 if (empty($words)) { 754 $parsed = '()'; // important: do not remove 755 } elseif ($words[0] === $term) { 756 $parsed = '(W+:'.$words[0].')'; 757 } elseif ($phrase_mode) { 758 $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term); 759 $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))'; 760 } else { 761 $parsed = '((W+:'.implode(')(W+:', $words).'))'; 762 } 763 } 764 return $parsed; 765} 766 767//Setup VIM: ex: et ts=4 : 768