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