xref: /dokuwiki/inc/fulltext.php (revision ba8f83490b45737d4cf33484c72b3aaa21e8894d)
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
478            } elseif (preg_match('/'.$re2.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
479
480            } elseif (preg_match('/'.$re1.'/iu', $text, $match, PREG_OFFSET_CAPTURE, $offset)) {
481
482            } else {
483                break;
484            }
485
486            [$str, $idx] = $match[0];
487
488            // convert $idx (a byte offset) into a utf8 character offset
489            $utf8_idx = PhpString::strlen(substr($text, 0, $idx));
490            $utf8_len = PhpString::strlen($str);
491
492            // establish context, 100 bytes surrounding the match string
493            // first look to see if we can go 100 either side,
494            // then drop to 50 adding any excess if the other side can't go to 50,
495            $pre = min($utf8_idx-$utf8_offset, 100);
496            $post = min($len-$utf8_idx-$utf8_len, 100);
497
498            if ($pre>50 && $post>50) {
499                $pre = 50;
500                $post = 50;
501            } elseif ($pre>50) {
502                $pre = min($pre, 100-$post);
503            } elseif ($post>50) {
504                $post = min($post, 100-$pre);
505            } elseif ($offset == 0) {
506                // both are less than 50, means the context is the whole string
507                // make it so and break out of this loop - there is no need for the
508                // complex snippet calculations
509                $snippets = [$text];
510                break;
511            }
512
513            // establish context start and end points, try to append to previous
514            // context if possible
515            $start = $utf8_idx - $pre;
516            $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
517            $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
518
519            if ($append) {
520                $snippets[count($snippets)-1] .= PhpString::substr($text, $append, $end-$append);
521            } else {
522                $snippets[] = PhpString::substr($text, $start, $end-$start);
523            }
524
525            // set $offset for next match attempt
526            // continue matching after the current match
527            // if the current match is not the longest possible match starting at the current offset
528            // this prevents further matching of this snippet but for possible matches of length
529            // smaller than match length + context (at least 50 characters) this match is part of the context
530            $utf8_offset = $utf8_idx + $utf8_len;
531            $offset = $idx + strlen(PhpString::substr($text, $utf8_idx, $utf8_len));
532            $offset = Clean::correctIdx($text, $offset);
533        }
534
535        $m = "\1";
536        $snippets = preg_replace('/'.$re1.'/iu', $m.'$1'.$m, $snippets);
537        $snippet = preg_replace(
538            '/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
539            '<strong class="search_hit">$1</strong>',
540            hsc(implode('... ', $snippets))
541        );
542
543        $evdata['snippet'] = $snippet;
544    }
545    $evt->advise_after();
546    unset($evt);
547
548    return $evdata['snippet'];
549}
550
551/**
552 * Wraps a search term in regex boundary checks.
553 *
554 * @param string $term
555 * @return string
556 */
557function ft_snippet_re_preprocess($term)
558{
559    // do not process asian terms where word boundaries are not explicit
560    if(Asian::isAsianWords($term)) return $term;
561
562    if (UTF8_PROPERTYSUPPORT) {
563        // unicode word boundaries
564        // see http://stackoverflow.com/a/2449017/172068
565        $BL = '(?<!\pL)';
566        $BR = '(?!\pL)';
567    } else {
568        // not as correct as above, but at least won't break
569        $BL = '\b';
570        $BR = '\b';
571    }
572
573    if(substr($term, 0, 2) == '\\*'){
574        $term = substr($term, 2);
575    }else{
576        $term = $BL.$term;
577    }
578
579    if(substr($term, -2, 2) == '\\*'){
580        $term = substr($term, 0, -2);
581    }else{
582        $term .= $BR;
583    }
584
585    if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
586    return $term;
587}
588
589/**
590 * Combine found documents and sum up their scores
591 *
592 * This function is used to combine searched words with a logical
593 * AND. Only documents available in all arrays are returned.
594 *
595 * based upon PEAR's PHP_Compat function for array_intersect_key()
596 *
597 * @param array $args An array of page arrays
598 * @return array
599 */
600function ft_resultCombine($args)
601{
602    $array_count = count($args);
603    if($array_count == 1){
604        return $args[0];
605    }
606
607    $result = [];
608    if ($array_count > 1) {
609        foreach ($args[0] as $key => $value) {
610            $result[$key] = $value;
611            for ($i = 1; $i !== $array_count; $i++) {
612                if (!isset($args[$i][$key])) {
613                    unset($result[$key]);
614                    break;
615                }
616                $result[$key] += $args[$i][$key];
617            }
618        }
619    }
620    return $result;
621}
622
623/**
624 * Unites found documents and sum up their scores
625 *
626 * based upon ft_resultCombine() function
627 *
628 * @param array $args An array of page arrays
629 * @return array
630 *
631 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
632 */
633function ft_resultUnite($args)
634{
635    $array_count = count($args);
636    if ($array_count === 1) {
637        return $args[0];
638    }
639
640    $result = $args[0];
641    for ($i = 1; $i !== $array_count; $i++) {
642        foreach (array_keys($args[$i]) as $id) {
643            $result[$id] += $args[$i][$id];
644        }
645    }
646    return $result;
647}
648
649/**
650 * Computes the difference of documents using page id for comparison
651 *
652 * nearly identical to PHP5's array_diff_key()
653 *
654 * @param array $args An array of page arrays
655 * @return array
656 *
657 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
658 */
659function ft_resultComplement($args)
660{
661    $array_count = count($args);
662    if ($array_count === 1) {
663        return $args[0];
664    }
665
666    $result = $args[0];
667    foreach (array_keys($result) as $id) {
668        for ($i = 1; $i !== $array_count; $i++) {
669            if (isset($args[$i][$id])) unset($result[$id]);
670        }
671    }
672    return $result;
673}
674
675/**
676 * Parses a search query and builds an array of search formulas
677 *
678 * @author Andreas Gohr <andi@splitbrain.org>
679 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
680 *
681 * @param Indexer $Indexer
682 * @param string                  $query search query
683 * @return array of search formulas
684 */
685function ft_queryParser($Indexer, $query)
686{
687    /**
688     * parse a search query and transform it into intermediate representation
689     *
690     * in a search query, you can use the following expressions:
691     *
692     *   words:
693     *     include
694     *     -exclude
695     *   phrases:
696     *     "phrase to be included"
697     *     -"phrase you want to exclude"
698     *   namespaces:
699     *     @include:namespace (or ns:include:namespace)
700     *     ^exclude:namespace (or -ns:exclude:namespace)
701     *   groups:
702     *     ()
703     *     -()
704     *   operators:
705     *     and ('and' is the default operator: you can always omit this)
706     *     or  (or pipe symbol '|', lower precedence than 'and')
707     *
708     * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
709     *      a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
710     *      this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
711     *      as long as you don't mind hit counts.
712     *
713     * intermediate representation consists of the following parts:
714     *
715     *   ( )           - group
716     *   AND           - logical and
717     *   OR            - logical or
718     *   NOT           - logical not
719     *   W+:, W-:, W_: - word      (underscore: no need to highlight)
720     *   P+:, P-:      - phrase    (minus sign: logically in NOT group)
721     *   N+:, N-:      - namespace
722     */
723    $parsed_query = '';
724    $parens_level = 0;
725    $terms = preg_split(
726        '/(-?".*?")/u',
727        PhpString::strtolower($query),
728        -1,
729        PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY
730    );
731
732    foreach ($terms as $term) {
733        $parsed = '';
734        if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
735            // phrase-include and phrase-exclude
736            $not = $matches[1] ? 'NOT' : '';
737            $parsed = $not.ft_termParser($Indexer, $matches[2], false, true);
738        } else {
739            // fix incomplete phrase
740            $term = str_replace('"', ' ', $term);
741
742            // fix parentheses
743            $term = str_replace(')', ' ) ', $term);
744            $term = str_replace('(', ' ( ', $term);
745            $term = str_replace('- (', ' -(', $term);
746
747            // treat pipe symbols as 'OR' operators
748            $term = str_replace('|', ' or ', $term);
749
750            // treat ideographic spaces (U+3000) as search term separators
751            // FIXME: some more separators?
752            $term = preg_replace('/[ \x{3000}]+/u', ' ', $term);
753            $term = trim($term);
754            if ($term === '') continue;
755
756            $tokens = explode(' ', $term);
757            foreach ($tokens as $token) {
758                if ($token === '(') {
759                    // parenthesis-include-open
760                    $parsed .= '(';
761                    ++$parens_level;
762                } elseif ($token === '-(') {
763                    // parenthesis-exclude-open
764                    $parsed .= 'NOT(';
765                    ++$parens_level;
766                } elseif ($token === ')') {
767                    // parenthesis-any-close
768                    if ($parens_level === 0) continue;
769                    $parsed .= ')';
770                    $parens_level--;
771                } elseif ($token === 'and') {
772                    // logical-and (do nothing)
773                } elseif ($token === 'or') {
774                    // logical-or
775                    $parsed .= 'OR';
776                } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
777                    // namespace-exclude
778                    $parsed .= 'NOT(N+:'.$matches[1].')';
779                } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
780                    // namespace-include
781                    $parsed .= '(N+:'.$matches[1].')';
782                } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
783                    // word-exclude
784                    $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')';
785                } else {
786                    // word-include
787                    $parsed .= ft_termParser($Indexer, $token);
788                }
789            }
790        }
791        $parsed_query .= $parsed;
792    }
793
794    // cleanup (very sensitive)
795    $parsed_query .= str_repeat(')', $parens_level);
796    do {
797        $parsed_query_old = $parsed_query;
798        $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
799    } while ($parsed_query !== $parsed_query_old);
800    $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')', $parsed_query);
801    $parsed_query = preg_replace('/(OR)+/u', 'OR', $parsed_query);
802    $parsed_query = preg_replace('/\(OR/u', '(', $parsed_query);
803    $parsed_query = preg_replace('/^OR|OR$/u', '', $parsed_query);
804    $parsed_query = preg_replace('/\)(NOT)?\(/u', ')AND$1(', $parsed_query);
805
806    // adjustment: make highlightings right
807    $parens_level     = 0;
808    $notgrp_levels    = [];
809    $parsed_query_new = '';
810    $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
811    foreach ($tokens as $token) {
812        if ($token === 'NOT(') {
813            $notgrp_levels[] = ++$parens_level;
814        } elseif ($token === '(') {
815            ++$parens_level;
816        } elseif ($token === ')') {
817            if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
818        } elseif (count($notgrp_levels) % 2 === 1) {
819            // turn highlight-flag off if terms are logically in "NOT" group
820            $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
821        }
822        $parsed_query_new .= $token;
823    }
824    $parsed_query = $parsed_query_new;
825
826    /**
827     * convert infix notation string into postfix (Reverse Polish notation) array
828     * by Shunting-yard algorithm
829     *
830     * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
831     * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
832     */
833    $parsed_ary     = [];
834    $ope_stack      = [];
835    $ope_precedence = [')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5];
836    $ope_regex      = '/([()]|OR|AND|NOT)/u';
837
838    $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
839    foreach ($tokens as $token) {
840        if (preg_match($ope_regex, $token)) {
841            // operator
842            $last_ope = end($ope_stack);
843            while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
844                $parsed_ary[] = array_pop($ope_stack);
845                $last_ope = end($ope_stack);
846            }
847            if ($token == ')') {
848                array_pop($ope_stack); // this array_pop always deletes '('
849            } else {
850                $ope_stack[] = $token;
851            }
852        } else {
853            // operand
854            $token_decoded = str_replace(['OP', 'CP'], ['(', ')'], $token);
855            $parsed_ary[] = $token_decoded;
856        }
857    }
858    $parsed_ary = array_values([...$parsed_ary, ...array_reverse($ope_stack)]);
859
860    // cleanup: each double "NOT" in RPN array actually does nothing
861    $parsed_ary_count = count($parsed_ary);
862    for ($i = 1; $i < $parsed_ary_count; ++$i) {
863        if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
864            unset($parsed_ary[$i], $parsed_ary[$i - 1]);
865        }
866    }
867    $parsed_ary = array_values($parsed_ary);
868
869    // build return value
870    $q = [];
871    $q['query']      = $query;
872    $q['parsed_str'] = $parsed_query;
873    $q['parsed_ary'] = $parsed_ary;
874
875    foreach ($q['parsed_ary'] as $token) {
876        if (strlen($token) < 3 || $token[2] !== ':') continue;
877        $body = substr($token, 3);
878
879        switch (substr($token, 0, 3)) {
880            case 'N+:':
881                     $q['ns'][]        = $body; // for backward compatibility
882                     break;
883            case 'N-:':
884                     $q['notns'][]     = $body; // for backward compatibility
885                     break;
886            case 'W_:':
887                     $q['words'][]     = $body;
888                     break;
889            case 'W-:':
890                     $q['words'][]     = $body;
891                     $q['not'][]       = $body; // for backward compatibility
892                     break;
893            case 'W+:':
894                     $q['words'][]     = $body;
895                     $q['highlight'][] = $body;
896                     $q['and'][]       = $body; // for backward compatibility
897                     break;
898            case 'P-:':
899                     $q['phrases'][]   = $body;
900                     break;
901            case 'P+:':
902                     $q['phrases'][]   = $body;
903                     $q['highlight'][] = $body;
904                     break;
905        }
906    }
907    foreach (['words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not'] as $key) {
908        $q[$key] = empty($q[$key]) ? [] : array_values(array_unique($q[$key]));
909    }
910
911    return $q;
912}
913
914/**
915 * Transforms given search term into intermediate representation
916 *
917 * This function is used in ft_queryParser() and not for general purpose use.
918 *
919 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
920 *
921 * @param Indexer $Indexer
922 * @param string                  $term
923 * @param bool                    $consider_asian
924 * @param bool                    $phrase_mode
925 * @return string
926 */
927function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false)
928{
929    $parsed = '';
930    if ($consider_asian) {
931        // successive asian characters need to be searched as a phrase
932        $words = Asian::splitAsianWords($term);
933        foreach ($words as $word) {
934            $phrase_mode = $phrase_mode ? true : Asian::isAsianWords($word);
935            $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
936        }
937    } else {
938        $term_noparen = str_replace(['(', ')'], ' ', $term);
939        $words = $Indexer->tokenizer($term_noparen, true);
940
941        // W_: no need to highlight
942        if (empty($words)) {
943            $parsed = '()'; // important: do not remove
944        } elseif ($words[0] === $term) {
945            $parsed = '(W+:'.$words[0].')';
946        } elseif ($phrase_mode) {
947            $term_encoded = str_replace(['(', ')'], ['OP', 'CP'], $term);
948            $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
949        } else {
950            $parsed = '((W+:'.implode(')(W+:', $words).'))';
951        }
952    }
953    return $parsed;
954}
955
956/**
957 * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches
958 *
959 * @param array $and
960 * @param array $not
961 * @param array $phrases
962 * @param array $ns
963 * @param array $notns
964 *
965 * @return string
966 */
967function ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns)
968{
969    $query = implode(' ', $and);
970    if ($not !== []) {
971        $query .= ' -' . implode(' -', $not);
972    }
973
974    if ($phrases !== []) {
975        $query .= ' "' . implode('" "', $phrases) . '"';
976    }
977
978    if ($ns !== []) {
979        $query .= ' @' . implode(' @', $ns);
980    }
981
982    if ($notns !== []) {
983        $query .= ' ^' . implode(' ^', $notns);
984    }
985
986    return $query;
987}
988
989//Setup VIM: ex: et ts=4 :
990