xref: /dokuwiki/inc/fulltext.php (revision e3776c06c37cc197709dac60892604dfea894ac2)
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 *
23f5eb7cf0SAndreas Gohr */
24546d3a99SAndreas Gohrfunction ft_pageSearch($query,&$highlight){
256840140fSChris Smith
266840140fSChris Smith    $data['query'] = $query;
276840140fSChris Smith    $data['highlight'] =& $highlight;
286840140fSChris Smith
296840140fSChris Smith    return trigger_event('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
306840140fSChris Smith}
31865c2687SKazutaka Miyasaka
32865c2687SKazutaka Miyasaka/**
33865c2687SKazutaka Miyasaka * Returns a list of matching documents for the given query
34865c2687SKazutaka Miyasaka *
35865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
36865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
37865c2687SKazutaka Miyasaka */
386840140fSChris Smithfunction _ft_pageSearch(&$data) {
39865c2687SKazutaka Miyasaka    // parse the given query
40865c2687SKazutaka Miyasaka    $q = ft_queryParser($data['query']);
41865c2687SKazutaka Miyasaka    $data['highlight'] = $q['highlight'];
426840140fSChris Smith
43865c2687SKazutaka Miyasaka    if (empty($q['parsed_ary'])) return array();
44506fa893SAndreas Gohr
45f5eb7cf0SAndreas Gohr    // lookup all words found in the query
46865c2687SKazutaka Miyasaka    $lookup = idx_lookup($q['words']);
47f5eb7cf0SAndreas Gohr
48865c2687SKazutaka Miyasaka    // get all pages in this dokuwiki site (!: includes nonexistent pages)
49865c2687SKazutaka Miyasaka    $pages_all = array();
50865c2687SKazutaka Miyasaka    foreach (idx_getIndex('page', '') as $id) {
51865c2687SKazutaka Miyasaka        $pages_all[trim($id)] = 0; // base: 0 hit
52f5eb7cf0SAndreas Gohr    }
53f5eb7cf0SAndreas Gohr
54865c2687SKazutaka Miyasaka    // process the query
55865c2687SKazutaka Miyasaka    $stack = array();
56865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
57865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
58865c2687SKazutaka Miyasaka            case 'W+:':
592f502d70SKazutaka Miyasaka            case 'W-:':
602f502d70SKazutaka Miyasaka            case 'W_:': // word
61865c2687SKazutaka Miyasaka                $word    = substr($token, 3);
62865c2687SKazutaka Miyasaka                $stack[] = (array) $lookup[$word];
63865c2687SKazutaka Miyasaka                break;
642f502d70SKazutaka Miyasaka            case 'P+:':
652f502d70SKazutaka Miyasaka            case 'P-:': // phrase
66865c2687SKazutaka Miyasaka                $phrase = substr($token, 3);
67865c2687SKazutaka Miyasaka                // since phrases are always parsed as ((W1)(W2)...(P)),
68865c2687SKazutaka Miyasaka                // the end($stack) always points the pages that contain
69865c2687SKazutaka Miyasaka                // all words in this phrase
70865c2687SKazutaka Miyasaka                $pages  = end($stack);
71865c2687SKazutaka Miyasaka                $pages_matched = array();
72865c2687SKazutaka Miyasaka                foreach(array_keys($pages) as $id){
73f5eb7cf0SAndreas Gohr                    $text = utf8_strtolower(rawWiki($id));
74865c2687SKazutaka Miyasaka                    if (strpos($text, $phrase) !== false) {
75865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // phrase: always 0 hit
76865c2687SKazutaka Miyasaka                    }
77865c2687SKazutaka Miyasaka                }
78865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
79865c2687SKazutaka Miyasaka                break;
802f502d70SKazutaka Miyasaka            case 'N+:':
812f502d70SKazutaka Miyasaka            case 'N-:': // namespace
82865c2687SKazutaka Miyasaka                $ns = substr($token, 3);
83865c2687SKazutaka Miyasaka                $pages_matched = array();
84865c2687SKazutaka Miyasaka                foreach (array_keys($pages_all) as $id) {
85865c2687SKazutaka Miyasaka                    if (strpos($id, $ns) === 0) {
86865c2687SKazutaka Miyasaka                        $pages_matched[$id] = 0; // namespace: always 0 hit
87865c2687SKazutaka Miyasaka                    }
88865c2687SKazutaka Miyasaka                }
89865c2687SKazutaka Miyasaka                $stack[] = $pages_matched;
90865c2687SKazutaka Miyasaka                break;
91865c2687SKazutaka Miyasaka            case 'AND': // and operation
92865c2687SKazutaka Miyasaka                list($pages1, $pages2) = array_splice($stack, -2);
93865c2687SKazutaka Miyasaka                $stack[] = ft_resultCombine(array($pages1, $pages2));
94865c2687SKazutaka Miyasaka                break;
95865c2687SKazutaka Miyasaka            case 'OR':  // or operation
96865c2687SKazutaka Miyasaka                list($pages1, $pages2) = array_splice($stack, -2);
97865c2687SKazutaka Miyasaka                $stack[] = ft_resultUnite(array($pages1, $pages2));
98865c2687SKazutaka Miyasaka                break;
99865c2687SKazutaka Miyasaka            case 'NOT': // not operation (unary)
100865c2687SKazutaka Miyasaka                $pages   = array_pop($stack);
101865c2687SKazutaka Miyasaka                $stack[] = ft_resultComplement(array($pages_all, $pages));
102a21136cdSAndreas Gohr                break;
103a21136cdSAndreas Gohr        }
104f5eb7cf0SAndreas Gohr    }
105865c2687SKazutaka Miyasaka    $docs = array_pop($stack);
106865c2687SKazutaka Miyasaka
107865c2687SKazutaka Miyasaka    if (empty($docs)) return array();
108865c2687SKazutaka Miyasaka
109865c2687SKazutaka Miyasaka    // check: settings, acls, existence
110865c2687SKazutaka Miyasaka    foreach (array_keys($docs) as $id) {
111865c2687SKazutaka Miyasaka        if (isHiddenPage($id) || auth_quickaclcheck($id) < AUTH_READ || !page_exists($id, '', false)) {
112865c2687SKazutaka Miyasaka            unset($docs[$id]);
113f5eb7cf0SAndreas Gohr        }
114f5eb7cf0SAndreas Gohr    }
115f5eb7cf0SAndreas Gohr
116865c2687SKazutaka Miyasaka    // sort docs by count
117f5eb7cf0SAndreas Gohr    arsort($docs);
118f5eb7cf0SAndreas Gohr
119f5eb7cf0SAndreas Gohr    return $docs;
120f5eb7cf0SAndreas Gohr}
121f5eb7cf0SAndreas Gohr
122f5eb7cf0SAndreas Gohr/**
12354f4c056SAndreas Gohr * Returns the backlinks for a given page
12454f4c056SAndreas Gohr *
12554f4c056SAndreas Gohr * Does a quick lookup with the fulltext index, then
12654f4c056SAndreas Gohr * evaluates the instructions of the found pages
12754f4c056SAndreas Gohr */
12854f4c056SAndreas Gohrfunction ft_backlinks($id){
12954f4c056SAndreas Gohr    global $conf;
1306b06b652Schris    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
1316b06b652Schris    $stopwords = @file_exists($swfile) ? file($swfile) : array();
1326b06b652Schris
13354f4c056SAndreas Gohr    $result = array();
13454f4c056SAndreas Gohr
13554f4c056SAndreas Gohr    // quick lookup of the pagename
13654f4c056SAndreas Gohr    $page    = noNS($id);
1376b06b652Schris    $matches = idx_lookup(idx_tokenizer($page,$stopwords));  // pagename may contain specials (_ or .)
1380dc92c6fSAndreas Gohr    $docs    = array_keys(ft_resultCombine(array_values($matches)));
1390dc92c6fSAndreas Gohr    $docs    = array_filter($docs,'isVisiblePage'); // discard hidden pages
1403cbaa9a4SAndreas Gohr    if(!count($docs)) return $result;
14154f4c056SAndreas Gohr
14210ffc9ddSAndreas Gohr    // check metadata for matching links
1430dc92c6fSAndreas Gohr    foreach($docs as $match){
14410ffc9ddSAndreas Gohr        // metadata relation reference links are already resolved
1456b06b652Schris        $links = p_get_metadata($match,'relation references');
1463be6e394Schris        if (isset($links[$id])) $result[] = $match;
14754f4c056SAndreas Gohr    }
14854f4c056SAndreas Gohr
14963773904SAndreas Gohr    if(!count($result)) return $result;
15063773904SAndreas Gohr
15163773904SAndreas Gohr    // check ACL permissions
15263773904SAndreas Gohr    foreach(array_keys($result) as $idx){
15363773904SAndreas Gohr        if(auth_quickaclcheck($result[$idx]) < AUTH_READ){
15463773904SAndreas Gohr            unset($result[$idx]);
15563773904SAndreas Gohr        }
15663773904SAndreas Gohr    }
15763773904SAndreas Gohr
15854f4c056SAndreas Gohr    sort($result);
15954f4c056SAndreas Gohr    return $result;
16054f4c056SAndreas Gohr}
16154f4c056SAndreas Gohr
16254f4c056SAndreas Gohr/**
163a05e297aSAndreas Gohr * Returns the pages that use a given media file
164a05e297aSAndreas Gohr *
165a05e297aSAndreas Gohr * Does a quick lookup with the fulltext index, then
166a05e297aSAndreas Gohr * evaluates the instructions of the found pages
167a05e297aSAndreas Gohr *
168a05e297aSAndreas Gohr * Aborts after $max found results
169a05e297aSAndreas Gohr */
170a05e297aSAndreas Gohrfunction ft_mediause($id,$max){
171a05e297aSAndreas Gohr    global $conf;
172a05e297aSAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
173a05e297aSAndreas Gohr    $stopwords = @file_exists($swfile) ? file($swfile) : array();
174a05e297aSAndreas Gohr
175a05e297aSAndreas Gohr    if(!$max) $max = 1; // need to find at least one
176a05e297aSAndreas Gohr
177a05e297aSAndreas Gohr    $result = array();
178a05e297aSAndreas Gohr
179a05e297aSAndreas Gohr    // quick lookup of the mediafile
180a05e297aSAndreas Gohr    $media   = noNS($id);
181a05e297aSAndreas Gohr    $matches = idx_lookup(idx_tokenizer($media,$stopwords));
182a05e297aSAndreas Gohr    $docs    = array_keys(ft_resultCombine(array_values($matches)));
183a05e297aSAndreas Gohr    if(!count($docs)) return $result;
184a05e297aSAndreas Gohr
185a05e297aSAndreas Gohr    // go through all found pages
186a05e297aSAndreas Gohr    $found = 0;
187a05e297aSAndreas Gohr    $pcre  = preg_quote($media,'/');
188a05e297aSAndreas Gohr    foreach($docs as $doc){
189a05e297aSAndreas Gohr        $ns = getNS($doc);
190a05e297aSAndreas Gohr        preg_match_all('/\{\{([^|}]*'.$pcre.'[^|}]*)(|[^}]+)?\}\}/i',rawWiki($doc),$matches);
191a05e297aSAndreas Gohr        foreach($matches[1] as $img){
192a05e297aSAndreas Gohr            $img = trim($img);
193a05e297aSAndreas Gohr            if(preg_match('/^https?:\/\//i',$img)) continue; // skip external images
194a05e297aSAndreas Gohr                list($img) = explode('?',$img);                  // remove any parameters
195a05e297aSAndreas Gohr            resolve_mediaid($ns,$img,$exists);               // resolve the possibly relative img
196a05e297aSAndreas Gohr
197a05e297aSAndreas Gohr            if($img == $id){                                 // we have a match
198a05e297aSAndreas Gohr                $result[] = $doc;
199a05e297aSAndreas Gohr                $found++;
200a05e297aSAndreas Gohr                break;
201a05e297aSAndreas Gohr            }
202a05e297aSAndreas Gohr        }
203a05e297aSAndreas Gohr        if($found >= $max) break;
204a05e297aSAndreas Gohr    }
205a05e297aSAndreas Gohr
206a05e297aSAndreas Gohr    sort($result);
207a05e297aSAndreas Gohr    return $result;
208a05e297aSAndreas Gohr}
209a05e297aSAndreas Gohr
210a05e297aSAndreas Gohr
211a05e297aSAndreas Gohr
212a05e297aSAndreas Gohr/**
213506fa893SAndreas Gohr * Quicksearch for pagenames
214506fa893SAndreas Gohr *
215506fa893SAndreas Gohr * By default it only matches the pagename and ignores the
21680423ab6SAdrian Lang * namespace. This can be changed with the second parameter.
21780423ab6SAdrian Lang * The third parameter allows to search in titles as well.
218506fa893SAndreas Gohr *
2198d22f1e9SAndreas Gohr * The function always returns titles as well
2206840140fSChris Smith *
2218d22f1e9SAndreas Gohr * @triggers SEARCH_QUERY_PAGELOOKUP
222506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
2238d22f1e9SAndreas Gohr * @author Adrian Lang <lang@cosmocode.de>
224506fa893SAndreas Gohr */
2258d22f1e9SAndreas Gohrfunction ft_pageLookup($id, $in_ns=false, $in_title=false){
2268d22f1e9SAndreas Gohr    $data = compact('id', 'in_ns', 'in_title');
2278d22f1e9SAndreas Gohr    $data['has_titles'] = true; // for plugin backward compatibility check
2286840140fSChris Smith    return trigger_event('SEARCH_QUERY_PAGELOOKUP', $data, '_ft_pageLookup');
2296840140fSChris Smith}
2306840140fSChris Smith
2316840140fSChris Smithfunction _ft_pageLookup(&$data){
2327f97a900SAndreas Gohr    global $conf;
23380423ab6SAdrian Lang    // split out original parameters
2346840140fSChris Smith    $id = $data['id'];
235b0f6db0cSAdrian Lang    if (preg_match('/(?:^| )@(\w+)/', $id, $matches)) {
236b0f6db0cSAdrian Lang        $ns = cleanID($matches[1]) . ':';
237b0f6db0cSAdrian Lang        $id = str_replace($matches[0], '', $id);
238b0f6db0cSAdrian Lang    }
239b0f6db0cSAdrian Lang
2408d22f1e9SAndreas Gohr    $in_ns    = $data['in_ns'];
2418d22f1e9SAndreas Gohr    $in_title = $data['in_title'];
2426840140fSChris Smith
243a0070b52SAdrian Lang    $pages  = array_map('rtrim', idx_getIndex('page', ''));
244a0070b52SAdrian Lang    $titles = array_map('rtrim', idx_getIndex('title', ''));
2454987233dSAndreas Gohr    // check for corrupt title index #FS2076
2464987233dSAndreas Gohr    if(count($pages) != count($titles)){
2474987233dSAndreas Gohr        $titles = array_fill(0,count($pages),'');
2484987233dSAndreas Gohr        @unlink($conf['indexdir'].'/title.idx'); // will be rebuilt in inc/init.php
2494987233dSAndreas Gohr    }
25080423ab6SAdrian Lang    $pages = array_combine($pages, $titles);
251506fa893SAndreas Gohr
25280423ab6SAdrian Lang    $cleaned = cleanID($id);
2535479a8c3SAndreas Gohr    if ($id !== '' && $cleaned !== '') {
25480423ab6SAdrian Lang        foreach ($pages as $p_id => $p_title) {
255d0bdf765SAdrian Lang            if ((strpos($in_ns ? $p_id : noNSorNS($p_id), $cleaned) === false) &&
2565479a8c3SAndreas Gohr                (!$in_title || (stripos($p_title, $id) === false)) ) {
257d0bdf765SAdrian Lang                unset($pages[$p_id]);
258506fa893SAndreas Gohr            }
259506fa893SAndreas Gohr        }
260d0bdf765SAdrian Lang    }
261d0bdf765SAdrian Lang    if (isset($ns)) {
262d0bdf765SAdrian Lang        foreach (array_keys($pages) as $p_id) {
263d0bdf765SAdrian Lang            if (strpos($p_id, $ns) !== 0) {
264d0bdf765SAdrian Lang                unset($pages[$p_id]);
265d0bdf765SAdrian Lang            }
266d0bdf765SAdrian Lang        }
267506fa893SAndreas Gohr    }
26863773904SAndreas Gohr
26980423ab6SAdrian Lang    // discard hidden pages
27080423ab6SAdrian Lang    // discard nonexistent pages
27163773904SAndreas Gohr    // check ACL permissions
27263773904SAndreas Gohr    foreach(array_keys($pages) as $idx){
27380423ab6SAdrian Lang        if(!isVisiblePage($idx) || !page_exists($idx) ||
27480423ab6SAdrian Lang           auth_quickaclcheck($idx) < AUTH_READ) {
27563773904SAndreas Gohr            unset($pages[$idx]);
27663773904SAndreas Gohr        }
27763773904SAndreas Gohr    }
27863773904SAndreas Gohr
2793d2017d9SAdrian Lang    uksort($pages,'ft_pagesorter');
2808d22f1e9SAndreas Gohr    return $pages;
281506fa893SAndreas Gohr}
282506fa893SAndreas Gohr
283506fa893SAndreas Gohr/**
284f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string
285f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy
286f31eb72bSAndreas Gohr * pages.
287f31eb72bSAndreas Gohr */
288f31eb72bSAndreas Gohrfunction ft_pagesorter($a, $b){
289f31eb72bSAndreas Gohr    $ac = count(explode(':',$a));
290f31eb72bSAndreas Gohr    $bc = count(explode(':',$b));
291f31eb72bSAndreas Gohr    if($ac < $bc){
292f31eb72bSAndreas Gohr        return -1;
293f31eb72bSAndreas Gohr    }elseif($ac > $bc){
294f31eb72bSAndreas Gohr        return 1;
295f31eb72bSAndreas Gohr    }
296f31eb72bSAndreas Gohr    return strcmp ($a,$b);
297f31eb72bSAndreas Gohr}
298f31eb72bSAndreas Gohr
299f31eb72bSAndreas Gohr/**
300506fa893SAndreas Gohr * Creates a snippet extract
301506fa893SAndreas Gohr *
302506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
30360e91a17SAndreas Gohr * @triggers FULLTEXT_SNIPPET_CREATE
304506fa893SAndreas Gohr */
305546d3a99SAndreas Gohrfunction ft_snippet($id,$highlight){
306506fa893SAndreas Gohr    $text = rawWiki($id);
30760e91a17SAndreas Gohr    $evdata = array(
30860e91a17SAndreas Gohr            'id'        => $id,
30960e91a17SAndreas Gohr            'text'      => &$text,
31060e91a17SAndreas Gohr            'highlight' => &$highlight,
31160e91a17SAndreas Gohr            'snippet'   => '',
31260e91a17SAndreas Gohr            );
31360e91a17SAndreas Gohr
31460e91a17SAndreas Gohr    $evt = new Doku_Event('FULLTEXT_SNIPPET_CREATE',$evdata);
31560e91a17SAndreas Gohr    if ($evt->advise_before()) {
316ced0762eSchris        $match = array();
317ced0762eSchris        $snippets = array();
3189ee93076Schris        $utf8_offset = $offset = $end = 0;
319ced0762eSchris        $len = utf8_strlen($text);
3209ee93076Schris
321546d3a99SAndreas Gohr        // build a regexp from the phrases to highlight
3222237b4faSAndreas Gohr        $re1 = '('.join('|',array_map('ft_snippet_re_preprocess', array_map('preg_quote_cb',array_filter((array) $highlight)))).')';
323b571ff2dSChuck Kollars        $re2 = "$re1.{0,75}(?!\\1)$re1";
324b571ff2dSChuck Kollars        $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
325546d3a99SAndreas Gohr
326b571ff2dSChuck Kollars        for ($cnt=4; $cnt--;) {
327b571ff2dSChuck Kollars            if (0) {
328b571ff2dSChuck Kollars            } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
329b571ff2dSChuck Kollars            } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
330b571ff2dSChuck Kollars            } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
331b571ff2dSChuck Kollars            } else {
332b571ff2dSChuck Kollars                break;
333b571ff2dSChuck Kollars            }
334ced0762eSchris
335ced0762eSchris            list($str,$idx) = $match[0];
336ced0762eSchris
337ced0762eSchris            // convert $idx (a byte offset) into a utf8 character offset
338ced0762eSchris            $utf8_idx = utf8_strlen(substr($text,0,$idx));
339ced0762eSchris            $utf8_len = utf8_strlen($str);
340ced0762eSchris
341ced0762eSchris            // establish context, 100 bytes surrounding the match string
342ced0762eSchris            // first look to see if we can go 100 either side,
343ced0762eSchris            // then drop to 50 adding any excess if the other side can't go to 50,
344ced0762eSchris            $pre = min($utf8_idx-$utf8_offset,100);
345ced0762eSchris            $post = min($len-$utf8_idx-$utf8_len,100);
346ced0762eSchris
347ced0762eSchris            if ($pre>50 && $post>50) {
348ced0762eSchris                $pre = $post = 50;
349ced0762eSchris            } else if ($pre>50) {
350ced0762eSchris                $pre = min($pre,100-$post);
351ced0762eSchris            } else if ($post>50) {
352ced0762eSchris                $post = min($post, 100-$pre);
353ced0762eSchris            } else {
354ced0762eSchris                // both are less than 50, means the context is the whole string
35510ffc9ddSAndreas Gohr                // make it so and break out of this loop - there is no need for the
35610ffc9ddSAndreas Gohr                // complex snippet calculations
357ced0762eSchris                $snippets = array($text);
358ced0762eSchris                break;
359ced0762eSchris            }
360ced0762eSchris
36110ffc9ddSAndreas Gohr            // establish context start and end points, try to append to previous
36210ffc9ddSAndreas Gohr            // context if possible
3639ee93076Schris            $start = $utf8_idx - $pre;
364ced0762eSchris            $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
3659ee93076Schris            $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
366ced0762eSchris
367ced0762eSchris            if ($append) {
368ced0762eSchris                $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append);
369ced0762eSchris            } else {
370ced0762eSchris                $snippets[] = utf8_substr($text,$start,$end-$start);
371ced0762eSchris            }
372ced0762eSchris
373ced0762eSchris            // set $offset for next match attempt
37410ffc9ddSAndreas Gohr            //   substract strlen to avoid splitting a potential search success,
37510ffc9ddSAndreas Gohr            //   this is an approximation as the search pattern may match strings
37610ffc9ddSAndreas Gohr            //   of varying length and it will fail if the context snippet
377ced0762eSchris            //   boundary breaks a matching string longer than the current match
3789ee93076Schris            $utf8_offset = $utf8_idx + $post;
3799ee93076Schris            $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$post));
3809ee93076Schris            $offset = utf8_correctIdx($text,$offset);
3819ee93076Schris        }
3829ee93076Schris
383ced0762eSchris        $m = "\1";
384b571ff2dSChuck Kollars        $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
385b571ff2dSChuck Kollars        $snippet = preg_replace('/'.$m.'([^'.$m.']*?)'.$m.'/iu','<strong class="search_hit">$1</strong>',hsc(join('... ',$snippets)));
386bd2cb6fcSchris
38760e91a17SAndreas Gohr        $evdata['snippet'] = $snippet;
38860e91a17SAndreas Gohr    }
38960e91a17SAndreas Gohr    $evt->advise_after();
39060e91a17SAndreas Gohr    unset($evt);
39160e91a17SAndreas Gohr
39260e91a17SAndreas Gohr    return $evdata['snippet'];
393506fa893SAndreas Gohr}
394506fa893SAndreas Gohr
395506fa893SAndreas Gohr/**
39626eb848cSGina Haeussge * Wraps a search term in regex boundary checks.
39726eb848cSGina Haeussge */
3982237b4faSAndreas Gohrfunction ft_snippet_re_preprocess($term) {
3992237b4faSAndreas Gohr    if(substr($term,0,2) == '\\*'){
4002237b4faSAndreas Gohr        $term = substr($term,2);
4012237b4faSAndreas Gohr    }else{
4022237b4faSAndreas Gohr        $term = '\b'.$term;
4032237b4faSAndreas Gohr    }
4042237b4faSAndreas Gohr
4052237b4faSAndreas Gohr    if(substr($term,-2,2) == '\\*'){
4062237b4faSAndreas Gohr        $term = substr($term,0,-2);
4072237b4faSAndreas Gohr    }else{
4082237b4faSAndreas Gohr        $term = $term.'\b';
4092237b4faSAndreas Gohr    }
4102237b4faSAndreas Gohr    return $term;
41126eb848cSGina Haeussge}
41226eb848cSGina Haeussge
41326eb848cSGina Haeussge/**
414f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores
415f5eb7cf0SAndreas Gohr *
416f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical
417f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned.
418f5eb7cf0SAndreas Gohr *
419f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key()
420f5eb7cf0SAndreas Gohr *
421f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays
422f5eb7cf0SAndreas Gohr */
423f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){
424f5eb7cf0SAndreas Gohr    $array_count = count($args);
425134f4ab2SAndreas Gohr    if($array_count == 1){
426134f4ab2SAndreas Gohr        return $args[0];
427134f4ab2SAndreas Gohr    }
428134f4ab2SAndreas Gohr
429f5eb7cf0SAndreas Gohr    $result = array();
43009c27a6dSGuy Brand    if ($array_count > 1) {
431a21136cdSAndreas Gohr        foreach ($args[0] as $key => $value) {
432a21136cdSAndreas Gohr            $result[$key] = $value;
433f5eb7cf0SAndreas Gohr            for ($i = 1; $i !== $array_count; $i++) {
434a21136cdSAndreas Gohr                if (!isset($args[$i][$key])) {
435a21136cdSAndreas Gohr                    unset($result[$key]);
436a21136cdSAndreas Gohr                    break;
437f5eb7cf0SAndreas Gohr                }
438a21136cdSAndreas Gohr                $result[$key] += $args[$i][$key];
439f5eb7cf0SAndreas Gohr            }
440f5eb7cf0SAndreas Gohr        }
44109c27a6dSGuy Brand    }
442f5eb7cf0SAndreas Gohr    return $result;
443f5eb7cf0SAndreas Gohr}
444f5eb7cf0SAndreas Gohr
445f5eb7cf0SAndreas Gohr/**
446865c2687SKazutaka Miyasaka * Unites found documents and sum up their scores
447f5eb7cf0SAndreas Gohr *
448865c2687SKazutaka Miyasaka * based upon ft_resultCombine() function
449865c2687SKazutaka Miyasaka *
450865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
451865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
452865c2687SKazutaka Miyasaka */
453865c2687SKazutaka Miyasakafunction ft_resultUnite($args) {
454865c2687SKazutaka Miyasaka    $array_count = count($args);
455865c2687SKazutaka Miyasaka    if ($array_count === 1) {
456865c2687SKazutaka Miyasaka        return $args[0];
457865c2687SKazutaka Miyasaka    }
458865c2687SKazutaka Miyasaka
459865c2687SKazutaka Miyasaka    $result = $args[0];
460865c2687SKazutaka Miyasaka    for ($i = 1; $i !== $array_count; $i++) {
461865c2687SKazutaka Miyasaka        foreach (array_keys($args[$i]) as $id) {
462865c2687SKazutaka Miyasaka            $result[$id] += $args[$i][$id];
463865c2687SKazutaka Miyasaka        }
464865c2687SKazutaka Miyasaka    }
465865c2687SKazutaka Miyasaka    return $result;
466865c2687SKazutaka Miyasaka}
467865c2687SKazutaka Miyasaka
468865c2687SKazutaka Miyasaka/**
469865c2687SKazutaka Miyasaka * Computes the difference of documents using page id for comparison
470865c2687SKazutaka Miyasaka *
471865c2687SKazutaka Miyasaka * nearly identical to PHP5's array_diff_key()
472865c2687SKazutaka Miyasaka *
473865c2687SKazutaka Miyasaka * @param array $args An array of page arrays
474865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
475865c2687SKazutaka Miyasaka */
476865c2687SKazutaka Miyasakafunction ft_resultComplement($args) {
477865c2687SKazutaka Miyasaka    $array_count = count($args);
478865c2687SKazutaka Miyasaka    if ($array_count === 1) {
479865c2687SKazutaka Miyasaka        return $args[0];
480865c2687SKazutaka Miyasaka    }
481865c2687SKazutaka Miyasaka
482865c2687SKazutaka Miyasaka    $result = $args[0];
483865c2687SKazutaka Miyasaka    foreach (array_keys($result) as $id) {
484865c2687SKazutaka Miyasaka        for ($i = 1; $i !== $array_count; $i++) {
485865c2687SKazutaka Miyasaka            if (isset($args[$i][$id])) unset($result[$id]);
486865c2687SKazutaka Miyasaka        }
487865c2687SKazutaka Miyasaka    }
488865c2687SKazutaka Miyasaka    return $result;
489865c2687SKazutaka Miyasaka}
490865c2687SKazutaka Miyasaka
491865c2687SKazutaka Miyasaka/**
492865c2687SKazutaka Miyasaka * Parses a search query and builds an array of search formulas
493865c2687SKazutaka Miyasaka *
494865c2687SKazutaka Miyasaka * @author Andreas Gohr <andi@splitbrain.org>
495865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
496f5eb7cf0SAndreas Gohr */
497f5eb7cf0SAndreas Gohrfunction ft_queryParser($query){
498f5eb7cf0SAndreas Gohr    global $conf;
499f5eb7cf0SAndreas Gohr    $swfile    = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
500865c2687SKazutaka Miyasaka    $stopwords = @file_exists($swfile) ? file($swfile) : array();
501865c2687SKazutaka Miyasaka
502865c2687SKazutaka Miyasaka    /**
503865c2687SKazutaka Miyasaka     * parse a search query and transform it into intermediate representation
504865c2687SKazutaka Miyasaka     *
505865c2687SKazutaka Miyasaka     * in a search query, you can use the following expressions:
506865c2687SKazutaka Miyasaka     *
507865c2687SKazutaka Miyasaka     *   words:
508865c2687SKazutaka Miyasaka     *     include
509865c2687SKazutaka Miyasaka     *     -exclude
510865c2687SKazutaka Miyasaka     *   phrases:
511865c2687SKazutaka Miyasaka     *     "phrase to be included"
512865c2687SKazutaka Miyasaka     *     -"phrase you want to exclude"
513865c2687SKazutaka Miyasaka     *   namespaces:
514865c2687SKazutaka Miyasaka     *     @include:namespace (or ns:include:namespace)
515865c2687SKazutaka Miyasaka     *     ^exclude:namespace (or -ns:exclude:namespace)
516865c2687SKazutaka Miyasaka     *   groups:
517865c2687SKazutaka Miyasaka     *     ()
518865c2687SKazutaka Miyasaka     *     -()
519865c2687SKazutaka Miyasaka     *   operators:
520865c2687SKazutaka Miyasaka     *     and ('and' is the default operator: you can always omit this)
5217871d415SKazutaka Miyasaka     *     or  (or pipe symbol '|', lower precedence than 'and')
522865c2687SKazutaka Miyasaka     *
523865c2687SKazutaka Miyasaka     * e.g. a query [ aa "bb cc" @dd:ee ] means "search pages which contain
524865c2687SKazutaka Miyasaka     *      a word 'aa', a phrase 'bb cc' and are within a namespace 'dd:ee'".
525865c2687SKazutaka Miyasaka     *      this query is equivalent to [ -(-aa or -"bb cc" or -ns:dd:ee) ]
526865c2687SKazutaka Miyasaka     *      as long as you don't mind hit counts.
527865c2687SKazutaka Miyasaka     *
528865c2687SKazutaka Miyasaka     * intermediate representation consists of the following parts:
529865c2687SKazutaka Miyasaka     *
530865c2687SKazutaka Miyasaka     *   ( )           - group
531865c2687SKazutaka Miyasaka     *   AND           - logical and
532865c2687SKazutaka Miyasaka     *   OR            - logical or
533865c2687SKazutaka Miyasaka     *   NOT           - logical not
5342f502d70SKazutaka Miyasaka     *   W+:, W-:, W_: - word      (underscore: no need to highlight)
5352f502d70SKazutaka Miyasaka     *   P+:, P-:      - phrase    (minus sign: logically in NOT group)
5362f502d70SKazutaka Miyasaka     *   N+:, N-:      - namespace
537865c2687SKazutaka Miyasaka     */
538865c2687SKazutaka Miyasaka    $parsed_query = '';
539865c2687SKazutaka Miyasaka    $parens_level = 0;
540865c2687SKazutaka Miyasaka    $terms = preg_split('/(-?".*?")/u', utf8_strtolower($query), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
541865c2687SKazutaka Miyasaka
542865c2687SKazutaka Miyasaka    foreach ($terms as $term) {
543865c2687SKazutaka Miyasaka        $parsed = '';
544865c2687SKazutaka Miyasaka        if (preg_match('/^(-?)"(.+)"$/u', $term, $matches)) {
545865c2687SKazutaka Miyasaka            // phrase-include and phrase-exclude
546865c2687SKazutaka Miyasaka            $not = $matches[1] ? 'NOT' : '';
547865c2687SKazutaka Miyasaka            $parsed = $not.ft_termParser($matches[2], $stopwords, false, true);
548f5eb7cf0SAndreas Gohr        } else {
549865c2687SKazutaka Miyasaka            // fix incomplete phrase
550865c2687SKazutaka Miyasaka            $term = str_replace('"', ' ', $term);
551865c2687SKazutaka Miyasaka
552865c2687SKazutaka Miyasaka            // fix parentheses
553865c2687SKazutaka Miyasaka            $term = str_replace(')'  , ' ) ', $term);
554865c2687SKazutaka Miyasaka            $term = str_replace('('  , ' ( ', $term);
555865c2687SKazutaka Miyasaka            $term = str_replace('- (', ' -(', $term);
556865c2687SKazutaka Miyasaka
5577871d415SKazutaka Miyasaka            // treat pipe symbols as 'OR' operators
5587871d415SKazutaka Miyasaka            $term = str_replace('|', ' or ', $term);
5597871d415SKazutaka Miyasaka
560865c2687SKazutaka Miyasaka            // treat ideographic spaces (U+3000) as search term separators
561865c2687SKazutaka Miyasaka            // FIXME: some more separators?
562865c2687SKazutaka Miyasaka            $term = preg_replace('/[ \x{3000}]+/u', ' ',  $term);
563865c2687SKazutaka Miyasaka            $term = trim($term);
564865c2687SKazutaka Miyasaka            if ($term === '') continue;
565865c2687SKazutaka Miyasaka
566865c2687SKazutaka Miyasaka            $tokens = explode(' ', $term);
567865c2687SKazutaka Miyasaka            foreach ($tokens as $token) {
568865c2687SKazutaka Miyasaka                if ($token === '(') {
569865c2687SKazutaka Miyasaka                    // parenthesis-include-open
570865c2687SKazutaka Miyasaka                    $parsed .= '(';
571865c2687SKazutaka Miyasaka                    ++$parens_level;
572865c2687SKazutaka Miyasaka                } elseif ($token === '-(') {
573865c2687SKazutaka Miyasaka                    // parenthesis-exclude-open
574865c2687SKazutaka Miyasaka                    $parsed .= 'NOT(';
575865c2687SKazutaka Miyasaka                    ++$parens_level;
576865c2687SKazutaka Miyasaka                } elseif ($token === ')') {
577865c2687SKazutaka Miyasaka                    // parenthesis-any-close
578865c2687SKazutaka Miyasaka                    if ($parens_level === 0) continue;
579865c2687SKazutaka Miyasaka                    $parsed .= ')';
580865c2687SKazutaka Miyasaka                    $parens_level--;
581865c2687SKazutaka Miyasaka                } elseif ($token === 'and') {
582865c2687SKazutaka Miyasaka                    // logical-and (do nothing)
583865c2687SKazutaka Miyasaka                } elseif ($token === 'or') {
584865c2687SKazutaka Miyasaka                    // logical-or
585865c2687SKazutaka Miyasaka                    $parsed .= 'OR';
586865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:\^|-ns:)(.+)$/u', $token, $matches)) {
587865c2687SKazutaka Miyasaka                    // namespace-exclude
5882f502d70SKazutaka Miyasaka                    $parsed .= 'NOT(N+:'.$matches[1].')';
589865c2687SKazutaka Miyasaka                } elseif (preg_match('/^(?:@|ns:)(.+)$/u', $token, $matches)) {
590865c2687SKazutaka Miyasaka                    // namespace-include
5912f502d70SKazutaka Miyasaka                    $parsed .= '(N+:'.$matches[1].')';
592865c2687SKazutaka Miyasaka                } elseif (preg_match('/^-(.+)$/', $token, $matches)) {
593865c2687SKazutaka Miyasaka                    // word-exclude
594865c2687SKazutaka Miyasaka                    $parsed .= 'NOT('.ft_termParser($matches[1], $stopwords).')';
595865c2687SKazutaka Miyasaka                } else {
596865c2687SKazutaka Miyasaka                    // word-include
597865c2687SKazutaka Miyasaka                    $parsed .= ft_termParser($token, $stopwords);
598865c2687SKazutaka Miyasaka                }
599865c2687SKazutaka Miyasaka            }
600865c2687SKazutaka Miyasaka        }
601865c2687SKazutaka Miyasaka        $parsed_query .= $parsed;
602f5eb7cf0SAndreas Gohr    }
603f5eb7cf0SAndreas Gohr
604865c2687SKazutaka Miyasaka    // cleanup (very sensitive)
605865c2687SKazutaka Miyasaka    $parsed_query .= str_repeat(')', $parens_level);
606865c2687SKazutaka Miyasaka    do {
607865c2687SKazutaka Miyasaka        $parsed_query_old = $parsed_query;
608865c2687SKazutaka Miyasaka        $parsed_query = preg_replace('/(NOT)?\(\)/u', '', $parsed_query);
609865c2687SKazutaka Miyasaka    } while ($parsed_query !== $parsed_query_old);
610865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(NOT|OR)+\)/u', ')'      , $parsed_query);
611865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/(OR)+/u'      , 'OR'     , $parsed_query);
612865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\(OR/u'       , '('      , $parsed_query);
613865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/^OR|OR$/u'    , ''       , $parsed_query);
614865c2687SKazutaka Miyasaka    $parsed_query = preg_replace('/\)(NOT)?\(/u' , ')AND$1(', $parsed_query);
615865c2687SKazutaka Miyasaka
6162f502d70SKazutaka Miyasaka    // adjustment: make highlightings right
6172f502d70SKazutaka Miyasaka    $parens_level     = 0;
6182f502d70SKazutaka Miyasaka    $notgrp_levels    = array();
6192f502d70SKazutaka Miyasaka    $parsed_query_new = '';
6202f502d70SKazutaka Miyasaka    $tokens = preg_split('/(NOT\(|[()])/u', $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
6212f502d70SKazutaka Miyasaka    foreach ($tokens as $token) {
6222f502d70SKazutaka Miyasaka        if ($token === 'NOT(') {
6232f502d70SKazutaka Miyasaka            $notgrp_levels[] = ++$parens_level;
6242f502d70SKazutaka Miyasaka        } elseif ($token === '(') {
6252f502d70SKazutaka Miyasaka            ++$parens_level;
6262f502d70SKazutaka Miyasaka        } elseif ($token === ')') {
6272f502d70SKazutaka Miyasaka            if ($parens_level-- === end($notgrp_levels)) array_pop($notgrp_levels);
6282f502d70SKazutaka Miyasaka        } elseif (count($notgrp_levels) % 2 === 1) {
6292f502d70SKazutaka Miyasaka            // turn highlight-flag off if terms are logically in "NOT" group
6302f502d70SKazutaka Miyasaka            $token = preg_replace('/([WPN])\+\:/u', '$1-:', $token);
6312f502d70SKazutaka Miyasaka        }
6322f502d70SKazutaka Miyasaka        $parsed_query_new .= $token;
6332f502d70SKazutaka Miyasaka    }
6342f502d70SKazutaka Miyasaka    $parsed_query = $parsed_query_new;
6352f502d70SKazutaka Miyasaka
636865c2687SKazutaka Miyasaka    /**
637865c2687SKazutaka Miyasaka     * convert infix notation string into postfix (Reverse Polish notation) array
638865c2687SKazutaka Miyasaka     * by Shunting-yard algorithm
639865c2687SKazutaka Miyasaka     *
640865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Reverse_Polish_notation
641865c2687SKazutaka Miyasaka     * see: http://en.wikipedia.org/wiki/Shunting-yard_algorithm
642865c2687SKazutaka Miyasaka     */
643865c2687SKazutaka Miyasaka    $parsed_ary     = array();
644865c2687SKazutaka Miyasaka    $ope_stack      = array();
645865c2687SKazutaka Miyasaka    $ope_precedence = array(')' => 1, 'OR' => 2, 'AND' => 3, 'NOT' => 4, '(' => 5);
646865c2687SKazutaka Miyasaka    $ope_regex      = '/([()]|OR|AND|NOT)/u';
647865c2687SKazutaka Miyasaka
648865c2687SKazutaka Miyasaka    $tokens = preg_split($ope_regex, $parsed_query, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
649865c2687SKazutaka Miyasaka    foreach ($tokens as $token) {
650865c2687SKazutaka Miyasaka        if (preg_match($ope_regex, $token)) {
651865c2687SKazutaka Miyasaka            // operator
652865c2687SKazutaka Miyasaka            $last_ope = end($ope_stack);
653865c2687SKazutaka Miyasaka            while ($ope_precedence[$token] <= $ope_precedence[$last_ope] && $last_ope != '(') {
654865c2687SKazutaka Miyasaka                $parsed_ary[] = array_pop($ope_stack);
655865c2687SKazutaka Miyasaka                $last_ope = end($ope_stack);
656865c2687SKazutaka Miyasaka            }
657865c2687SKazutaka Miyasaka            if ($token == ')') {
658865c2687SKazutaka Miyasaka                array_pop($ope_stack); // this array_pop always deletes '('
659865c2687SKazutaka Miyasaka            } else {
660865c2687SKazutaka Miyasaka                $ope_stack[] = $token;
661865c2687SKazutaka Miyasaka            }
662865c2687SKazutaka Miyasaka        } else {
663865c2687SKazutaka Miyasaka            // operand
664865c2687SKazutaka Miyasaka            $token_decoded = str_replace(array('OP', 'CP'), array('(', ')'), $token);
665865c2687SKazutaka Miyasaka            $parsed_ary[] = $token_decoded;
666865c2687SKazutaka Miyasaka        }
667865c2687SKazutaka Miyasaka    }
668865c2687SKazutaka Miyasaka    $parsed_ary = array_values(array_merge($parsed_ary, array_reverse($ope_stack)));
669865c2687SKazutaka Miyasaka
670865c2687SKazutaka Miyasaka    // cleanup: each double "NOT" in RPN array actually does nothing
671865c2687SKazutaka Miyasaka    $parsed_ary_count = count($parsed_ary);
672865c2687SKazutaka Miyasaka    for ($i = 1; $i < $parsed_ary_count; ++$i) {
673865c2687SKazutaka Miyasaka        if ($parsed_ary[$i] === 'NOT' && $parsed_ary[$i - 1] === 'NOT') {
674865c2687SKazutaka Miyasaka            unset($parsed_ary[$i], $parsed_ary[$i - 1]);
675865c2687SKazutaka Miyasaka        }
676865c2687SKazutaka Miyasaka    }
677865c2687SKazutaka Miyasaka    $parsed_ary = array_values($parsed_ary);
678865c2687SKazutaka Miyasaka
679865c2687SKazutaka Miyasaka    // build return value
680f5eb7cf0SAndreas Gohr    $q = array();
681f5eb7cf0SAndreas Gohr    $q['query']      = $query;
682865c2687SKazutaka Miyasaka    $q['parsed_str'] = $parsed_query;
683865c2687SKazutaka Miyasaka    $q['parsed_ary'] = $parsed_ary;
684f5eb7cf0SAndreas Gohr
685865c2687SKazutaka Miyasaka    foreach ($q['parsed_ary'] as $token) {
686865c2687SKazutaka Miyasaka        if ($token[2] !== ':') continue;
687865c2687SKazutaka Miyasaka        $body = substr($token, 3);
688865c2687SKazutaka Miyasaka
689865c2687SKazutaka Miyasaka        switch (substr($token, 0, 3)) {
6902f502d70SKazutaka Miyasaka            case 'N+:':
691865c2687SKazutaka Miyasaka                     $q['ns'][]        = $body; // for backward compatibility
692865c2687SKazutaka Miyasaka                     break;
6932f502d70SKazutaka Miyasaka            case 'N-:':
6942f502d70SKazutaka Miyasaka                     $q['notns'][]     = $body; // for backward compatibility
6952f502d70SKazutaka Miyasaka                     break;
6962f502d70SKazutaka Miyasaka            case 'W_:':
6972f502d70SKazutaka Miyasaka                     $q['words'][]     = $body;
6982f502d70SKazutaka Miyasaka                     break;
699865c2687SKazutaka Miyasaka            case 'W-:':
700865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
7012f502d70SKazutaka Miyasaka                     $q['not'][]       = $body; // for backward compatibility
702865c2687SKazutaka Miyasaka                     break;
703865c2687SKazutaka Miyasaka            case 'W+:':
704865c2687SKazutaka Miyasaka                     $q['words'][]     = $body;
7052237b4faSAndreas Gohr                     $q['highlight'][] = $body;
7062f502d70SKazutaka Miyasaka                     $q['and'][]       = $body; // for backward compatibility
707865c2687SKazutaka Miyasaka                     break;
7082f502d70SKazutaka Miyasaka            case 'P-:':
7092f502d70SKazutaka Miyasaka                     $q['phrases'][]   = $body;
7102f502d70SKazutaka Miyasaka                     break;
7112f502d70SKazutaka Miyasaka            case 'P+:':
712865c2687SKazutaka Miyasaka                     $q['phrases'][]   = $body;
7132237b4faSAndreas Gohr                     $q['highlight'][] = $body;
714865c2687SKazutaka Miyasaka                     break;
715865c2687SKazutaka Miyasaka        }
716865c2687SKazutaka Miyasaka    }
7172f502d70SKazutaka Miyasaka    foreach (array('words', 'phrases', 'highlight', 'ns', 'notns', 'and', 'not') as $key) {
718865c2687SKazutaka Miyasaka        $q[$key] = empty($q[$key]) ? array() : array_values(array_unique($q[$key]));
719f5eb7cf0SAndreas Gohr    }
720f5eb7cf0SAndreas Gohr
721f5eb7cf0SAndreas Gohr    return $q;
722f5eb7cf0SAndreas Gohr}
723f5eb7cf0SAndreas Gohr
724865c2687SKazutaka Miyasaka/**
725865c2687SKazutaka Miyasaka * Transforms given search term into intermediate representation
726865c2687SKazutaka Miyasaka *
727865c2687SKazutaka Miyasaka * This function is used in ft_queryParser() and not for general purpose use.
728865c2687SKazutaka Miyasaka *
729865c2687SKazutaka Miyasaka * @author Kazutaka Miyasaka <kazmiya@gmail.com>
730865c2687SKazutaka Miyasaka */
731865c2687SKazutaka Miyasakafunction ft_termParser($term, &$stopwords, $consider_asian = true, $phrase_mode = false) {
732865c2687SKazutaka Miyasaka    $parsed = '';
733865c2687SKazutaka Miyasaka    if ($consider_asian) {
734865c2687SKazutaka Miyasaka        // successive asian characters need to be searched as a phrase
735865c2687SKazutaka Miyasaka        $words = preg_split('/('.IDX_ASIAN.'+)/u', $term, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
736865c2687SKazutaka Miyasaka        foreach ($words as $word) {
737865c2687SKazutaka Miyasaka            if (preg_match('/'.IDX_ASIAN.'/u', $word)) $phrase_mode = true;
738865c2687SKazutaka Miyasaka            $parsed .= ft_termParser($word, $stopwords, false, $phrase_mode);
739865c2687SKazutaka Miyasaka        }
740865c2687SKazutaka Miyasaka    } else {
741865c2687SKazutaka Miyasaka        $term_noparen = str_replace(array('(', ')'), ' ', $term);
742865c2687SKazutaka Miyasaka        $words = idx_tokenizer($term_noparen, $stopwords, true);
743865c2687SKazutaka Miyasaka
7442f502d70SKazutaka Miyasaka        // W_: no need to highlight
745865c2687SKazutaka Miyasaka        if (empty($words)) {
746865c2687SKazutaka Miyasaka            $parsed = '()'; // important: do not remove
747865c2687SKazutaka Miyasaka        } elseif ($words[0] === $term) {
748865c2687SKazutaka Miyasaka            $parsed = '(W+:'.$words[0].')';
749865c2687SKazutaka Miyasaka        } elseif ($phrase_mode) {
750865c2687SKazutaka Miyasaka            $term_encoded = str_replace(array('(', ')'), array('OP', 'CP'), $term);
7512f502d70SKazutaka Miyasaka            $parsed = '((W_:'.implode(')(W_:', $words).')(P+:'.$term_encoded.'))';
752865c2687SKazutaka Miyasaka        } else {
753865c2687SKazutaka Miyasaka            $parsed = '((W+:'.implode(')(W+:', $words).'))';
754865c2687SKazutaka Miyasaka        }
755865c2687SKazutaka Miyasaka    }
756865c2687SKazutaka Miyasaka    return $parsed;
757865c2687SKazutaka Miyasaka}
758865c2687SKazutaka Miyasaka
759*e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 :
760