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