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