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