xref: /dokuwiki/inc/Search/FulltextSearch.php (revision 0a3e25f4dc31fa96366f0551ea8f5c1343d02425)
1<?php
2namespace dokuwiki\Search;
3
4use dokuwiki\Extension\Event;
5use dokuwiki\Search\Indexer;
6use dokuwiki\Utf8;
7
8/**
9 * Class DokuWiki Fulltext Search
10 *
11 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
12 * @author     Andreas Gohr <andi@splitbrain.org>
13 */
14class FulltextSearch
15{
16    /**
17     *  Fulltext Search constructor. prevent direct object creation
18     */
19    protected function __construct() {}
20
21    /**
22     * The fulltext search
23     *
24     * Returns a list of matching documents for the given query
25     *
26     * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event()
27     *
28     * @param string     $query
29     * @param array      $highlight
30     * @param string     $sort
31     * @param int|string $after  only show results with mtime after this date,
32     *                           accepts timestap or strtotime arguments
33     * @param int|string $before only show results with mtime before this date,
34     *                           accepts timestap or strtotime arguments
35     *
36     * @return array
37     */
38    public static function pageSearch($query, &$highlight, $sort = null, $after = null, $before = null)
39    {
40        if ($sort === null) {
41            $sort = 'hits';
42        }
43        $data = [
44            'query' => $query,
45            'sort' => $sort,
46            'after' => $after,
47            'before' => $before
48        ];
49        $data['highlight'] =& $highlight;
50        $action = static::class.'::callback_pageSearch';
51        return Event::createAndTrigger('SEARCH_QUERY_FULLPAGE', $data, $action);
52    }
53
54    /**
55     * Returns a list of matching documents for the given query
56     *
57     * @author Andreas Gohr <andi@splitbrain.org>
58     * @author Kazutaka Miyasaka <kazmiya@gmail.com>
59     *
60     * @param array $data event data
61     * @return array matching documents
62     */
63    public static function callback_pageSearch(&$data)
64    {
65        $Indexer = Indexer::getInstance();
66
67        // parse the given query
68        $q = static::queryParser($Indexer, $data['query']);
69        $data['highlight'] = $q['highlight'];
70
71        if (empty($q['parsed_ary'])) return array();
72
73        // lookup all words found in the query
74        $lookup = $Indexer->lookup($q['words']);
75
76        // get all pages in this dokuwiki site (!: includes nonexistent pages)
77        $pages_all = array();
78        foreach ($Indexer->getPages() as $id) {
79            $pages_all[$id] = 0; // base: 0 hit
80        }
81
82        // process the query
83        $stack = array();
84        foreach ($q['parsed_ary'] as $token) {
85            switch (substr($token, 0, 3)) {
86                case 'W+:':
87                case 'W-:':
88                case 'W_:': // word
89                    $word    = substr($token, 3);
90                    $stack[] = (array) $lookup[$word];
91                    break;
92                case 'P+:':
93                case 'P-:': // phrase
94                    $phrase = substr($token, 3);
95                    // since phrases are always parsed as ((W1)(W2)...(P)),
96                    // the end($stack) always points the pages that contain
97                    // all words in this phrase
98                    $pages  = end($stack);
99                    $pages_matched = array();
100                    foreach (array_keys($pages) as $id) {
101                        $evdata = array(
102                            'id' => $id,
103                            'phrase' => $phrase,
104                            'text' => rawWiki($id)
105                        );
106                        $evt = new Event('FULLTEXT_PHRASE_MATCH', $evdata);
107                        if ($evt->advise_before() && $evt->result !== true) {
108                            $text = Utf8\PhpString::strtolower($evdata['text']);
109                            if (strpos($text, $phrase) !== false) {
110                                $evt->result = true;
111                            }
112                        }
113                        $evt->advise_after();
114                        if ($evt->result === true) {
115                            $pages_matched[$id] = 0; // phrase: always 0 hit
116                        }
117                    }
118                    $stack[] = $pages_matched;
119                    break;
120                case 'N+:':
121                case 'N-:': // namespace
122                    $ns = cleanID(substr($token, 3)) . ':';
123                    $pages_matched = array();
124                    foreach (array_keys($pages_all) as $id) {
125                        if (strpos($id, $ns) === 0) {
126                            $pages_matched[$id] = 0; // namespace: always 0 hit
127                        }
128                    }
129                    $stack[] = $pages_matched;
130                    break;
131                case 'AND': // and operation
132                    list($pages1, $pages2) = array_splice($stack, -2);
133                    $stack[] = static::resultCombine(array($pages1, $pages2));
134                    break;
135                case 'OR':  // or operation
136                    list($pages1, $pages2) = array_splice($stack, -2);
137                    $stack[] = static::resultUnite(array($pages1, $pages2));
138                    break;
139                case 'NOT': // not operation (unary)
140                    $pages   = array_pop($stack);
141                    $stack[] = static::resultComplement(array($pages_all, $pages));
142                    break;
143            }
144        }
145        $docs = array_pop($stack);
146
147        if (empty($docs)) return array();
148
149        // check: settings, acls, existence
150        foreach (array_keys($docs) as $id) {
151            if (isHiddenPage($id)
152                || auth_quickaclcheck($id) < AUTH_READ
153                || !page_exists($id, '', false)
154            ) {
155                unset($docs[$id]);
156            }
157        }
158
159        $docs = static::filterResultsByTime($docs, $data['after'], $data['before']);
160
161        if ($data['sort'] === 'mtime') {
162            uksort($docs, static::class.'::pagemtimesorter');
163        } else {
164            // sort docs by count
165            arsort($docs);
166        }
167
168        return $docs;
169    }
170
171    /**
172     * Quicksearch for pagenames
173     *
174     * By default it only matches the pagename and ignores the
175     * namespace. This can be changed with the second parameter.
176     * The third parameter allows to search in titles as well.
177     *
178     * The function always returns titles as well
179     *
180     * @triggers SEARCH_QUERY_PAGELOOKUP
181     * @author   Andreas Gohr <andi@splitbrain.org>
182     * @author   Adrian Lang <lang@cosmocode.de>
183     *
184     * @param string     $id       page id
185     * @param bool       $in_ns    match against namespace as well?
186     * @param bool       $in_title search in title?
187     * @param int|string $after    only show results with mtime after this date,
188     *                             accepts timestap or strtotime arguments
189     * @param int|string $before   only show results with mtime before this date,
190     *                             accepts timestap or strtotime arguments
191     *
192     * @return string[]
193     */
194    public static function pageLookup($id, $in_ns=false, $in_title=false, $after = null, $before = null)
195    {
196        $data = [
197            'id' => $id,
198            'in_ns' => $in_ns,
199            'in_title' => $in_title,
200            'after' => $after,
201            'before' => $before
202        ];
203        $data['has_titles'] = true; // for plugin backward compatibility check
204        $action = static::class.'::callback_pageLookup';
205        return Event::createAndTrigger('SEARCH_QUERY_PAGELOOKUP', $data, $action);
206    }
207
208    /**
209     * Returns list of pages as array(pageid => First Heading)
210     *
211     * @param array &$data event data
212     * @return string[]
213     */
214    public static function callback_pageLookup(&$data)
215    {
216        $Indexer = Indexer::getInstance();
217
218        // split out original parameters
219        $id = $data['id'];
220        $parsedQuery = static::queryParser($Indexer, $id);
221        if (count($parsedQuery['ns']) > 0) {
222            $ns = cleanID($parsedQuery['ns'][0]) . ':';
223            $id = implode(' ', $parsedQuery['highlight']);
224        }
225
226        $in_ns    = $data['in_ns'];
227        $in_title = $data['in_title'];
228        $cleaned = cleanID($id);
229
230        $pages = array();
231        if ($id !== '' && $cleaned !== '') {
232            $page_idx = $Indexer->getPages();
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            }
240            if ($in_title) {
241                $func = static::class.'::pageLookupTitleCompare';
242                foreach ($Indexer->lookupKey('title', $id, $func) as $p_id) {
243                    if (!isset($pages[$p_id])) {
244                        $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
245                    }
246                }
247            }
248        }
249
250        if (isset($ns)) {
251            foreach (array_keys($pages) as $p_id) {
252                if (strpos($p_id, $ns) !== 0) {
253                    unset($pages[$p_id]);
254                }
255            }
256        }
257
258        // discard hidden pages
259        // discard nonexistent pages
260        // check ACL permissions
261        foreach (array_keys($pages) as $idx) {
262            if (!isVisiblePage($idx) || !page_exists($idx) || auth_quickaclcheck($idx) < AUTH_READ) {
263                unset($pages[$idx]);
264            }
265        }
266
267        $pages = static::filterResultsByTime($pages, $data['after'], $data['before']);
268
269        uksort($pages, static::class.'::pagesorter');
270        return $pages;
271    }
272
273    /**
274     * @param array      $results search results in the form pageid => value
275     * @param int|string $after   only returns results with mtime after this date,
276     *                            accepts timestap or strtotime arguments
277     * @param int|string $before  only returns results with mtime after this date,
278     *                            accepts timestap or strtotime arguments
279     *
280     * @return array
281     */
282    protected static function filterResultsByTime(array $results, $after, $before)
283    {
284        if ($after || $before) {
285            $after = is_int($after) ? $after : strtotime($after);
286            $before = is_int($before) ? $before : strtotime($before);
287
288            foreach ($results as $id => $value) {
289                $mTime = filemtime(wikiFN($id));
290                if ($after && $after > $mTime) {
291                    unset($results[$id]);
292                    continue;
293                }
294                if ($before && $before < $mTime) {
295                    unset($results[$id]);
296                }
297            }
298        }
299
300        return $results;
301    }
302
303    /**
304     * Tiny helper function for comparing the searched title with the title
305     * from the search index. This function is a wrapper around stripos with
306     * adapted argument order and return value.
307     *
308     * @param string $search searched title
309     * @param string $title  title from index
310     * @return bool
311     */
312    protected static function pageLookupTitleCompare($search, $title)
313    {
314        return stripos($title, $search) !== false;
315    }
316
317    /**
318     * Sort pages based on their namespace level first, then on their string
319     * values. This makes higher hierarchy pages rank higher than lower hierarchy
320     * pages.
321     *
322     * @param string $a
323     * @param string $b
324     * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b,
325     *             and 0 if they are equal.
326     */
327    protected static function pagesorter($a, $b)
328    {
329        $ac = count(explode(':',$a));
330        $bc = count(explode(':',$b));
331        if ($ac < $bc) {
332            return -1;
333        } elseif ($ac > $bc) {
334            return 1;
335        }
336        return strcmp ($a,$b);
337    }
338
339    /**
340     * Sort pages by their mtime, from newest to oldest
341     *
342     * @param string $a
343     * @param string $b
344     *
345     * @return int Returns < 0 if $a is newer than $b, > 0 if $b is newer than $a
346     *             and 0 if they are of the same age
347     */
348    protected static function pagemtimesorter($a, $b)
349    {
350        $mtimeA = filemtime(wikiFN($a));
351        $mtimeB = filemtime(wikiFN($b));
352        return $mtimeB - $mtimeA;
353    }
354
355    /**
356     * Creates a snippet extract
357     *
358     * @author Andreas Gohr <andi@splitbrain.org>
359     * @triggers FULLTEXT_SNIPPET_CREATE
360     *
361     * @param string $id page id
362     * @param array $highlight
363     * @return mixed
364     */
365    public static function snippet($id, $highlight)
366    {
367        $text = rawWiki($id);
368        $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens
369        $evdata = array(
370            'id'        => $id,
371            'text'      => &$text,
372            'highlight' => &$highlight,
373            'snippet'   => '',
374        );
375
376        $evt = new Event('FULLTEXT_SNIPPET_CREATE', $evdata);
377        if ($evt->advise_before()) {
378            $match = array();
379            $snippets = array();
380            $utf8_offset = $offset = $end = 0;
381            $len = Utf8\PhpString::strlen($text);
382
383            // build a regexp from the phrases to highlight
384            $re1 = '(' .
385                join(
386                    '|',
387                    array_map(
388                        static::class.'::snippet_re_preprocess',
389                        array_map(
390                            'preg_quote_cb',
391                            array_filter((array) $highlight)
392                        )
393                    )
394                ) .
395                ')';
396            $re2 = "$re1.{0,75}(?!\\1)$re1";
397            $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
398
399            for ($cnt=4; $cnt--;) {
400                if (0) {
401                } elseif (preg_match('/'.$re3.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
402                } elseif (preg_match('/'.$re2.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
403                } elseif (preg_match('/'.$re1.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
404                } else {
405                    break;
406                }
407
408                list($str, $idx) = $match[0];
409
410                // convert $idx (a byte offset) into a utf8 character offset
411                $utf8_idx = Utf8\PhpString::strlen(substr($text, 0, $idx));
412                $utf8_len = Utf8\PhpString::strlen($str);
413
414                // establish context, 100 bytes surrounding the match string
415                // first look to see if we can go 100 either side,
416                // then drop to 50 adding any excess if the other side can't go to 50,
417                $pre = min($utf8_idx - $utf8_offset, 100);
418                $post = min($len - $utf8_idx - $utf8_len, 100);
419
420                if ($pre > 50 && $post > 50) {
421                    $pre = $post = 50;
422                } elseif ($pre > 50) {
423                    $pre = min($pre, 100 - $post);
424                } elseif ($post > 50) {
425                    $post = min($post, 100 - $pre);
426                } elseif ($offset == 0) {
427                    // both are less than 50, means the context is the whole string
428                    // make it so and break out of this loop - there is no need for the
429                    // complex snippet calculations
430                    $snippets = array($text);
431                    break;
432                }
433
434                // establish context start and end points, try to append to previous
435                // context if possible
436                $start = $utf8_idx - $pre;
437                $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
438                $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
439
440                if ($append) {
441                    $snippets[count($snippets)-1] .= Utf8\PhpString::substr($text, $append, $end-$append);
442                } else {
443                    $snippets[] = Utf8\PhpString::substr($text, $start, $end-$start);
444                }
445
446                // set $offset for next match attempt
447                // continue matching after the current match
448                // if the current match is not the longest possible match starting at the current offset
449                // this prevents further matching of this snippet but for possible matches of length
450                // smaller than match length + context (at least 50 characters) this match is part of the context
451                $utf8_offset = $utf8_idx + $utf8_len;
452                $offset = $idx + strlen(Utf8\PhpString::substr($text, $utf8_idx, $utf8_len));
453                $offset = Utf8\Clean::correctIdx($text, $offset);
454            }
455
456            $m = "\1";
457            $snippets = preg_replace('/'.$re1.'/iu', $m.'$1'.$m, $snippets);
458            $snippet = preg_replace(
459                '/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
460                '<strong class="search_hit">$1</strong>',
461                hsc(join('... ', $snippets))
462            );
463
464            $evdata['snippet'] = $snippet;
465        }
466        $evt->advise_after();
467        unset($evt);
468
469        return $evdata['snippet'];
470    }
471
472    /**
473     * Wraps a search term in regex boundary checks.
474     *
475     * @param string $term
476     * @return string
477     */
478    public static function snippet_re_preprocess($term)
479    {
480        // do not process asian terms where word boundaries are not explicit
481        if (Utf8\Asian::isAsianWords($term)) return $term;
482
483        if (UTF8_PROPERTYSUPPORT) {
484            // unicode word boundaries
485            // see http://stackoverflow.com/a/2449017/172068
486            $BL = '(?<!\pL)';
487            $BR = '(?!\pL)';
488        } else {
489            // not as correct as above, but at least won't break
490            $BL = '\b';
491            $BR = '\b';
492        }
493
494        if (substr($term, 0, 2) == '\\*') {
495            $term = substr($term, 2);
496        } else {
497            $term = $BL.$term;
498        }
499
500        if (substr($term, -2, 2) == '\\*') {
501            $term = substr($term, 0, -2);
502        } else {
503            $term = $term.$BR;
504        }
505
506        if ($term == $BL || $term == $BR || $term == $BL.$BR) {
507            $term = '';
508        }
509        return $term;
510    }
511
512    /**
513     * Combine found documents and sum up their scores
514     *
515     * This function is used to combine searched words with a logical
516     * AND. Only documents available in all arrays are returned.
517     *
518     * based upon PEAR's PHP_Compat function for array_intersect_key()
519     *
520     * @param array $args An array of page arrays
521     * @return array
522     */
523    protected static function resultCombine($args)
524    {
525        $array_count = count($args);
526        if ($array_count == 1) {
527            return $args[0];
528        }
529
530        $result = array();
531        if ($array_count > 1) {
532            foreach ($args[0] as $key => $value) {
533                $result[$key] = $value;
534                for ($i = 1; $i !== $array_count; $i++) {
535                    if (!isset($args[$i][$key])) {
536                        unset($result[$key]);
537                        break;
538                    }
539                    $result[$key] += $args[$i][$key];
540                }
541            }
542        }
543        return $result;
544    }
545
546    /**
547     * Unites found documents and sum up their scores
548     * based upon resultCombine() method
549     *
550     * @param array $args An array of page arrays
551     * @return array
552     *
553     * @author Kazutaka Miyasaka <kazmiya@gmail.com>
554     */
555    protected static function resultUnite($args)
556    {
557        $array_count = count($args);
558        if ($array_count === 1) {
559            return $args[0];
560        }
561
562        $result = $args[0];
563        for ($i = 1; $i !== $array_count; $i++) {
564            foreach (array_keys($args[$i]) as $id) {
565                $result[$id] += $args[$i][$id];
566            }
567        }
568        return $result;
569    }
570
571    /**
572     * Computes the difference of documents using page id for comparison
573     * nearly identical to PHP5's array_diff_key()
574     *
575     * @param array $args An array of page arrays
576     * @return array
577     *
578     * @author Kazutaka Miyasaka <kazmiya@gmail.com>
579     */
580    protected static function resultComplement($args)
581    {
582        $array_count = count($args);
583        if ($array_count === 1) {
584            return $args[0];
585        }
586
587        $result = $args[0];
588        foreach (array_keys($result) as $id) {
589            for ($i = 1; $i !== $array_count; $i++) {
590                if (isset($args[$i][$id])) unset($result[$id]);
591            }
592        }
593        return $result;
594    }
595
596    /**
597     * Parses a search query and builds an array of search formulas
598     *
599     * @author Andreas Gohr <andi@splitbrain.org>
600     * @author Kazutaka Miyasaka <kazmiya@gmail.com>
601     *
602     * @param Indexer $Indexer
603     * @param string $query search query
604     * @return array of search formulas
605     */
606    public static function queryParser($Indexer, $query)
607    {
608        /**
609         * parse a search query and transform it into intermediate representation
610         *
611         * in a search query, you can use the following expressions:
612         *
613         *   words:
614         *     include
615         *     -exclude
616         *   phrases:
617         *     "phrase to be included"
618         *     -"phrase you want to exclude"
619         *   namespaces:
620         *     @include:namespace (or ns:include:namespace)
621         *     ^exclude:namespace (or -ns:exclude:namespace)
622         *   groups:
623         *     ()
624         *     -()
625         *   operators:
626         *     and ('and' is the default operator: you can always omit this)
627         *     or  (or pipe symbol '|', lower precedence than 'and')
628         *
629         * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
630         *      a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
631         *      this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
632         *      as long as you don't mind hit counts.
633         *
634         * intermediate representation consists of the following parts:
635         *
636         *   ( )           - group
637         *   AND           - logical and
638         *   OR            - logical or
639         *   NOT           - logical not
640         *   W+:, W-:, W_: - word      (underscore: no need to highlight)
641         *   P+:, P-:      - phrase    (minus sign: logically in NOT group)
642         *   N+:, N-:      - namespace
643         */
644        $parsed_query = '';
645        $parens_level = 0;
646        $terms = preg_split('/(-?".*?")/u', Utf8\PhpString::strtolower($query),
647                    -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
648        );
649
650        foreach ($terms as $term) {
651            $parsed = '';
652            if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
653                // phrase-include and phrase-exclude
654                $not = $matches[1] ? 'NOT' : '';
655                $parsed = $not . static::termParser($Indexer, $matches[2], false, true);
656            } else {
657                // fix incomplete phrase
658                $term = str_replace('"', ' ', $term);
659
660                // fix parentheses
661                $term = str_replace(')'  , ' ) ', $term);
662                $term = str_replace('('  , ' ( ', $term);
663                $term = str_replace('- (', ' -(', $term);
664
665                // treat pipe symbols as 'OR' operators
666                $term = str_replace('|', ' or ', $term);
667
668                // treat ideographic spaces (U+3000) as search term separators
669                // FIXME: some more separators?
670                $term = preg_replace('/[ \x{3000}]+/u', ' ',  $term);
671                $term = trim($term);
672                if ($term === '') continue;
673
674                $tokens = explode(' ', $term);
675                foreach ($tokens as $token) {
676                    if ($token === '(') {
677                        // parenthesis-include-open
678                        $parsed .= '(';
679                        ++$parens_level;
680                    } elseif ($token === '-(') {
681                        // parenthesis-exclude-open
682                        $parsed .= 'NOT(';
683                        ++$parens_level;
684                    } elseif ($token === ')') {
685                        // parenthesis-any-close
686                        if ($parens_level === 0) continue;
687                        $parsed .= ')';
688                        $parens_level--;
689                    } elseif ($token === 'and') {
690                        // logical-and (do nothing)
691                    } elseif ($token === 'or') {
692                        // logical-or
693                        $parsed .= 'OR';
694                    } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
695                        // namespace-exclude
696                        $parsed .= 'NOT(N+:'.$matches[1].')';
697                    } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
698                        // namespace-include
699                        $parsed .= '(N+:'.$matches[1].')';
700                    } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
701                        // word-exclude
702                        $parsed .= 'NOT('.static::termParser($Indexer, $matches[1]).')';
703                    } else {
704                        // word-include
705                        $parsed .= static::termParser($Indexer, $token);
706                    }
707                }
708            }
709            $parsed_query .= $parsed;
710        }
711
712        // cleanup (very sensitive)
713        $parsed_query .= str_repeat(')', $parens_level);
714        do {
715            $parsed_query_old = $parsed_query;
716            $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
717        } while ($parsed_query !== $parsed_query_old);
718        $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')'      , $parsed_query);
719        $parsed_query = preg_replace('/(OR)+/u'      , 'OR'     , $parsed_query);
720        $parsed_query = preg_replace('/\(OR/u'       , '('      , $parsed_query);
721        $parsed_query = preg_replace('/^OR|OR$/u'    , ''       , $parsed_query);
722        $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
723
724        // adjustment: make highlightings right
725        $parens_level     = 0;
726        $notgrp_levels    = array();
727        $parsed_query_new = '';
728        $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query,
729                    -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
730        );
731        foreach ($tokens as $token) {
732            if ($token === 'NOT(') {
733                $notgrp_levels[] = ++$parens_level;
734            } elseif ($token === '(') {
735                ++$parens_level;
736            } elseif ($token === ')') {
737                if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
738            } elseif (count($notgrp_levels) % 2 === 1) {
739                // turn highlight-flag off if terms are logically in "NOT" group
740                $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
741            }
742            $parsed_query_new .= $token;
743        }
744        $parsed_query = $parsed_query_new;
745
746        /**
747         * convert infix notation string into postfix (Reverse Polish notation) array
748         * by Shunting-yard algorithm
749         *
750         * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
751         * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
752         */
753        $parsed_ary     = array();
754        $ope_stack      = array();
755        $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
756        $ope_regex      = '/([()]|OR|AND|NOT)/u';
757
758        $tokens = preg_split($ope_regex, $parsed_query,
759                    -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
760        );
761        foreach ($tokens as $token) {
762            if (preg_match($ope_regex, $token)) {
763                // operator
764                $last_ope = end($ope_stack);
765                while ($last_ope !== false
766                    && $ope_precedence[$token] <= $ope_precedence[$last_ope]
767                    && $last_ope != '('
768                ) {
769                    $parsed_ary[] = array_pop($ope_stack);
770                    $last_ope = end($ope_stack);
771                }
772                if ($token == ')') {
773                    array_pop($ope_stack); // this array_pop always deletes '('
774                } else {
775                    $ope_stack[] = $token;
776                }
777            } else {
778                // operand
779                $token_decoded = str_replace(['OP','CP'], ['(',')'], $token);
780                $parsed_ary[] = $token_decoded;
781            }
782        }
783        $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
784
785        // cleanup: each double "NOT" in RPN array actually does nothing
786        $parsed_ary_count = count($parsed_ary);
787        for ($i = 1; $i < $parsed_ary_count; ++$i) {
788            if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
789                unset($parsed_ary[$i], $parsed_ary[$i - 1]);
790            }
791        }
792        $parsed_ary = array_values($parsed_ary);
793
794        // build return value
795        $q = array();
796        $q['query']      = $query;
797        $q['parsed_str'] = $parsed_query;
798        $q['parsed_ary'] = $parsed_ary;
799
800        foreach ($q['parsed_ary'] as $token) {
801            if ($token[2] !== ':') continue;
802            $body = substr($token, 3);
803
804            switch (substr($token, 0, 3)) {
805                case 'N+:':
806                     $q['ns'][]        = $body; // for backward compatibility
807                     break;
808                case 'N-:':
809                     $q['notns'][]     = $body; // for backward compatibility
810                     break;
811                case 'W_:':
812                     $q['words'][]     = $body;
813                     break;
814                case 'W-:':
815                     $q['words'][]     = $body;
816                     $q['not'][]       = $body; // for backward compatibility
817                     break;
818                case 'W+:':
819                     $q['words'][]     = $body;
820                     $q['highlight'][] = $body;
821                     $q['and'][]       = $body; // for backward compatibility
822                     break;
823                case 'P-:':
824                     $q['phrases'][]   = $body;
825                     break;
826                case 'P+:':
827                     $q['phrases'][]   = $body;
828                     $q['highlight'][] = $body;
829                     break;
830            }
831        }
832        foreach (['words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not'] as $key) {
833            $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
834        }
835
836        return $q;
837    }
838
839    /**
840     * Transforms given search term into intermediate representation
841     *
842     * This function is used in ft_queryParser() and not for general purpose use.
843     *
844     * @author Kazutaka Miyasaka <kazmiya@gmail.com>
845     *
846     * @param Indexer      $Indexer
847     * @param string       $term
848     * @param bool         $consider_asian
849     * @param bool         $phrase_mode
850     * @return string
851     */
852    protected static function termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false)
853    {
854        $parsed = '';
855        if ($consider_asian) {
856            // successive asian characters need to be searched as a phrase
857            $words = Utf8\Asian::splitAsianWords($term);
858            foreach ($words as $word) {
859                $phrase_mode = $phrase_mode ? true : Utf8\Asian::isAsianWords($word);
860                $parsed .= static::termParser($Indexer, $word, false, $phrase_mode);
861            }
862        } else {
863            $term_noparen = str_replace(['(',')'], ' ', $term);
864            $words = $Indexer->tokenizer($term_noparen, true);
865
866            // W_: no need to highlight
867            if (empty($words)) {
868                $parsed = '()'; // important: do not remove
869            } elseif ($words[0] === $term) {
870                $parsed = '(W+:'.$words[0].')';
871            } elseif ($phrase_mode) {
872                $term_encoded = str_replace(['(',')'], ['OP','CP'], $term);
873                $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
874            } else {
875                $parsed = '((W+:'.implode(')(W+:', $words).'))';
876            }
877        }
878        return $parsed;
879    }
880
881    /**
882     * Recreate a search query string based on parsed parts,
883     * doesn't support negated phrases and `OR` searches
884     *
885     * @param array $and
886     * @param array $not
887     * @param array $phrases
888     * @param array $ns
889     * @param array $notns
890     *
891     * @return string
892     */
893    public static function queryUnparser_simple(
894                        array $and, array $not, array $phrases, array $ns, array $notns
895    ) {
896        $query = implode(' ', $and);
897
898        if (!empty($not)) {
899            $query .= ' -' . implode(' -', $not);
900        }
901        if (!empty($phrases)) {
902            $query .= ' "' . implode('" "', $phrases) . '"';
903        }
904        if (!empty($ns)) {
905            $query .= ' @' . implode(' @', $ns);
906        }
907        if (!empty($notns)) {
908            $query .= ' ^' . implode(' ^', $notns);
909        }
910        return $query;
911    }
912}
913