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