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