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