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