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