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