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