xref: /dokuwiki/inc/fulltext.php (revision 940f24fc89392ebb37bf46b27eb0adbd74962112)
1f5eb7cf0SAndreas Gohr<?php
2f5eb7cf0SAndreas Gohr/**
3f5eb7cf0SAndreas Gohr * DokuWiki fulltextsearch functions using the index
4f5eb7cf0SAndreas Gohr *
5f5eb7cf0SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6f5eb7cf0SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
7f5eb7cf0SAndreas Gohr */
8f5eb7cf0SAndreas Gohr
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
10f5eb7cf0SAndreas Gohr
11bd0293e7SAndreas Gohr/**
12bd0293e7SAndreas Gohr * create snippets for the first few results only
13bd0293e7SAndreas Gohr */
14bd0293e7SAndreas Gohrif(!defined('FT_SNIPPET_NUMBER')) define('FT_SNIPPET_NUMBER',15);
15f5eb7cf0SAndreas Gohr
16f5eb7cf0SAndreas Gohr/**
17f5eb7cf0SAndreas Gohr * The fulltext search
18f5eb7cf0SAndreas Gohr *
19f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query
20506fa893SAndreas Gohr *
216840140fSChris Smith * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event()
226840140fSChris Smith *
2342ea7f44SGerrit Uitslag * @param string $query
2442ea7f44SGerrit Uitslag * @param array $highlight
2542ea7f44SGerrit Uitslag * @return array
26f5eb7cf0SAndreas Gohr */
27546d3a99SAndreas Gohrfunction ft_pageSearch($query,&$highlight){
286840140fSChris Smith
2959bc3b48SGerrit Uitslag    $data = array();
306840140fSChris Smith    $data['query'] = $query;
316840140fSChris Smith    $data['highlight'] =& $highlight;
326840140fSChris Smith
336840140fSChris Smith    return trigger_event('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
346840140fSChris Smith}
35865c2687SKazutaka Miyasaka
36865c2687SKazutaka Miyasaka/**
37865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query
38865c2687SKazutaka Miyasaka *
39865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
40865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
4142ea7f44SGerrit Uitslag *
4242ea7f44SGerrit Uitslag * @param array $data event data
4342ea7f44SGerrit Uitslag * @return array matching documents
44865c2687SKazutaka Miyasaka */
456840140fSChris Smithfunction _ft_pageSearch(&$data) {
469b41be24STom N Harris    $Indexer = idx_get_indexer();
479b41be24STom N Harris
48865c2687SKazutaka Miyasaka    // parse the given query
499b41be24STom N Harris    $q = ft_queryParser($Indexer, $data['query']);
50865c2687SKazutaka Miyasaka    $data['highlight'] = $q['highlight'];
516840140fSChris Smith
52865c2687SKazutaka Miyasaka    if (empty($q['parsed_ary'])) return array();
53506fa893SAndreas Gohr
54f5eb7cf0SAndreas Gohr    // lookup all words found in the query
559b41be24STom N Harris    $lookup = $Indexer->lookup($q['words']);
56f5eb7cf0SAndreas Gohr
57865c2687SKazutaka Miyasaka    // get all pages in this dokuwiki site (!: includes nonexistent pages)
58865c2687SKazutaka Miyasaka    $pages_all = array();
599b41be24STom N Harris    foreach ($Indexer->getPages() as $id) {
609b41be24STom N Harris        $pages_all[$id] = 0; // base: 0 hit
61f5eb7cf0SAndreas Gohr    }
62f5eb7cf0SAndreas Gohr
63865c2687SKazutaka Miyasaka    // process the query
64865c2687SKazutaka Miyasaka    $stack = array();
65865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
66865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
67865c2687SKazutaka Miyasaka            case 'W+:':
682f502d70SKazutaka Miyasaka            case 'W-:':
692f502d70SKazutaka Miyasaka            case 'W_:': // word
70865c2687SKazutaka Miyasaka                $word    = substr($token, 3);
71865c2687SKazutaka Miyasaka                $stack[] = (array) $lookup[$word];
72865c2687SKazutaka Miyasaka                break;
732f502d70SKazutaka Miyasaka            case 'P+:':
742f502d70SKazutaka Miyasaka            case 'P-:': // phrase
75865c2687SKazutaka Miyasaka                $phrase = substr($token, 3);
76865c2687SKazutaka Miyasaka                // since phrases are always parsed as ((W1)(W2)...(P)),
77865c2687SKazutaka Miyasaka                // the end($stack) always points the pages that contain
78865c2687SKazutaka Miyasaka                // all words in this phrase
79865c2687SKazutaka Miyasaka                $pages  = end($stack);
80865c2687SKazutaka Miyasaka                $pages_matched = array();
81865c2687SKazutaka Miyasaka                foreach(array_keys($pages) as $id){
82a7e8b43eSMichael Hamann                    $evdata = array(
83a7e8b43eSMichael Hamann                        'id' => $id,
84a7e8b43eSMichael Hamann                        'phrase' => $phrase,
85a7e8b43eSMichael Hamann                        'text' => rawWiki($id)
86a7e8b43eSMichael Hamann                    );
87a7e8b43eSMichael Hamann                    $evt = new Doku_Event('FULLTEXT_PHRASE_MATCH',$evdata);
88a7e8b43eSMichael Hamann                    if ($evt->advise_before() && $evt->result !== true) {
89a7e8b43eSMichael Hamann                        $text = utf8_strtolower($evdata['text']);
90865c2687SKazutaka Miyasaka                        if (strpos($text, $phrase) !== false) {
91a7e8b43eSMichael Hamann                            $evt->result = true;
92a7e8b43eSMichael Hamann                        }
93a7e8b43eSMichael Hamann                    }
94a7e8b43eSMichael Hamann                    $evt->advise_after();
95a7e8b43eSMichael Hamann                    if ($evt->result === true) {
96865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // phrase: always 0 hit
97865c2687SKazutaka Miyasaka                    }
98865c2687SKazutaka Miyasaka                }
99865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
100865c2687SKazutaka Miyasaka                break;
1012f502d70SKazutaka Miyasaka            case 'N+:':
1022f502d70SKazutaka Miyasaka            case 'N-:': // namespace
103de3383c6SMichael Große                $ns = cleanID(substr($token, 3)) . ':';
104865c2687SKazutaka Miyasaka                $pages_matched = array();
105865c2687SKazutaka Miyasaka                foreach (array_keys($pages_all) as $id) {
106865c2687SKazutaka Miyasaka                    if (strpos($id, $ns) === 0) {
107865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // namespace: always 0 hit
108865c2687SKazutaka Miyasaka                    }
109865c2687SKazutaka Miyasaka                }
110865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
111865c2687SKazutaka Miyasaka                break;
112865c2687SKazutaka Miyasaka            case 'AND': // and operation
113865c2687SKazutaka Miyasaka                list($pages1, $pages2) = array_splice($stack, -2);
114865c2687SKazutaka Miyasaka                $stack[] = ft_resultCombine(array($pages1, $pages2));
115865c2687SKazutaka Miyasaka                break;
116865c2687SKazutaka Miyasaka            case 'OR':  // or operation
117865c2687SKazutaka Miyasaka                list($pages1, $pages2) = array_splice($stack, -2);
118865c2687SKazutaka Miyasaka                $stack[] = ft_resultUnite(array($pages1, $pages2));
119865c2687SKazutaka Miyasaka                break;
120865c2687SKazutaka Miyasaka            case 'NOT': // not operation (unary)
121865c2687SKazutaka Miyasaka                $pages   = array_pop($stack);
122865c2687SKazutaka Miyasaka                $stack[] = ft_resultComplement(array($pages_all, $pages));
123a21136cdSAndreas Gohr                break;
124a21136cdSAndreas Gohr        }
125f5eb7cf0SAndreas Gohr    }
126865c2687SKazutaka Miyasaka    $docs = array_pop($stack);
127865c2687SKazutaka Miyasaka
128865c2687SKazutaka Miyasaka    if (empty($docs)) return array();
129865c2687SKazutaka Miyasaka
130865c2687SKazutaka Miyasaka    // check: settings, acls, existence
131865c2687SKazutaka Miyasaka    foreach (array_keys($docs) as $id) {
132865c2687SKazutaka Miyasaka        if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) {
133865c2687SKazutaka Miyasaka            unset($docs[$id]);
134f5eb7cf0SAndreas Gohr        }
135f5eb7cf0SAndreas Gohr    }
136f5eb7cf0SAndreas Gohr
137865c2687SKazutaka Miyasaka    // sort docs by count
138f5eb7cf0SAndreas Gohr    arsort($docs);
139f5eb7cf0SAndreas Gohr
140f5eb7cf0SAndreas Gohr    return $docs;
141f5eb7cf0SAndreas Gohr}
142f5eb7cf0SAndreas Gohr
143f5eb7cf0SAndreas Gohr/**
14454f4c056SAndreas Gohr * Returns the backlinks for a given page
14554f4c056SAndreas Gohr *
146320f489aSMichael Hamann * Uses the metadata index.
14707ff0babSMichael Hamann *
14807ff0babSMichael Hamann * @param string $id           The id for which links shall be returned
14907ff0babSMichael Hamann * @param bool   $ignore_perms Ignore the fact that pages are hidden or read-protected
15007ff0babSMichael Hamann * @return array The pages that contain links to the given page
15154f4c056SAndreas Gohr */
15207ff0babSMichael Hamannfunction ft_backlinks($id, $ignore_perms = false){
153320f489aSMichael Hamann    $result = idx_get_indexer()->lookupKey('relation_references', $id);
15454f4c056SAndreas Gohr
15563773904SAndreas Gohr    if(!count($result)) return $result;
15663773904SAndreas Gohr
15763773904SAndreas Gohr    // check ACL permissions
15863773904SAndreas Gohr    foreach(array_keys($result) as $idx){
15907ff0babSMichael Hamann        if(($ignore_perms !== true && (
16007ff0babSMichael Hamann                isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
16107ff0babSMichael Hamann            )) || !page_exists($result[$idx], '', false)){
16263773904SAndreas Gohr            unset($result[$idx]);
16363773904SAndreas Gohr        }
16463773904SAndreas Gohr    }
16563773904SAndreas Gohr
16654f4c056SAndreas Gohr    sort($result);
16754f4c056SAndreas Gohr    return $result;
16854f4c056SAndreas Gohr}
16954f4c056SAndreas Gohr
17054f4c056SAndreas Gohr/**
171a05e297aSAndreas Gohr * Returns the pages that use a given media file
172a05e297aSAndreas Gohr *
173ffec1009SMichael Hamann * Uses the relation media metadata property and the metadata index.
174a05e297aSAndreas Gohr *
175ffec1009SMichael Hamann * Note that before 2013-07-31 the second parameter was the maximum number of results and
176ffec1009SMichael Hamann * permissions were ignored. That's why the parameter is now checked to be explicitely set
177ffec1009SMichael Hamann * to true (with type bool) in order to be compatible with older uses of the function.
178ffec1009SMichael Hamann *
179ffec1009SMichael Hamann * @param string $id           The media id to look for
180ffec1009SMichael Hamann * @param bool   $ignore_perms Ignore hidden pages and acls (optional, default: false)
181ffec1009SMichael Hamann * @return array A list of pages that use the given media file
182a05e297aSAndreas Gohr */
183ffec1009SMichael Hamannfunction ft_mediause($id, $ignore_perms = false){
184ffec1009SMichael Hamann    $result = idx_get_indexer()->lookupKey('relation_media', $id);
185a05e297aSAndreas Gohr
186ffec1009SMichael Hamann    if(!count($result)) return $result;
187a05e297aSAndreas Gohr
188ffec1009SMichael Hamann    // check ACL permissions
189ffec1009SMichael Hamann    foreach(array_keys($result) as $idx){
190ffec1009SMichael Hamann        if(($ignore_perms !== true && (
191ffec1009SMichael Hamann                    isHiddenPage($result[$idx]) || auth_quickaclcheck($result[$idx]) < AUTH_READ
192ffec1009SMichael Hamann                )) || !page_exists($result[$idx], '', false)){
193ffec1009SMichael Hamann            unset($result[$idx]);
194a05e297aSAndreas Gohr        }
195a05e297aSAndreas Gohr    }
196a05e297aSAndreas Gohr
197a05e297aSAndreas Gohr    sort($result);
198a05e297aSAndreas Gohr    return $result;
199a05e297aSAndreas Gohr}
200a05e297aSAndreas Gohr
201a05e297aSAndreas Gohr
202a05e297aSAndreas Gohr
203a05e297aSAndreas Gohr/**
204506fa893SAndreas Gohr * Quicksearch for pagenames
205506fa893SAndreas Gohr *
206506fa893SAndreas Gohr * By default it only matches the pagename and ignores the
20780423ab6SAdrian Lang * namespace. This can be changed with the second parameter.
20880423ab6SAdrian Lang * The third parameter allows to search in titles as well.
209506fa893SAndreas Gohr *
2108d22f1e9SAndreas Gohr * The function always returns titles as well
2116840140fSChris Smith *
2128d22f1e9SAndreas Gohr * @triggers SEARCH_QUERY_PAGELOOKUP
213506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
2148d22f1e9SAndreas Gohr * @author Adrian Lang <lang@cosmocode.de>
21542ea7f44SGerrit Uitslag *
21642ea7f44SGerrit Uitslag * @param string $id        page id
21742ea7f44SGerrit Uitslag * @param bool   $in_ns     match against namespace as well?
21842ea7f44SGerrit Uitslag * @param bool   $in_title  search in title?
21942ea7f44SGerrit Uitslag * @return string[]
220506fa893SAndreas Gohr */
2218d22f1e9SAndreas Gohrfunction ft_pageLookup($id, $in_ns=false, $in_title=false){
2228d22f1e9SAndreas Gohr    $data = compact('id', 'in_ns', 'in_title');
2238d22f1e9SAndreas Gohr    $data['has_titles'] = true; // for plugin backward compatibility check
2246840140fSChris Smith    return trigger_event('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup');
2256840140fSChris Smith}
2266840140fSChris Smith
22742ea7f44SGerrit Uitslag/**
22842ea7f44SGerrit Uitslag * Returns list of pages as array(pageid => First Heading)
22942ea7f44SGerrit Uitslag *
23042ea7f44SGerrit Uitslag * @param array &$data event data
23142ea7f44SGerrit Uitslag * @return string[]
23242ea7f44SGerrit Uitslag */
2336840140fSChris Smithfunction _ft_pageLookup(&$data){
23480423ab6SAdrian Lang    // split out original parameters
2356840140fSChris Smith    $id = $data['id'];
236*940f24fcSMichael Große    $Indexer = idx_get_indexer();
237*940f24fcSMichael Große    $parsedQuery = ft_queryParser($Indexer, $id);
238*940f24fcSMichael Große    if (count($parsedQuery['ns']) > 0) {
239*940f24fcSMichael Große        $ns = cleanID($parsedQuery['ns'][0]) . ':';
240*940f24fcSMichael Große        $id = implode(' ', $parsedQuery['highlight']);
241b0f6db0cSAdrian Lang    }
242b0f6db0cSAdrian Lang
2438d22f1e9SAndreas Gohr    $in_ns    = $data['in_ns'];
2448d22f1e9SAndreas Gohr    $in_title = $data['in_title'];
24580423ab6SAdrian Lang    $cleaned = cleanID($id);
2469b41be24STom N Harris
2479b41be24STom N Harris    $Indexer = idx_get_indexer();
2489b41be24STom N Harris    $page_idx = $Indexer->getPages();
2499b41be24STom N Harris
2509b41be24STom N Harris    $pages = array();
2515479a8c3SAndreas Gohr    if ($id !== '' && $cleaned !== '') {
2529b41be24STom N Harris        foreach ($page_idx as $p_id) {
2539b41be24STom N Harris            if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) !== false)) {
2549b41be24STom N Harris                if (!isset($pages[$p_id]))
25567c15eceSMichael Hamann                    $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
256506fa893SAndreas Gohr            }
257506fa893SAndreas Gohr        }
258f078bb00STom N Harris        if ($in_title) {
259c66f16a3SMichael Hamann            foreach ($Indexer->lookupKey('title', $id, '_ft_pageLookupTitleCompare') as $p_id) {
260f078bb00STom N Harris                if (!isset($pages[$p_id]))
26167c15eceSMichael Hamann                    $pages[$p_id] = p_get_first_heading($p_id, METADATA_DONT_RENDER);
262f078bb00STom N Harris            }
263f078bb00STom N Harris        }
264d0bdf765SAdrian Lang    }
2650c074a52SMichael Hamann
266d0bdf765SAdrian Lang    if (isset($ns)) {
2670c074a52SMichael Hamann        foreach (array_keys($pages) as $p_id) {
2680c074a52SMichael Hamann            if (strpos($p_id, $ns) !== 0) {
2690c074a52SMichael Hamann                unset($pages[$p_id]);
270d0bdf765SAdrian Lang            }
271d0bdf765SAdrian Lang        }
272506fa893SAndreas Gohr    }
27363773904SAndreas Gohr
27480423ab6SAdrian Lang    // discard hidden pages
27580423ab6SAdrian Lang    // discard nonexistent pages
27663773904SAndreas Gohr    // check ACL permissions
27763773904SAndreas Gohr    foreach(array_keys($pages) as $idx){
27880423ab6SAdrian Lang        if(!isVisiblePage($idx) || !page_exists($idx) ||
27980423ab6SAdrian Lang           auth_quickaclcheck($idx) < AUTH_READ) {
28063773904SAndreas Gohr            unset($pages[$idx]);
28163773904SAndreas Gohr        }
28263773904SAndreas Gohr    }
28363773904SAndreas Gohr
2843d2017d9SAdrian Lang    uksort($pages,'ft_pagesorter');
2858d22f1e9SAndreas Gohr    return $pages;
286506fa893SAndreas Gohr}
287506fa893SAndreas Gohr
288506fa893SAndreas Gohr/**
289c66f16a3SMichael Hamann * Tiny helper function for comparing the searched title with the title
290c66f16a3SMichael Hamann * from the search index. This function is a wrapper around stripos with
291c66f16a3SMichael Hamann * adapted argument order and return value.
29242ea7f44SGerrit Uitslag *
29342ea7f44SGerrit Uitslag * @param string $search searched title
29442ea7f44SGerrit Uitslag * @param string $title  title from index
29542ea7f44SGerrit Uitslag * @return bool
296c66f16a3SMichael Hamann */
297c66f16a3SMichael Hamannfunction _ft_pageLookupTitleCompare($search, $title) {
298c66f16a3SMichael Hamann    return stripos($title, $search) !== false;
299c66f16a3SMichael Hamann}
300c66f16a3SMichael Hamann
301c66f16a3SMichael Hamann/**
302f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string
303f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy
304f31eb72bSAndreas Gohr * pages.
30542ea7f44SGerrit Uitslag *
30642ea7f44SGerrit Uitslag * @param string $a
30742ea7f44SGerrit Uitslag * @param string $b
30842ea7f44SGerrit Uitslag * @return int Returns < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal.
309f31eb72bSAndreas Gohr */
310f31eb72bSAndreas Gohrfunction ft_pagesorter($a, $b){
311f31eb72bSAndreas Gohr    $ac = count(explode(':',$a));
312f31eb72bSAndreas Gohr    $bc = count(explode(':',$b));
313f31eb72bSAndreas Gohr    if($ac < $bc){
314f31eb72bSAndreas Gohr        return -1;
315f31eb72bSAndreas Gohr    }elseif($ac > $bc){
316f31eb72bSAndreas Gohr        return 1;
317f31eb72bSAndreas Gohr    }
318f31eb72bSAndreas Gohr    return strcmp ($a,$b);
319f31eb72bSAndreas Gohr}
320f31eb72bSAndreas Gohr
321f31eb72bSAndreas Gohr/**
322506fa893SAndreas Gohr * Creates a snippet extract
323506fa893SAndreas Gohr *
324506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
32560e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE
32642ea7f44SGerrit Uitslag *
32742ea7f44SGerrit Uitslag * @param string $id page id
32842ea7f44SGerrit Uitslag * @param array $highlight
32942ea7f44SGerrit Uitslag * @return mixed
330506fa893SAndreas Gohr */
331546d3a99SAndreas Gohrfunction ft_snippet($id,$highlight){
332506fa893SAndreas Gohr    $text = rawWiki($id);
3334f0030ddSAndreas Gohr    $text = str_replace("\xC2\xAD",'',$text); // remove soft-hyphens
33460e91a17SAndreas Gohr    $evdata = array(
33560e91a17SAndreas Gohr            'id'        => $id,
33660e91a17SAndreas Gohr            'text'      => &$text,
33760e91a17SAndreas Gohr            'highlight' => &$highlight,
33860e91a17SAndreas Gohr            'snippet'   => '',
33960e91a17SAndreas Gohr            );
34060e91a17SAndreas Gohr
34160e91a17SAndreas Gohr    $evt = new Doku_Event('FULLTEXT_SNIPPET_CREATE',$evdata);
34260e91a17SAndreas Gohr    if ($evt->advise_before()) {
343ced0762eSchris        $match = array();
344ced0762eSchris        $snippets = array();
3459ee93076Schris        $utf8_offset = $offset = $end = 0;
346ced0762eSchris        $len = utf8_strlen($text);
3479ee93076Schris
348546d3a99SAndreas Gohr        // build a regexp from the phrases to highlight
3492237b4faSAndreas Gohr        $re1 = '('.join('|',array_map('ft_snippet_re_preprocess', array_map('preg_quote_cb',array_filter((array) $highlight)))).')';
350b571ff2dSChuck Kollars        $re2 = "$re1.{0,75}(?!\\1)$re1";
351b571ff2dSChuck Kollars        $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
352546d3a99SAndreas Gohr
353b571ff2dSChuck Kollars        for ($cnt=4; $cnt--;) {
354b571ff2dSChuck Kollars            if (0) {
355b571ff2dSChuck Kollars            } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
356b571ff2dSChuck Kollars            } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
357b571ff2dSChuck Kollars            } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
358b571ff2dSChuck Kollars            } else {
359b571ff2dSChuck Kollars                break;
360b571ff2dSChuck Kollars            }
361ced0762eSchris
362ced0762eSchris            list($str,$idx) = $match[0];
363ced0762eSchris
364ced0762eSchris            // convert $idx (a byte offset) into a utf8 character offset
365ced0762eSchris            $utf8_idx = utf8_strlen(substr($text,0,$idx));
366ced0762eSchris            $utf8_len = utf8_strlen($str);
367ced0762eSchris
368ced0762eSchris            // establish context, 100 bytes surrounding the match string
369ced0762eSchris            // first look to see if we can go 100 either side,
370ced0762eSchris            // then drop to 50 adding any excess if the other side can't go to 50,
371ced0762eSchris            $pre = min($utf8_idx-$utf8_offset,100);
372ced0762eSchris            $post = min($len-$utf8_idx-$utf8_len,100);
373ced0762eSchris
374ced0762eSchris            if ($pre>50 && $post>50) {
375ced0762eSchris                $pre = $post = 50;
376ced0762eSchris            } else if ($pre>50) {
377ced0762eSchris                $pre = min($pre,100-$post);
378ced0762eSchris            } else if ($post>50) {
379ced0762eSchris                $post = min($post, 100-$pre);
380ef3e3cddSMichael Hamann            } else if ($offset == 0) {
381ced0762eSchris                // both are less than 50, means the context is the whole string
38210ffc9ddSAndreas Gohr                // make it so and break out of this loop - there is no need for the
38310ffc9ddSAndreas Gohr                // complex snippet calculations
384ced0762eSchris                $snippets = array($text);
385ced0762eSchris                break;
386ced0762eSchris            }
387ced0762eSchris
38810ffc9ddSAndreas Gohr            // establish context start and end points, try to append to previous
38910ffc9ddSAndreas Gohr            // context if possible
3909ee93076Schris            $start = $utf8_idx - $pre;
391ced0762eSchris            $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
3929ee93076Schris            $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
393ced0762eSchris
394ced0762eSchris            if ($append) {
395ced0762eSchris                $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append);
396ced0762eSchris            } else {
397ced0762eSchris                $snippets[] = utf8_substr($text,$start,$end-$start);
398ced0762eSchris            }
399ced0762eSchris
400ced0762eSchris            // set $offset for next match attempt
40143d58b76SMichael Hamann            // continue matching after the current match
40243d58b76SMichael Hamann            // if the current match is not the longest possible match starting at the current offset
40343d58b76SMichael Hamann            // this prevents further matching of this snippet but for possible matches of length
40443d58b76SMichael Hamann            // smaller than match length + context (at least 50 characters) this match is part of the context
40543d58b76SMichael Hamann            $utf8_offset = $utf8_idx + $utf8_len;
40643d58b76SMichael Hamann            $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$utf8_len));
4079ee93076Schris            $offset = utf8_correctIdx($text,$offset);
4089ee93076Schris        }
4099ee93076Schris
410ced0762eSchris        $m = "\1";
411b571ff2dSChuck Kollars        $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
412b571ff2dSChuck Kollars        $snippet = preg_replace('/'.$m.'([^'.$m.']*?)'.$m.'/iu','<strong class="search_hit">$1</strong>',hsc(join('... ',$snippets)));
413bd2cb6fcSchris
41460e91a17SAndreas Gohr        $evdata['snippet'] = $snippet;
41560e91a17SAndreas Gohr    }
41660e91a17SAndreas Gohr    $evt->advise_after();
41760e91a17SAndreas Gohr    unset($evt);
41860e91a17SAndreas Gohr
41960e91a17SAndreas Gohr    return $evdata['snippet'];
420506fa893SAndreas Gohr}
421506fa893SAndreas Gohr
422506fa893SAndreas Gohr/**
42326eb848cSGina Haeussge * Wraps a search term in regex boundary checks.
42442ea7f44SGerrit Uitslag *
42542ea7f44SGerrit Uitslag * @param string $term
42642ea7f44SGerrit Uitslag * @return string
42726eb848cSGina Haeussge */
4282237b4faSAndreas Gohrfunction ft_snippet_re_preprocess($term) {
42935594613SKazutaka Miyasaka    // do not process asian terms where word boundaries are not explicit
43035594613SKazutaka Miyasaka    if(preg_match('/'.IDX_ASIAN.'/u',$term)){
43135594613SKazutaka Miyasaka        return $term;
43235594613SKazutaka Miyasaka    }
43335594613SKazutaka Miyasaka
4343161005dSAndreas Gohr    if (UTF8_PROPERTYSUPPORT) {
43584e581a6SAndreas Gohr        // unicode word boundaries
43684e581a6SAndreas Gohr        // see http://stackoverflow.com/a/2449017/172068
43784e581a6SAndreas Gohr        $BL = '(?<!\pL)';
43884e581a6SAndreas Gohr        $BR = '(?!\pL)';
4393161005dSAndreas Gohr    } else {
4403161005dSAndreas Gohr        // not as correct as above, but at least won't break
4413161005dSAndreas Gohr        $BL = '\b';
4423161005dSAndreas Gohr        $BR = '\b';
4433161005dSAndreas Gohr    }
4443161005dSAndreas Gohr
4452237b4faSAndreas Gohr    if(substr($term,0,2) == '\\*'){
4462237b4faSAndreas Gohr        $term = substr($term,2);
4472237b4faSAndreas Gohr    }else{
44884e581a6SAndreas Gohr        $term = $BL.$term;
4492237b4faSAndreas Gohr    }
4502237b4faSAndreas Gohr
4512237b4faSAndreas Gohr    if(substr($term,-2,2) == '\\*'){
4522237b4faSAndreas Gohr        $term = substr($term,0,-2);
4532237b4faSAndreas Gohr    }else{
45484e581a6SAndreas Gohr        $term = $term.$BR;
4552237b4faSAndreas Gohr    }
4568a803caeSAndreas Gohr
45784e581a6SAndreas Gohr    if($term == $BL || $term == $BR || $term == $BL.$BR) $term = '';
4582237b4faSAndreas Gohr    return $term;
45926eb848cSGina Haeussge}
46026eb848cSGina Haeussge
46126eb848cSGina Haeussge/**
462f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores
463f5eb7cf0SAndreas Gohr *
464f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical
465f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned.
466f5eb7cf0SAndreas Gohr *
467f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key()
468f5eb7cf0SAndreas Gohr *
469f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays
47042ea7f44SGerrit Uitslag * @return array
471f5eb7cf0SAndreas Gohr */
472f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){
473f5eb7cf0SAndreas Gohr    $array_count = count($args);
474134f4ab2SAndreas Gohr    if($array_count == 1){
475134f4ab2SAndreas Gohr        return $args[0];
476134f4ab2SAndreas Gohr    }
477134f4ab2SAndreas Gohr
478f5eb7cf0SAndreas Gohr    $result = array();
47909c27a6dSGuy Brand    if ($array_count > 1) {
480a21136cdSAndreas Gohr        foreach ($args[0] as $key => $value) {
481a21136cdSAndreas Gohr            $result[$key] = $value;
482f5eb7cf0SAndreas Gohr            for ($i = 1; $i !== $array_count; $i++) {
483a21136cdSAndreas Gohr                if (!isset($args[$i][$key])) {
484a21136cdSAndreas Gohr                    unset($result[$key]);
485a21136cdSAndreas Gohr                    break;
486f5eb7cf0SAndreas Gohr                }
487a21136cdSAndreas Gohr                $result[$key] += $args[$i][$key];
488f5eb7cf0SAndreas Gohr            }
489f5eb7cf0SAndreas Gohr        }
49009c27a6dSGuy Brand    }
491f5eb7cf0SAndreas Gohr    return $result;
492f5eb7cf0SAndreas Gohr}
493f5eb7cf0SAndreas Gohr
494f5eb7cf0SAndreas Gohr/**
495865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores
496f5eb7cf0SAndreas Gohr *
497865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function
498865c2687SKazutaka Miyasaka *
499865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
50042ea7f44SGerrit Uitslag * @return array
50142ea7f44SGerrit Uitslag *
502865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
503865c2687SKazutaka Miyasaka */
504865c2687SKazutaka Miyasakafunction ft_resultUnite($args) {
505865c2687SKazutaka Miyasaka    $array_count = count($args);
506865c2687SKazutaka Miyasaka    if ($array_count === 1) {
507865c2687SKazutaka Miyasaka        return $args[0];
508865c2687SKazutaka Miyasaka    }
509865c2687SKazutaka Miyasaka
510865c2687SKazutaka Miyasaka    $result = $args[0];
511865c2687SKazutaka Miyasaka    for ($i = 1; $i !== $array_count; $i++) {
512865c2687SKazutaka Miyasaka        foreach (array_keys($args[$i]) as $id) {
513865c2687SKazutaka Miyasaka            $result[$id] += $args[$i][$id];
514865c2687SKazutaka Miyasaka        }
515865c2687SKazutaka Miyasaka    }
516865c2687SKazutaka Miyasaka    return $result;
517865c2687SKazutaka Miyasaka}
518865c2687SKazutaka Miyasaka
519865c2687SKazutaka Miyasaka/**
520865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison
521865c2687SKazutaka Miyasaka *
522865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key()
523865c2687SKazutaka Miyasaka *
524865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
52542ea7f44SGerrit Uitslag * @return array
52642ea7f44SGerrit Uitslag *
527865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
528865c2687SKazutaka Miyasaka */
529865c2687SKazutaka Miyasakafunction ft_resultComplement($args) {
530865c2687SKazutaka Miyasaka    $array_count = count($args);
531865c2687SKazutaka Miyasaka    if ($array_count === 1) {
532865c2687SKazutaka Miyasaka        return $args[0];
533865c2687SKazutaka Miyasaka    }
534865c2687SKazutaka Miyasaka
535865c2687SKazutaka Miyasaka    $result = $args[0];
536865c2687SKazutaka Miyasaka    foreach (array_keys($result) as $id) {
537865c2687SKazutaka Miyasaka        for ($i = 1; $i !== $array_count; $i++) {
538865c2687SKazutaka Miyasaka            if (isset($args[$i][$id])) unset($result[$id]);
539865c2687SKazutaka Miyasaka        }
540865c2687SKazutaka Miyasaka    }
541865c2687SKazutaka Miyasaka    return $result;
542865c2687SKazutaka Miyasaka}
543865c2687SKazutaka Miyasaka
544865c2687SKazutaka Miyasaka/**
545865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas
546865c2687SKazutaka Miyasaka *
547865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
548865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
54942ea7f44SGerrit Uitslag *
55042ea7f44SGerrit Uitslag * @param Doku_Indexer $Indexer
55142ea7f44SGerrit Uitslag * @param string $query search query
55242ea7f44SGerrit Uitslag * @return array of search formulas
553f5eb7cf0SAndreas Gohr */
5549b41be24STom N Harrisfunction ft_queryParser($Indexer, $query){
555865c2687SKazutaka Miyasaka    /**
556865c2687SKazutaka Miyasaka     * parse a search query and transform it into intermediate representation
557865c2687SKazutaka Miyasaka     *
558865c2687SKazutaka Miyasaka     * in a search query, you can use the following expressions:
559865c2687SKazutaka Miyasaka     *
560865c2687SKazutaka Miyasaka     *   words:
561865c2687SKazutaka Miyasaka     *     include
562865c2687SKazutaka Miyasaka     *     -exclude
563865c2687SKazutaka Miyasaka     *   phrases:
564865c2687SKazutaka Miyasaka     *     "phrase to be included"
565865c2687SKazutaka Miyasaka     *     -"phrase you want to exclude"
566865c2687SKazutaka Miyasaka     *   namespaces:
567865c2687SKazutaka Miyasaka     *     @include:namespace (or ns:include:namespace)
568865c2687SKazutaka Miyasaka     *     ^exclude:namespace (or -ns:exclude:namespace)
569865c2687SKazutaka Miyasaka     *   groups:
570865c2687SKazutaka Miyasaka     *     ()
571865c2687SKazutaka Miyasaka     *     -()
572865c2687SKazutaka Miyasaka     *   operators:
573865c2687SKazutaka Miyasaka     *     and ('and' is the default operator: you can always omit this)
5747871d415SKazutaka Miyasaka     *     or  (or pipe symbol '|', lower precedence than 'and')
575865c2687SKazutaka Miyasaka     *
576865c2687SKazutaka Miyasaka     * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
577865c2687SKazutaka Miyasaka     *      a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
578865c2687SKazutaka Miyasaka     *      this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
579865c2687SKazutaka Miyasaka     *      as long as you don't mind hit counts.
580865c2687SKazutaka Miyasaka     *
581865c2687SKazutaka Miyasaka     * intermediate representation consists of the following parts:
582865c2687SKazutaka Miyasaka     *
583865c2687SKazutaka Miyasaka     *   ( )           - group
584865c2687SKazutaka Miyasaka     *   AND           - logical and
585865c2687SKazutaka Miyasaka     *   OR            - logical or
586865c2687SKazutaka Miyasaka     *   NOT           - logical not
5872f502d70SKazutaka Miyasaka     *   W+:, W-:, W_: - word      (underscore: no need to highlight)
5882f502d70SKazutaka Miyasaka     *   P+:, P-:      - phrase    (minus sign: logically in NOT group)
5892f502d70SKazutaka Miyasaka     *   N+:, N-:      - namespace
590865c2687SKazutaka Miyasaka     */
591865c2687SKazutaka Miyasaka    $parsed_query = '';
592865c2687SKazutaka Miyasaka    $parens_level = 0;
593865c2687SKazutaka Miyasaka    $terms = preg_split('/(-?".*?")/u', utf8_strtolower($query), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
594865c2687SKazutaka Miyasaka
595865c2687SKazutaka Miyasaka    foreach ($terms as $term) {
596865c2687SKazutaka Miyasaka        $parsed = '';
597865c2687SKazutaka Miyasaka        if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
598865c2687SKazutaka Miyasaka            // phrase-include and phrase-exclude
599865c2687SKazutaka Miyasaka            $not = $matches[1] ? 'NOT' : '';
6009b41be24STom N Harris            $parsed = $not.ft_termParser($Indexer, $matches[2], false, true);
601f5eb7cf0SAndreas Gohr        } else {
602865c2687SKazutaka Miyasaka            // fix incomplete phrase
603865c2687SKazutaka Miyasaka            $term = str_replace('"', ' ', $term);
604865c2687SKazutaka Miyasaka
605865c2687SKazutaka Miyasaka            // fix parentheses
606865c2687SKazutaka Miyasaka            $term = str_replace(')'  , ' ) ', $term);
607865c2687SKazutaka Miyasaka            $term = str_replace('('  , ' ( ', $term);
608865c2687SKazutaka Miyasaka            $term = str_replace('- (', ' -(', $term);
609865c2687SKazutaka Miyasaka
6107871d415SKazutaka Miyasaka            // treat pipe symbols as 'OR' operators
6117871d415SKazutaka Miyasaka            $term = str_replace('|', ' or ', $term);
6127871d415SKazutaka Miyasaka
613865c2687SKazutaka Miyasaka            // treat ideographic spaces (U+3000) as search term separators
614865c2687SKazutaka Miyasaka            // FIXME: some more separators?
615865c2687SKazutaka Miyasaka            $term = preg_replace('/[ \x{3000}]+/u', ' ',  $term);
616865c2687SKazutaka Miyasaka            $term = trim($term);
617865c2687SKazutaka Miyasaka            if ($term === '') continue;
618865c2687SKazutaka Miyasaka
619865c2687SKazutaka Miyasaka            $tokens = explode(' ', $term);
620865c2687SKazutaka Miyasaka            foreach ($tokens as $token) {
621865c2687SKazutaka Miyasaka                if ($token === '(') {
622865c2687SKazutaka Miyasaka                    // parenthesis-include-open
623865c2687SKazutaka Miyasaka                    $parsed .= '(';
624865c2687SKazutaka Miyasaka                    ++$parens_level;
625865c2687SKazutaka Miyasaka                } elseif ($token === '-(') {
626865c2687SKazutaka Miyasaka                    // parenthesis-exclude-open
627865c2687SKazutaka Miyasaka                    $parsed .= 'NOT(';
628865c2687SKazutaka Miyasaka                    ++$parens_level;
629865c2687SKazutaka Miyasaka                } elseif ($token === ')') {
630865c2687SKazutaka Miyasaka                    // parenthesis-any-close
631865c2687SKazutaka Miyasaka                    if ($parens_level === 0) continue;
632865c2687SKazutaka Miyasaka                    $parsed .= ')';
633865c2687SKazutaka Miyasaka                    $parens_level--;
634865c2687SKazutaka Miyasaka                } elseif ($token === 'and') {
635865c2687SKazutaka Miyasaka                    // logical-and (do nothing)
636865c2687SKazutaka Miyasaka                } elseif ($token === 'or') {
637865c2687SKazutaka Miyasaka                    // logical-or
638865c2687SKazutaka Miyasaka                    $parsed .= 'OR';
639865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
640865c2687SKazutaka Miyasaka                    // namespace-exclude
6412f502d70SKazutaka Miyasaka                    $parsed .= 'NOT(N+:'.$matches[1].')';
642865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
643865c2687SKazutaka Miyasaka                    // namespace-include
6442f502d70SKazutaka Miyasaka                    $parsed .= '(N+:'.$matches[1].')';
645865c2687SKazutaka Miyasaka                } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
646865c2687SKazutaka Miyasaka                    // word-exclude
6479b41be24STom N Harris                    $parsed .= 'NOT('.ft_termParser($Indexer, $matches[1]).')';
648865c2687SKazutaka Miyasaka                } else {
649865c2687SKazutaka Miyasaka                    // word-include
6509b41be24STom N Harris                    $parsed .= ft_termParser($Indexer, $token);
651865c2687SKazutaka Miyasaka                }
652865c2687SKazutaka Miyasaka            }
653865c2687SKazutaka Miyasaka        }
654865c2687SKazutaka Miyasaka        $parsed_query .= $parsed;
655f5eb7cf0SAndreas Gohr    }
656f5eb7cf0SAndreas Gohr
657865c2687SKazutaka Miyasaka    // cleanup (very sensitive)
658865c2687SKazutaka Miyasaka    $parsed_query .= str_repeat(')', $parens_level);
659865c2687SKazutaka Miyasaka    do {
660865c2687SKazutaka Miyasaka        $parsed_query_old = $parsed_query;
661865c2687SKazutaka Miyasaka        $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
662865c2687SKazutaka Miyasaka    } while ($parsed_query !== $parsed_query_old);
663865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')'      , $parsed_query);
664865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(OR)+/u'      , 'OR'     , $parsed_query);
665865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\(OR/u'       , '('      , $parsed_query);
666865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/^OR|OR$/u'    , ''       , $parsed_query);
667865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
668865c2687SKazutaka Miyasaka
6692f502d70SKazutaka Miyasaka    // adjustment: make highlightings right
6702f502d70SKazutaka Miyasaka    $parens_level     = 0;
6712f502d70SKazutaka Miyasaka    $notgrp_levels    = array();
6722f502d70SKazutaka Miyasaka    $parsed_query_new = '';
6732f502d70SKazutaka Miyasaka    $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
6742f502d70SKazutaka Miyasaka    foreach ($tokens as $token) {
6752f502d70SKazutaka Miyasaka        if ($token === 'NOT(') {
6762f502d70SKazutaka Miyasaka            $notgrp_levels[] = ++$parens_level;
6772f502d70SKazutaka Miyasaka        } elseif ($token === '(') {
6782f502d70SKazutaka Miyasaka            ++$parens_level;
6792f502d70SKazutaka Miyasaka        } elseif ($token === ')') {
6802f502d70SKazutaka Miyasaka            if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
6812f502d70SKazutaka Miyasaka        } elseif (count($notgrp_levels) % 2 === 1) {
6822f502d70SKazutaka Miyasaka            // turn highlight-flag off if terms are logically in "NOT" group
6832f502d70SKazutaka Miyasaka            $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
6842f502d70SKazutaka Miyasaka        }
6852f502d70SKazutaka Miyasaka        $parsed_query_new .= $token;
6862f502d70SKazutaka Miyasaka    }
6872f502d70SKazutaka Miyasaka    $parsed_query = $parsed_query_new;
6882f502d70SKazutaka Miyasaka
689865c2687SKazutaka Miyasaka    /**
690865c2687SKazutaka Miyasaka     * convert infix notation string into postfix (Reverse Polish notation) array
691865c2687SKazutaka Miyasaka     * by Shunting-yard algorithm
692865c2687SKazutaka Miyasaka     *
693865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
694865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
695865c2687SKazutaka Miyasaka     */
696865c2687SKazutaka Miyasaka    $parsed_ary     = array();
697865c2687SKazutaka Miyasaka    $ope_stack      = array();
698865c2687SKazutaka Miyasaka    $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
699865c2687SKazutaka Miyasaka    $ope_regex      = '/([()]|OR|AND|NOT)/u';
700865c2687SKazutaka Miyasaka
701865c2687SKazutaka Miyasaka    $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
702865c2687SKazutaka Miyasaka    foreach ($tokens as $token) {
703865c2687SKazutaka Miyasaka        if (preg_match($ope_regex, $token)) {
704865c2687SKazutaka Miyasaka            // operator
705865c2687SKazutaka Miyasaka            $last_ope = end($ope_stack);
70667d812e0SMarius van Witzenburg            while ($last_ope !== false && $ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
707865c2687SKazutaka Miyasaka                $parsed_ary[] = array_pop($ope_stack);
708865c2687SKazutaka Miyasaka                $last_ope = end($ope_stack);
709865c2687SKazutaka Miyasaka            }
710865c2687SKazutaka Miyasaka            if ($token == ')') {
711865c2687SKazutaka Miyasaka                array_pop($ope_stack); // this array_pop always deletes '('
712865c2687SKazutaka Miyasaka            } else {
713865c2687SKazutaka Miyasaka                $ope_stack[] = $token;
714865c2687SKazutaka Miyasaka            }
715865c2687SKazutaka Miyasaka        } else {
716865c2687SKazutaka Miyasaka            // operand
717865c2687SKazutaka Miyasaka            $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token);
718865c2687SKazutaka Miyasaka            $parsed_ary[] = $token_decoded;
719865c2687SKazutaka Miyasaka        }
720865c2687SKazutaka Miyasaka    }
721865c2687SKazutaka Miyasaka    $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
722865c2687SKazutaka Miyasaka
723865c2687SKazutaka Miyasaka    // cleanup: each double "NOT" in RPN array actually does nothing
724865c2687SKazutaka Miyasaka    $parsed_ary_count = count($parsed_ary);
725865c2687SKazutaka Miyasaka    for ($i = 1; $i < $parsed_ary_count; ++$i) {
726865c2687SKazutaka Miyasaka        if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
727865c2687SKazutaka Miyasaka            unset($parsed_ary[$i], $parsed_ary[$i - 1]);
728865c2687SKazutaka Miyasaka        }
729865c2687SKazutaka Miyasaka    }
730865c2687SKazutaka Miyasaka    $parsed_ary = array_values($parsed_ary);
731865c2687SKazutaka Miyasaka
732865c2687SKazutaka Miyasaka    // build return value
733f5eb7cf0SAndreas Gohr    $q = array();
734f5eb7cf0SAndreas Gohr    $q['query']      = $query;
735865c2687SKazutaka Miyasaka    $q['parsed_str'] = $parsed_query;
736865c2687SKazutaka Miyasaka    $q['parsed_ary'] = $parsed_ary;
737f5eb7cf0SAndreas Gohr
738865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
739865c2687SKazutaka Miyasaka        if ($token[2] !== ':') continue;
740865c2687SKazutaka Miyasaka        $body = substr($token, 3);
741865c2687SKazutaka Miyasaka
742865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
7432f502d70SKazutaka Miyasaka            case 'N+:':
744865c2687SKazutaka Miyasaka                     $q['ns'][]        = $body; // for backward compatibility
745865c2687SKazutaka Miyasaka                     break;
7462f502d70SKazutaka Miyasaka            case 'N-:':
7472f502d70SKazutaka Miyasaka                     $q['notns'][]     = $body; // for backward compatibility
7482f502d70SKazutaka Miyasaka                     break;
7492f502d70SKazutaka Miyasaka            case 'W_:':
7502f502d70SKazutaka Miyasaka                     $q['words'][]     = $body;
7512f502d70SKazutaka Miyasaka                     break;
752865c2687SKazutaka Miyasaka            case 'W-:':
753865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
7542f502d70SKazutaka Miyasaka                     $q['not'][]       = $body; // for backward compatibility
755865c2687SKazutaka Miyasaka                     break;
756865c2687SKazutaka Miyasaka            case 'W+:':
757865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
7582237b4faSAndreas Gohr                     $q['highlight'][] = $body;
7592f502d70SKazutaka Miyasaka                     $q['and'][]       = $body; // for backward compatibility
760865c2687SKazutaka Miyasaka                     break;
7612f502d70SKazutaka Miyasaka            case 'P-:':
7622f502d70SKazutaka Miyasaka                     $q['phrases'][]   = $body;
7632f502d70SKazutaka Miyasaka                     break;
7642f502d70SKazutaka Miyasaka            case 'P+:':
765865c2687SKazutaka Miyasaka                     $q['phrases'][]   = $body;
7662237b4faSAndreas Gohr                     $q['highlight'][] = $body;
767865c2687SKazutaka Miyasaka                     break;
768865c2687SKazutaka Miyasaka        }
769865c2687SKazutaka Miyasaka    }
7702f502d70SKazutaka Miyasaka    foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) {
771865c2687SKazutaka Miyasaka        $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
772f5eb7cf0SAndreas Gohr    }
773f5eb7cf0SAndreas Gohr
774f5eb7cf0SAndreas Gohr    return $q;
775f5eb7cf0SAndreas Gohr}
776f5eb7cf0SAndreas Gohr
777865c2687SKazutaka Miyasaka/**
778865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation
779865c2687SKazutaka Miyasaka *
780865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use.
781865c2687SKazutaka Miyasaka *
782865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
78342ea7f44SGerrit Uitslag *
78442ea7f44SGerrit Uitslag * @param Doku_Indexer $Indexer
78542ea7f44SGerrit Uitslag * @param string       $term
78642ea7f44SGerrit Uitslag * @param bool         $consider_asian
78742ea7f44SGerrit Uitslag * @param bool         $phrase_mode
78842ea7f44SGerrit Uitslag * @return string
789865c2687SKazutaka Miyasaka */
7909b41be24STom N Harrisfunction ft_termParser($Indexer, $term, $consider_asian = true, $phrase_mode = false) {
791865c2687SKazutaka Miyasaka    $parsed = '';
792865c2687SKazutaka Miyasaka    if ($consider_asian) {
793865c2687SKazutaka Miyasaka        // successive asian characters need to be searched as a phrase
794865c2687SKazutaka Miyasaka        $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
795865c2687SKazutaka Miyasaka        foreach ($words as $word) {
7966ac2077aSKazutaka Miyasaka            $phrase_mode = $phrase_mode ? true : preg_match('/'.IDX_ASIAN.'/u', $word);
7979b41be24STom N Harris            $parsed .= ft_termParser($Indexer, $word, false, $phrase_mode);
798865c2687SKazutaka Miyasaka        }
799865c2687SKazutaka Miyasaka    } else {
800865c2687SKazutaka Miyasaka        $term_noparen = str_replace(array('(', ')'), ' ', $term);
8019b41be24STom N Harris        $words = $Indexer->tokenizer($term_noparen, true);
802865c2687SKazutaka Miyasaka
8032f502d70SKazutaka Miyasaka        // W_: no need to highlight
804865c2687SKazutaka Miyasaka        if (empty($words)) {
805865c2687SKazutaka Miyasaka            $parsed = '()'; // important: do not remove
806865c2687SKazutaka Miyasaka        } elseif ($words[0] === $term) {
807865c2687SKazutaka Miyasaka            $parsed = '(W+:'.$words[0].')';
808865c2687SKazutaka Miyasaka        } elseif ($phrase_mode) {
809865c2687SKazutaka Miyasaka            $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term);
8102f502d70SKazutaka Miyasaka            $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
811865c2687SKazutaka Miyasaka        } else {
812865c2687SKazutaka Miyasaka            $parsed = '((W+:'.implode(')(W+:', $words).'))';
813865c2687SKazutaka Miyasaka        }
814865c2687SKazutaka Miyasaka    }
815865c2687SKazutaka Miyasaka    return $parsed;
816865c2687SKazutaka Miyasaka}
817865c2687SKazutaka Miyasaka
81844156e11SMichael Große/**
81944156e11SMichael Große * Recreate a search query string based on parsed parts, doesn't support negated phrases and `OR` searches
82044156e11SMichael Große *
82144156e11SMichael Große * @param array $and
82244156e11SMichael Große * @param array $not
82344156e11SMichael Große * @param array $phrases
82444156e11SMichael Große * @param array $ns
82544156e11SMichael Große * @param array $notns
82644156e11SMichael Große *
82744156e11SMichael Große * @return string
82844156e11SMichael Große */
82944156e11SMichael Großefunction ft_queryUnparser_simple(array $and, array $not, array $phrases, array $ns, array $notns) {
83044156e11SMichael Große    $query = implode(' ', $and);
83144156e11SMichael Große    if (!empty($not)) {
83244156e11SMichael Große        $query .= ' -' . implode(' -', $not);
83344156e11SMichael Große    }
83444156e11SMichael Große
83544156e11SMichael Große    if (!empty($phrases)) {
83644156e11SMichael Große        $query .= ' "' . implode('" "', $phrases) . '"';
83744156e11SMichael Große    }
83844156e11SMichael Große
83944156e11SMichael Große    if (!empty($ns)) {
84044156e11SMichael Große        $query .= ' @' . implode(' @', $ns);
84144156e11SMichael Große    }
84244156e11SMichael Große
84344156e11SMichael Große    if (!empty($notns)) {
84444156e11SMichael Große        $query .= ' ^' . implode(' ^', $notns);
84544156e11SMichael Große    }
84644156e11SMichael Große
84744156e11SMichael Große    return $query;
84844156e11SMichael Große}
84944156e11SMichael Große
850e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 :
851