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