xref: /dokuwiki/inc/fulltext.php (revision 5aa905e95e0f4ee1de1d93da15dbd388e985c134)
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 mtime after this date, accepts timestap or strtotime arguments
25 * @param int|string $before only show results with mtime 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 mtime after this date, accepts timestap or strtotime arguments
234 * @param int|string $before   only show results with mtime 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 mtime after this date, accepts timestap or strtotime arguments
317 * @param int|string $before  only returns results with mtime 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 = '(' .
417            join(
418                '|',
419                array_map(
420                    'ft_snippet_re_preprocess',
421                    array_map(
422                        'preg_quote_cb',
423                        array_filter((array) $highlight)
424                    )
425                )
426            ) .
427            ')';
428        $re2 = "$re1.{0,75}(?!\\1)$re1";
429        $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
430
431        for ($cnt=4; $cnt--;) {
432            if (0) {
433            } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
434            } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
435            } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
436            } else {
437                break;
438            }
439
440            list($str,$idx) = $match[0];
441
442            // convert $idx (a byte offset) into a utf8 character offset
443            $utf8_idx = utf8_strlen(substr($text,0,$idx));
444            $utf8_len = utf8_strlen($str);
445
446            // establish context, 100 bytes surrounding the match string
447            // first look to see if we can go 100 either side,
448            // then drop to 50 adding any excess if the other side can't go to 50,
449            $pre = min($utf8_idx-$utf8_offset,100);
450            $post = min($len-$utf8_idx-$utf8_len,100);
451
452            if ($pre>50 && $post>50) {
453                $pre = $post = 50;
454            } else if ($pre>50) {
455                $pre = min($pre,100-$post);
456            } else if ($post>50) {
457                $post = min($post, 100-$pre);
458            } else if ($offset == 0) {
459                // both are less than 50, means the context is the whole string
460                // make it so and break out of this loop - there is no need for the
461                // complex snippet calculations
462                $snippets = array($text);
463                break;
464            }
465
466            // establish context start and end points, try to append to previous
467            // context if possible
468            $start = $utf8_idx - $pre;
469            $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
470            $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
471
472            if ($append) {
473                $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append);
474            } else {
475                $snippets[] = utf8_substr($text,$start,$end-$start);
476            }
477
478            // set $offset for next match attempt
479            // continue matching after the current match
480            // if the current match is not the longest possible match starting at the current offset
481            // this prevents further matching of this snippet but for possible matches of length
482            // smaller than match length + context (at least 50 characters) this match is part of the context
483            $utf8_offset = $utf8_idx + $utf8_len;
484            $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$utf8_len));
485            $offset = utf8_correctIdx($text,$offset);
486        }
487
488        $m = "\1";
489        $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
490        $snippet = preg_replace(
491            '/' . $m . '([^' . $m . ']*?)' . $m . '/iu',
492            '<strong class="search_hit">$1</strong>',
493            hsc(join('... ', $snippets))
494        );
495
496        $evdata['snippet'] = $snippet;
497    }
498    $evt->advise_after();
499    unset($evt);
500
501    return $evdata['snippet'];
502}
503
504/**
505 * Wraps a search term in regex boundary checks.
506 *
507 * @param string $term
508 * @return string
509 */
510function ft_snippet_re_preprocess($term) {
511    // do not process asian terms where word boundaries are not explicit
512    if(preg_match('/'.IDX_ASIAN.'/u',$term)){
513        return $term;
514    }
515
516    if (UTF8_PROPERTYSUPPORT) {
517        // unicode word boundaries
518        // see http://stackoverflow.com/a/2449017/172068
519        $BL = '(?<!\pL)';
520        $BR = '(?!\pL)';
521    } else {
522        // not as correct as above, but at least won't break
523        $BL = '\b';
524        $BR = '\b';
525    }
526
527    if(substr($term,0,2) == '\\*'){
528        $term = substr($term,2);
529    }else{
530        $term = $BL.$term;
531    }
532
533    if(substr($term,-2,2) == '\\*'){
534        $term = substr($term,0,-2);
535    }else{
536        $term = $term.$BR;
537    }
538
539    if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
540    return $term;
541}
542
543/**
544 * Combine found documents and sum up their scores
545 *
546 * This function is used to combine searched words with a logical
547 * AND. Only documents available in all arrays are returned.
548 *
549 * based upon PEAR's PHP_Compat function for array_intersect_key()
550 *
551 * @param array $args An array of page arrays
552 * @return array
553 */
554function ft_resultCombine($args){
555    $array_count = count($args);
556    if($array_count == 1){
557        return $args[0];
558    }
559
560    $result = array();
561    if ($array_count > 1) {
562        foreach ($args[0] as $key => $value) {
563            $result[$key] = $value;
564            for ($i = 1; $i !== $array_count; $i++) {
565                if (!isset($args[$i][$key])) {
566                    unset($result[$key]);
567                    break;
568                }
569                $result[$key] += $args[$i][$key];
570            }
571        }
572    }
573    return $result;
574}
575
576/**
577 * Unites found documents and sum up their scores
578 *
579 * based upon ft_resultCombine() function
580 *
581 * @param array $args An array of page arrays
582 * @return array
583 *
584 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
585 */
586function ft_resultUnite($args) {
587    $array_count = count($args);
588    if ($array_count === 1) {
589        return $args[0];
590    }
591
592    $result = $args[0];
593    for ($i = 1; $i !== $array_count; $i++) {
594        foreach (array_keys($args[$i]) as $id) {
595            $result[$id] += $args[$i][$id];
596        }
597    }
598    return $result;
599}
600
601/**
602 * Computes the difference of documents using page id for comparison
603 *
604 * nearly identical to PHP5's array_diff_key()
605 *
606 * @param array $args An array of page arrays
607 * @return array
608 *
609 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
610 */
611function ft_resultComplement($args) {
612    $array_count = count($args);
613    if ($array_count === 1) {
614        return $args[0];
615    }
616
617    $result = $args[0];
618    foreach (array_keys($result) as $id) {
619        for ($i = 1; $i !== $array_count; $i++) {
620            if (isset($args[$i][$id])) unset($result[$id]);
621        }
622    }
623    return $result;
624}
625
626/**
627 * Parses a search query and builds an array of search formulas
628 *
629 * @author Andreas Gohr <andi@splitbrain.org>
630 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
631 *
632 * @param Doku_Indexer $Indexer
633 * @param string $query search query
634 * @return array of search formulas
635 */
636function ft_queryParser($Indexer, $query){
637    /**
638     * parse a search query and transform it into intermediate representation
639     *
640     * in a search query, you can use the following expressions:
641     *
642     *   words:
643     *     include
644     *     -exclude
645     *   phrases:
646     *     "phrase to be included"
647     *     -"phrase you want to exclude"
648     *   namespaces:
649     *     @include:namespace (or ns:include:namespace)
650     *     ^exclude:namespace (or -ns:exclude:namespace)
651     *   groups:
652     *     ()
653     *     -()
654     *   operators:
655     *     and ('and' is the default operator: you can always omit this)
656     *     or  (or pipe symbol '|', lower precedence than 'and')
657     *
658     * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
659     *      a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
660     *      this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
661     *      as long as you don't mind hit counts.
662     *
663     * intermediate representation consists of the following parts:
664     *
665     *   ( )           - group
666     *   AND           - logical and
667     *   OR            - logical or
668     *   NOT           - logical not
669     *   W+:, W-:, W_: - word      (underscore: no need to highlight)
670     *   P+:, P-:      - phrase    (minus sign: logically in NOT group)
671     *   N+:, N-:      - namespace
672     */
673    $parsed_query = '';
674    $parens_level = 0;
675    $terms = preg_split('/(-?".*?")/u', utf8_strtolower($query), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
676
677    foreach ($terms as $term) {
678        $parsed = '';
679        if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
680            // phrase-include and phrase-exclude
681            $not = $matches[1] ? 'NOT' : '';
682            $parsed = $not.ft_termParser($Indexer, $matches[2], false, true);
683        } else {
684            // fix incomplete phrase
685            $term = str_replace('"', ' ', $term);
686
687            // fix parentheses
688            $term = str_replace(')'  , ' ) ', $term);
689            $term = str_replace('('  , ' ( ', $term);
690            $term = str_replace('- (', ' -(', $term);
691
692            // treat pipe symbols as 'OR' operators
693            $term = str_replace('|', ' or ', $term);
694
695            // treat ideographic spaces (U+3000) as search term separators
696            // FIXME: some more separators?
697            $term = preg_replace('/[ \x{3000}]+/u', ' ',  $term);
698            $term = trim($term);
699            if ($term === '') continue;
700
701            $tokens = explode(' ', $term);
702            foreach ($tokens as $token) {
703                if ($token === '(') {
704                    // parenthesis-include-open
705                    $parsed .= '(';
706                    ++$parens_level;
707                } elseif ($token === '-(') {
708                    // parenthesis-exclude-open
709                    $parsed .= 'NOT(';
710                    ++$parens_level;
711                } elseif ($token === ')') {
712                    // parenthesis-any-close
713                    if ($parens_level === 0) continue;
714                    $parsed .= ')';
715                    $parens_level--;
716                } elseif ($token === 'and') {
717                    // logical-and (do nothing)
718                } elseif ($token === 'or') {
719                    // logical-or
720                    $parsed .= 'OR';
721                } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
722                    // namespace-exclude
723                    $parsed .= 'NOT(N+:'.$matches[1].')';
724                } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
725                    // namespace-include
726                    $parsed .= '(N+:'.$matches[1].')';
727                } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
728                    // word-exclude
729                    $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')';
730                } else {
731                    // word-include
732                    $parsed .= ft_termParser($Indexer, $token);
733                }
734            }
735        }
736        $parsed_query .= $parsed;
737    }
738
739    // cleanup (very sensitive)
740    $parsed_query .= str_repeat(')', $parens_level);
741    do {
742        $parsed_query_old = $parsed_query;
743        $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
744    } while ($parsed_query !== $parsed_query_old);
745    $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')'      , $parsed_query);
746    $parsed_query = preg_replace('/(OR)+/u'      , 'OR'     , $parsed_query);
747    $parsed_query = preg_replace('/\(OR/u'       , '('      , $parsed_query);
748    $parsed_query = preg_replace('/^OR|OR$/u'    , ''       , $parsed_query);
749    $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
750
751    // adjustment: make highlightings right
752    $parens_level     = 0;
753    $notgrp_levels    = array();
754    $parsed_query_new = '';
755    $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
756    foreach ($tokens as $token) {
757        if ($token === 'NOT(') {
758            $notgrp_levels[] = ++$parens_level;
759        } elseif ($token === '(') {
760            ++$parens_level;
761        } elseif ($token === ')') {
762            if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
763        } elseif (count($notgrp_levels) % 2 === 1) {
764            // turn highlight-flag off if terms are logically in "NOT" group
765            $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
766        }
767        $parsed_query_new .= $token;
768    }
769    $parsed_query = $parsed_query_new;
770
771    /**
772     * convert infix notation string into postfix (Reverse Polish notation) array
773     * by Shunting-yard algorithm
774     *
775     * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
776     * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
777     */
778    $parsed_ary     = array();
779    $ope_stack      = array();
780    $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
781    $ope_regex      = '/([()]|OR|AND|NOT)/u';
782
783    $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
784    foreach ($tokens as $token) {
785        if (preg_match($ope_regex, $token)) {
786            // operator
787            $last_ope = end($ope_stack);
788            while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
789                $parsed_ary[] = array_pop($ope_stack);
790                $last_ope = end($ope_stack);
791            }
792            if ($token == ')') {
793                array_pop($ope_stack); // this array_pop always deletes '('
794            } else {
795                $ope_stack[] = $token;
796            }
797        } else {
798            // operand
799            $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token);
800            $parsed_ary[] = $token_decoded;
801        }
802    }
803    $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
804
805    // cleanup: each double "NOT" in RPN array actually does nothing
806    $parsed_ary_count = count($parsed_ary);
807    for ($i = 1; $i < $parsed_ary_count; ++$i) {
808        if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
809            unset($parsed_ary[$i], $parsed_ary[$i - 1]);
810        }
811    }
812    $parsed_ary = array_values($parsed_ary);
813
814    // build return value
815    $q = array();
816    $q['query']      = $query;
817    $q['parsed_str'] = $parsed_query;
818    $q['parsed_ary'] = $parsed_ary;
819
820    foreach ($q['parsed_ary'] as $token) {
821        if ($token[2] !== ':') continue;
822        $body = substr($token, 3);
823
824        switch (substr($token, 0, 3)) {
825            case 'N+:':
826                     $q['ns'][]        = $body; // for backward compatibility
827                     break;
828            case 'N-:':
829                     $q['notns'][]     = $body; // for backward compatibility
830                     break;
831            case 'W_:':
832                     $q['words'][]     = $body;
833                     break;
834            case 'W-:':
835                     $q['words'][]     = $body;
836                     $q['not'][]       = $body; // for backward compatibility
837                     break;
838            case 'W+:':
839                     $q['words'][]     = $body;
840                     $q['highlight'][] = $body;
841                     $q['and'][]       = $body; // for backward compatibility
842                     break;
843            case 'P-:':
844                     $q['phrases'][]   = $body;
845                     break;
846            case 'P+:':
847                     $q['phrases'][]   = $body;
848                     $q['highlight'][] = $body;
849                     break;
850        }
851    }
852    foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) {
853        $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
854    }
855
856    return $q;
857}
858
859/**
860 * Transforms given search term into intermediate representation
861 *
862 * This function is used in ft_queryParser() and not for general purpose use.
863 *
864 * @author Kazutaka Miyasaka <kazmiya@gmail.com>
865 *
866 * @param Doku_Indexer $Indexer
867 * @param string       $term
868 * @param bool         $consider_asian
869 * @param bool         $phrase_mode
870 * @return string
871 */
872function ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) {
873    $parsed = '';
874    if ($consider_asian) {
875        // successive asian characters need to be searched as a phrase
876        $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
877        foreach ($words as $word) {
878            $phrase_mode = $phrase_mode ? true : preg_match('/'.IDX_ASIAN.'/u', $word);
879            $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
880        }
881    } else {
882        $term_noparen = str_replace(array('(', ')'), ' ', $term);
883        $words = $Indexer->tokenizer($term_noparen, true);
884
885        // W_: no need to highlight
886        if (empty($words)) {
887            $parsed = '()'; // important: do not remove
888        } elseif ($words[0] === $term) {
889            $parsed = '(W+:'.$words[0].')';
890        } elseif ($phrase_mode) {
891            $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term);
892            $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
893        } else {
894            $parsed = '((W+:'.implode(')(W+:', $words).'))';
895        }
896    }
897    return $parsed;
898}
899
900/**
901 * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches
902 *
903 * @param array $and
904 * @param array $not
905 * @param array $phrases
906 * @param array $ns
907 * @param array $notns
908 *
909 * @return string
910 */
911function ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) {
912    $query = implode(' ', $and);
913    if (!empty($not)) {
914        $query .= ' -' . implode(' -', $not);
915    }
916
917    if (!empty($phrases)) {
918        $query .= ' "' . implode('" "', $phrases) . '"';
919    }
920
921    if (!empty($ns)) {
922        $query .= ' @' . implode(' @', $ns);
923    }
924
925    if (!empty($notns)) {
926        $query .= ' ^' . implode(' ^', $notns);
927    }
928
929    return $query;
930}
931
932//Setup VIM: ex: et ts=4 :
933