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