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 * 129 * @param string $id The id for which links shall be returned 130 * @param bool $ignore_perms Ignore the fact that pages are hidden or read-protected 131 * @return array The pages that contain links to the given page 132 */ 133function ft_backlinks($id, $ignore_perms = false){ 134 $result = idx_get_indexer()->lookupKey('relation_references', $id); 135 136 if(!count($result)) return $result; 137 138 // check ACL permissions 139 foreach(array_keys($result) as $idx){ 140 if(($ignore_perms !== true && ( 141 isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 142 )) || !page_exists($result[$idx], '', false)){ 143 unset($result[$idx]); 144 } 145 } 146 147 sort($result); 148 return $result; 149} 150 151/** 152 * Returns the pages that use a given media file 153 * 154 * Uses the relation media metadata property and the metadata index. 155 * 156 * Note that before 2013-07-31 the second parameter was the maximum number of results and 157 * permissions were ignored. That's why the parameter is now checked to be explicitely set 158 * to true (with type bool) in order to be compatible with older uses of the function. 159 * 160 * @param string $id The media id to look for 161 * @param bool $ignore_perms Ignore hidden pages and acls (optional, default: false) 162 * @return array A list of pages that use the given media file 163 */ 164function ft_mediause($id, $ignore_perms = false){ 165 $result = idx_get_indexer()->lookupKey('relation_media', $id); 166 167 if(!count($result)) return $result; 168 169 // check ACL permissions 170 foreach(array_keys($result) as $idx){ 171 if(($ignore_perms !== true && ( 172 isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ 173 )) || !page_exists($result[$idx], '', false)){ 174 unset($result[$idx]); 175 } 176 } 177 178 sort($result); 179 return $result; 180} 181 182 183 184/** 185 * Quicksearch for pagenames 186 * 187 * By default it only matches the pagename and ignores the 188 * namespace. This can be changed with the second parameter. 189 * The third parameter allows to search in titles as well. 190 * 191 * The function always returns titles as well 192 * 193 * @triggers SEARCH_QUERY_PAGELOOKUP 194 * @author Andreas Gohr <andi@splitbrain.org> 195 * @author Adrian Lang <lang@cosmocode.de> 196 */ 197function ft_pageLookup($id, $in_ns=false, $in_title=false){ 198 $data = compact('id', 'in_ns', 'in_title'); 199 $data['has_titles'] = true; // for plugin backward compatibility check 200 return trigger_event('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup'); 201} 202 203function _ft_pageLookup(&$data){ 204 // split out original parameters 205 $id = $data['id']; 206 if (preg_match('/(?:^| )@(\w+)/', $id, $matches)) { 207 $ns = cleanID($matches[1]) . ':'; 208 $id = str_replace($matches[0], '', $id); 209 } 210 211 $in_ns = $data['in_ns']; 212 $in_title = $data['in_title']; 213 $cleaned = cleanID($id); 214 215 $Indexer = idx_get_indexer(); 216 $page_idx = $Indexer->getPages(); 217 218 $pages = array(); 219 if ($id !== '' && $cleaned !== '') { 220 foreach ($page_idx as $p_id) { 221 if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) { 222 if (!isset($pages[$p_id])) 223 $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 224 } 225 } 226 if ($in_title) { 227 foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) { 228 if (!isset($pages[$p_id])) 229 $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER); 230 } 231 } 232 } 233 234 if (isset($ns)) { 235 foreach (array_keys($pages) as $p_id) { 236 if (strpos($p_id, $ns) !== 0) { 237 unset($pages[$p_id]); 238 } 239 } 240 } 241 242 // discard hidden pages 243 // discard nonexistent pages 244 // check ACL permissions 245 foreach(array_keys($pages) as $idx){ 246 if(!isVisiblePage($idx) || !page_exists($idx) || 247 auth_quickaclcheck($idx) < AUTH_READ) { 248 unset($pages[$idx]); 249 } 250 } 251 252 uksort($pages,'ft_pagesorter'); 253 return $pages; 254} 255 256/** 257 * Tiny helper function for comparing the searched title with the title 258 * from the search index. This function is a wrapper around stripos with 259 * adapted argument order and return value. 260 */ 261function _ft_pageLookupTitleCompare($search, $title) { 262 return stripos($title, $search) !== false; 263} 264 265/** 266 * Sort pages based on their namespace level first, then on their string 267 * values. This makes higher hierarchy pages rank higher than lower hierarchy 268 * pages. 269 */ 270function ft_pagesorter($a, $b){ 271 $ac = count(explode(':',$a)); 272 $bc = count(explode(':',$b)); 273 if($ac < $bc){ 274 return -1; 275 }elseif($ac > $bc){ 276 return 1; 277 } 278 return strcmp ($a,$b); 279} 280 281/** 282 * Creates a snippet extract 283 * 284 * @author Andreas Gohr <andi@splitbrain.org> 285 * @triggers FULLTEXT_SNIPPET_CREATE 286 */ 287function ft_snippet($id,$highlight){ 288 $text = rawWiki($id); 289 $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens 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 (UTF8_PROPERTYSUPPORT) { 388 // unicode word boundaries 389 // see http://stackoverflow.com/a/2449017/172068 390 $BL = '(?<!\pL)'; 391 $BR = '(?!\pL)'; 392 } else { 393 // not as correct as above, but at least won't break 394 $BL = '\b'; 395 $BR = '\b'; 396 } 397 398 399 if(substr($term,0,2) == '\\*'){ 400 $term = substr($term,2); 401 }else{ 402 $term = $BL.$term; 403 } 404 405 if(substr($term,-2,2) == '\\*'){ 406 $term = substr($term,0,-2); 407 }else{ 408 $term = $term.$BR; 409 } 410 411 if($term == $BL || $term == $BR || $term == $BL.$BR) $term = ''; 412 return $term; 413} 414 415/** 416 * Combine found documents and sum up their scores 417 * 418 * This function is used to combine searched words with a logical 419 * AND. Only documents available in all arrays are returned. 420 * 421 * based upon PEAR's PHP_Compat function for array_intersect_key() 422 * 423 * @param array $args An array of page arrays 424 */ 425function ft_resultCombine($args){ 426 $array_count = count($args); 427 if($array_count == 1){ 428 return $args[0]; 429 } 430 431 $result = array(); 432 if ($array_count > 1) { 433 foreach ($args[0] as $key => $value) { 434 $result[$key] = $value; 435 for ($i = 1; $i !== $array_count; $i++) { 436 if (!isset($args[$i][$key])) { 437 unset($result[$key]); 438 break; 439 } 440 $result[$key] += $args[$i][$key]; 441 } 442 } 443 } 444 return $result; 445} 446 447/** 448 * Unites found documents and sum up their scores 449 * 450 * based upon ft_resultCombine() function 451 * 452 * @param array $args An array of page arrays 453 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 454 */ 455function ft_resultUnite($args) { 456 $array_count = count($args); 457 if ($array_count === 1) { 458 return $args[0]; 459 } 460 461 $result = $args[0]; 462 for ($i = 1; $i !== $array_count; $i++) { 463 foreach (array_keys($args[$i]) as $id) { 464 $result[$id] += $args[$i][$id]; 465 } 466 } 467 return $result; 468} 469 470/** 471 * Computes the difference of documents using page id for comparison 472 * 473 * nearly identical to PHP5's array_diff_key() 474 * 475 * @param array $args An array of page arrays 476 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 477 */ 478function ft_resultComplement($args) { 479 $array_count = count($args); 480 if ($array_count === 1) { 481 return $args[0]; 482 } 483 484 $result = $args[0]; 485 foreach (array_keys($result) as $id) { 486 for ($i = 1; $i !== $array_count; $i++) { 487 if (isset($args[$i][$id])) unset($result[$id]); 488 } 489 } 490 return $result; 491} 492 493/** 494 * Parses a search query and builds an array of search formulas 495 * 496 * @author Andreas Gohr <andi@splitbrain.org> 497 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 498 */ 499function ft_queryParser($Indexer, $query){ 500 /** 501 * parse a search query and transform it into intermediate representation 502 * 503 * in a search query, you can use the following expressions: 504 * 505 * words: 506 * include 507 * -exclude 508 * phrases: 509 * "phrase to be included" 510 * -"phrase you want to exclude" 511 * namespaces: 512 * @include:namespace (or ns:include:namespace) 513 * ^exclude:namespace (or -ns:exclude:namespace) 514 * groups: 515 * () 516 * -() 517 * operators: 518 * and ('and' is the default operator: you can always omit this) 519 * or (or pipe symbol '|', lower precedence than 'and') 520 * 521 * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain 522 * a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'". 523 * this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ] 524 * as long as you don't mind hit counts. 525 * 526 * intermediate representation consists of the following parts: 527 * 528 * ( ) - group 529 * AND - logical and 530 * OR - logical or 531 * NOT - logical not 532 * W+:, W-:, W_: - word (underscore: no need to highlight) 533 * P+:, P-: - phrase (minus sign: logically in NOT group) 534 * N+:, N-: - namespace 535 */ 536 $parsed_query = ''; 537 $parens_level = 0; 538 $terms = preg_split('/(-?".*?")/u', utf8_strtolower($query), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 539 540 foreach ($terms as $term) { 541 $parsed = ''; 542 if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) { 543 // phrase-include and phrase-exclude 544 $not = $matches[1] ? 'NOT' : ''; 545 $parsed = $not.ft_termParser($Indexer, $matches[2], false, true); 546 } else { 547 // fix incomplete phrase 548 $term = str_replace('"', ' ', $term); 549 550 // fix parentheses 551 $term = str_replace(')' , ' ) ', $term); 552 $term = str_replace('(' , ' ( ', $term); 553 $term = str_replace('- (', ' -(', $term); 554 555 // treat pipe symbols as 'OR' operators 556 $term = str_replace('|', ' or ', $term); 557 558 // treat ideographic spaces (U+3000) as search term separators 559 // FIXME: some more separators? 560 $term = preg_replace('/[ \x{3000}]+/u', ' ', $term); 561 $term = trim($term); 562 if ($term === '') continue; 563 564 $tokens = explode(' ', $term); 565 foreach ($tokens as $token) { 566 if ($token === '(') { 567 // parenthesis-include-open 568 $parsed .= '('; 569 ++$parens_level; 570 } elseif ($token === '-(') { 571 // parenthesis-exclude-open 572 $parsed .= 'NOT('; 573 ++$parens_level; 574 } elseif ($token === ')') { 575 // parenthesis-any-close 576 if ($parens_level === 0) continue; 577 $parsed .= ')'; 578 $parens_level--; 579 } elseif ($token === 'and') { 580 // logical-and (do nothing) 581 } elseif ($token === 'or') { 582 // logical-or 583 $parsed .= 'OR'; 584 } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) { 585 // namespace-exclude 586 $parsed .= 'NOT(N+:'.$matches[1].')'; 587 } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) { 588 // namespace-include 589 $parsed .= '(N+:'.$matches[1].')'; 590 } elseif (preg_match('/^-(.+)$/', $token, $matches)) { 591 // word-exclude 592 $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')'; 593 } else { 594 // word-include 595 $parsed .= ft_termParser($Indexer, $token); 596 } 597 } 598 } 599 $parsed_query .= $parsed; 600 } 601 602 // cleanup (very sensitive) 603 $parsed_query .= str_repeat(')', $parens_level); 604 do { 605 $parsed_query_old = $parsed_query; 606 $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query); 607 } while ($parsed_query !== $parsed_query_old); 608 $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')' , $parsed_query); 609 $parsed_query = preg_replace('/(OR)+/u' , 'OR' , $parsed_query); 610 $parsed_query = preg_replace('/\(OR/u' , '(' , $parsed_query); 611 $parsed_query = preg_replace('/^OR|OR$/u' , '' , $parsed_query); 612 $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query); 613 614 // adjustment: make highlightings right 615 $parens_level = 0; 616 $notgrp_levels = array(); 617 $parsed_query_new = ''; 618 $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 619 foreach ($tokens as $token) { 620 if ($token === 'NOT(') { 621 $notgrp_levels[] = ++$parens_level; 622 } elseif ($token === '(') { 623 ++$parens_level; 624 } elseif ($token === ')') { 625 if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels); 626 } elseif (count($notgrp_levels) % 2 === 1) { 627 // turn highlight-flag off if terms are logically in "NOT" group 628 $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token); 629 } 630 $parsed_query_new .= $token; 631 } 632 $parsed_query = $parsed_query_new; 633 634 /** 635 * convert infix notation string into postfix (Reverse Polish notation) array 636 * by Shunting-yard algorithm 637 * 638 * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation 639 * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm 640 */ 641 $parsed_ary = array(); 642 $ope_stack = array(); 643 $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5); 644 $ope_regex = '/([()]|OR|AND|NOT)/u'; 645 646 $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 647 foreach ($tokens as $token) { 648 if (preg_match($ope_regex, $token)) { 649 // operator 650 $last_ope = end($ope_stack); 651 while ($ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') { 652 $parsed_ary[] = array_pop($ope_stack); 653 $last_ope = end($ope_stack); 654 } 655 if ($token == ')') { 656 array_pop($ope_stack); // this array_pop always deletes '(' 657 } else { 658 $ope_stack[] = $token; 659 } 660 } else { 661 // operand 662 $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token); 663 $parsed_ary[] = $token_decoded; 664 } 665 } 666 $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack))); 667 668 // cleanup: each double "NOT" in RPN array actually does nothing 669 $parsed_ary_count = count($parsed_ary); 670 for ($i = 1; $i < $parsed_ary_count; ++$i) { 671 if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') { 672 unset($parsed_ary[$i], $parsed_ary[$i - 1]); 673 } 674 } 675 $parsed_ary = array_values($parsed_ary); 676 677 // build return value 678 $q = array(); 679 $q['query'] = $query; 680 $q['parsed_str'] = $parsed_query; 681 $q['parsed_ary'] = $parsed_ary; 682 683 foreach ($q['parsed_ary'] as $token) { 684 if ($token[2] !== ':') continue; 685 $body = substr($token, 3); 686 687 switch (substr($token, 0, 3)) { 688 case 'N+:': 689 $q['ns'][] = $body; // for backward compatibility 690 break; 691 case 'N-:': 692 $q['notns'][] = $body; // for backward compatibility 693 break; 694 case 'W_:': 695 $q['words'][] = $body; 696 break; 697 case 'W-:': 698 $q['words'][] = $body; 699 $q['not'][] = $body; // for backward compatibility 700 break; 701 case 'W+:': 702 $q['words'][] = $body; 703 $q['highlight'][] = $body; 704 $q['and'][] = $body; // for backward compatibility 705 break; 706 case 'P-:': 707 $q['phrases'][] = $body; 708 break; 709 case 'P+:': 710 $q['phrases'][] = $body; 711 $q['highlight'][] = $body; 712 break; 713 } 714 } 715 foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) { 716 $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key])); 717 } 718 719 return $q; 720} 721 722/** 723 * Transforms given search term into intermediate representation 724 * 725 * This function is used in ft_queryParser() and not for general purpose use. 726 * 727 * @author Kazutaka Miyasaka <kazmiya@gmail.com> 728 */ 729function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) { 730 $parsed = ''; 731 if ($consider_asian) { 732 // successive asian characters need to be searched as a phrase 733 $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); 734 foreach ($words as $word) { 735 $phrase_mode = $phrase_mode ? true : preg_match('/'.IDX_ASIAN.'/u', $word); 736 $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode); 737 } 738 } else { 739 $term_noparen = str_replace(array('(', ')'), ' ', $term); 740 $words = $Indexer->tokenizer($term_noparen, true); 741 742 // W_: no need to highlight 743 if (empty($words)) { 744 $parsed = '()'; // important: do not remove 745 } elseif ($words[0] === $term) { 746 $parsed = '(W+:'.$words[0].')'; 747 } elseif ($phrase_mode) { 748 $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term); 749 $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))'; 750 } else { 751 $parsed = '((W+:'.implode(')(W+:', $words).'))'; 752 } 753 } 754 return $parsed; 755} 756 757//Setup VIM: ex: et ts=4 : 758