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