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