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