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