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