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