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