xref: /dokuwiki/inc/fulltext.php (revision 3be6e3945ae175b4785e18f9aa9d18f557592dd7)
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
9f5eb7cf0SAndreas Gohr  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
10f5eb7cf0SAndreas Gohr  require_once(DOKU_INC.'inc/indexer.php');
11f5eb7cf0SAndreas Gohr
12f5eb7cf0SAndreas Gohr
13f5eb7cf0SAndreas Gohr/**
14f5eb7cf0SAndreas Gohr * The fulltext search
15f5eb7cf0SAndreas Gohr *
16f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query
17506fa893SAndreas Gohr *
18f5eb7cf0SAndreas Gohr */
19506fa893SAndreas Gohrfunction ft_pageSearch($query,&$poswords){
20f5eb7cf0SAndreas Gohr    $q = ft_queryParser($query);
21506fa893SAndreas Gohr    // use this for higlighting later:
22ad81d431SAndreas Gohr    $poswords = str_replace('*','',join(' ',$q['and']));
23506fa893SAndreas Gohr
24f5eb7cf0SAndreas Gohr    // lookup all words found in the query
25f5eb7cf0SAndreas Gohr    $words  = array_merge($q['and'],$q['not']);
26f5eb7cf0SAndreas Gohr    if(!count($words)) return array();
27f5eb7cf0SAndreas Gohr    $result = idx_lookup($words);
28f5eb7cf0SAndreas Gohr
29f5eb7cf0SAndreas Gohr    // merge search results with query
30f5eb7cf0SAndreas Gohr    foreach($q['and'] as $pos => $w){
31f5eb7cf0SAndreas Gohr        $q['and'][$pos] = $result[$w];
32f5eb7cf0SAndreas Gohr    }
33f5eb7cf0SAndreas Gohr    // create a list of unwanted docs
34f5eb7cf0SAndreas Gohr    $not = array();
35f5eb7cf0SAndreas Gohr    foreach($q['not'] as $pos => $w){
36f5eb7cf0SAndreas Gohr        $not = array_merge($not,array_keys($result[$w]));
37f5eb7cf0SAndreas Gohr    }
38f5eb7cf0SAndreas Gohr
39506fa893SAndreas Gohr    // combine and-words
40f5eb7cf0SAndreas Gohr    if(count($q['and']) > 1){
41f5eb7cf0SAndreas Gohr        $docs = ft_resultCombine($q['and']);
42f5eb7cf0SAndreas Gohr    }else{
43f5eb7cf0SAndreas Gohr        $docs = $q['and'][0];
44f5eb7cf0SAndreas Gohr    }
45f5eb7cf0SAndreas Gohr    if(!count($docs)) return array();
46f5eb7cf0SAndreas Gohr
470dc92c6fSAndreas Gohr    // create a list of hidden pages in the result
480dc92c6fSAndreas Gohr    $hidden = array();
490dc92c6fSAndreas Gohr    $hidden = array_filter(array_keys($docs),'isHiddenPage');
500dc92c6fSAndreas Gohr    $not = array_merge($not,$hidden);
510dc92c6fSAndreas Gohr
52d0ab54f6SMichael Klier chi@chimeric.de    // filter unmatched namespaces
53d0ab54f6SMichael Klier chi@chimeric.de    if(!empty($q['ns'])) {
54a219c1f0SMichael Klier chi@chimeric.de        $pattern = implode('|^',$q['ns']);
55d0ab54f6SMichael Klier chi@chimeric.de        foreach($docs as $key => $val) {
56a219c1f0SMichael Klier chi@chimeric.de            if(!preg_match('/^'.$pattern.'/',$key)) {
57d0ab54f6SMichael Klier chi@chimeric.de                unset($docs[$key]);
58d0ab54f6SMichael Klier chi@chimeric.de            }
59d0ab54f6SMichael Klier chi@chimeric.de        }
60d0ab54f6SMichael Klier chi@chimeric.de    }
61d0ab54f6SMichael Klier chi@chimeric.de
62f5eb7cf0SAndreas Gohr    // remove negative matches
63f5eb7cf0SAndreas Gohr    foreach($not as $n){
64f5eb7cf0SAndreas Gohr        unset($docs[$n]);
65f5eb7cf0SAndreas Gohr    }
66f5eb7cf0SAndreas Gohr
67f5eb7cf0SAndreas Gohr    if(!count($docs)) return array();
68f5eb7cf0SAndreas Gohr    // handle phrases
69f5eb7cf0SAndreas Gohr    if(count($q['phrases'])){
70f5eb7cf0SAndreas Gohr        //build a regexp
71f5eb7cf0SAndreas Gohr        $q['phrases'] = array_map('utf8_strtolower',$q['phrases']);
72f5eb7cf0SAndreas Gohr        $q['phrases'] = array_map('preg_quote',$q['phrases']);
73f5eb7cf0SAndreas Gohr        $regex = '('.join('|',$q['phrases']).')';
74f5eb7cf0SAndreas Gohr        // check the source of all documents for the exact phrases
75f5eb7cf0SAndreas Gohr        foreach(array_keys($docs) as $id){
76f5eb7cf0SAndreas Gohr            $text  = utf8_strtolower(rawWiki($id));
77506fa893SAndreas Gohr            if(!preg_match('/'.$regex.'/usi',$text)){
78f5eb7cf0SAndreas Gohr                unset($docs[$id]); // no hit - remove
79f5eb7cf0SAndreas Gohr            }
80f5eb7cf0SAndreas Gohr        }
81f5eb7cf0SAndreas Gohr    }
82f5eb7cf0SAndreas Gohr
83f5eb7cf0SAndreas Gohr    if(!count($docs)) return array();
84f5eb7cf0SAndreas Gohr
8563773904SAndreas Gohr    // check ACL permissions
8663773904SAndreas Gohr    foreach(array_keys($docs) as $doc){
8763773904SAndreas Gohr        if(auth_quickaclcheck($doc) < AUTH_READ){
8863773904SAndreas Gohr            unset($docs[$doc]);
8963773904SAndreas Gohr        }
9063773904SAndreas Gohr    }
9163773904SAndreas Gohr
9263773904SAndreas Gohr    if(!count($docs)) return array();
9363773904SAndreas Gohr
94f5eb7cf0SAndreas Gohr    // if there are any hits left, sort them by count
95f5eb7cf0SAndreas Gohr    arsort($docs);
96f5eb7cf0SAndreas Gohr
97f5eb7cf0SAndreas Gohr    return $docs;
98f5eb7cf0SAndreas Gohr}
99f5eb7cf0SAndreas Gohr
100f5eb7cf0SAndreas Gohr/**
10154f4c056SAndreas Gohr * Returns the backlinks for a given page
10254f4c056SAndreas Gohr *
10354f4c056SAndreas Gohr * Does a quick lookup with the fulltext index, then
10454f4c056SAndreas Gohr * evaluates the instructions of the found pages
10554f4c056SAndreas Gohr */
10654f4c056SAndreas Gohrfunction ft_backlinks($id){
10754f4c056SAndreas Gohr    global $conf;
10854f4c056SAndreas Gohr    $result = array();
10954f4c056SAndreas Gohr
11054f4c056SAndreas Gohr    // quick lookup of the pagename
11154f4c056SAndreas Gohr    $page    = noNS($id);
1123cbaa9a4SAndreas Gohr    $sw      = array(); // we don't use stopwords here
1133cbaa9a4SAndreas Gohr    $matches = idx_lookup(idx_tokenizer($page,$sw));  // pagename may contain specials (_ or .)
1140dc92c6fSAndreas Gohr    $docs    = array_keys(ft_resultCombine(array_values($matches)));
1150dc92c6fSAndreas Gohr    $docs    = array_filter($docs,'isVisiblePage'); // discard hidden pages
1163cbaa9a4SAndreas Gohr    if(!count($docs)) return $result;
11754f4c056SAndreas Gohr    require_once(DOKU_INC.'inc/parserutils.php');
11854f4c056SAndreas Gohr
11954f4c056SAndreas Gohr    // check instructions for matching links
1200dc92c6fSAndreas Gohr    foreach($docs as $match){
121*3be6e394Schris/*
122*3be6e394Schris        // orig code, examine each page's instruction list
12354f4c056SAndreas Gohr        $instructions = p_cached_instructions(wikiFN($match),true);
12454f4c056SAndreas Gohr        if(is_null($instructions)) continue;
12554f4c056SAndreas Gohr
12654f4c056SAndreas Gohr        $match_ns =  getNS($match);
12754f4c056SAndreas Gohr
12854f4c056SAndreas Gohr        foreach($instructions as $ins){
12954f4c056SAndreas Gohr            if($ins[0] == 'internallink' || ($conf['camelcase'] && $ins[0] == 'camelcaselink') ){
13054f4c056SAndreas Gohr                $link = $ins[1][0];
13154f4c056SAndreas Gohr                resolve_pageid($match_ns,$link,$exists); //exists is not used
13254f4c056SAndreas Gohr                if($link == $id){
13354f4c056SAndreas Gohr                    //we have a match - finish
13454f4c056SAndreas Gohr                    $result[] = $match;
13554f4c056SAndreas Gohr                    break;
13654f4c056SAndreas Gohr                }
13754f4c056SAndreas Gohr            }
13854f4c056SAndreas Gohr        }
139*3be6e394Schris*/
140*3be6e394Schris// now with metadata
141*3be6e394Schris        $links = p_get_metadata($match,"relation references");
142*3be6e394Schris        if (isset($links[$id])) $result[] = $match;
14354f4c056SAndreas Gohr    }
14454f4c056SAndreas Gohr
14563773904SAndreas Gohr    if(!count($result)) return $result;
14663773904SAndreas Gohr
14763773904SAndreas Gohr    // check ACL permissions
14863773904SAndreas Gohr    foreach(array_keys($result) as $idx){
14963773904SAndreas Gohr        if(auth_quickaclcheck($result[$idx]) < AUTH_READ){
15063773904SAndreas Gohr            unset($result[$idx]);
15163773904SAndreas Gohr        }
15263773904SAndreas Gohr    }
15363773904SAndreas Gohr
15454f4c056SAndreas Gohr    sort($result);
15554f4c056SAndreas Gohr    return $result;
15654f4c056SAndreas Gohr}
15754f4c056SAndreas Gohr
15854f4c056SAndreas Gohr/**
159506fa893SAndreas Gohr * Quicksearch for pagenames
160506fa893SAndreas Gohr *
161506fa893SAndreas Gohr * By default it only matches the pagename and ignores the
162506fa893SAndreas Gohr * namespace. This can be changed with the second parameter
163506fa893SAndreas Gohr *
164506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
165506fa893SAndreas Gohr */
166506fa893SAndreas Gohrfunction ft_pageLookup($id,$pageonly=true){
167506fa893SAndreas Gohr    global $conf;
168506fa893SAndreas Gohr    $id    = preg_quote($id,'/');
169506fa893SAndreas Gohr    $pages = file($conf['cachedir'].'/page.idx');
170506fa893SAndreas Gohr    $pages = array_values(preg_grep('/'.$id.'/',$pages));
171506fa893SAndreas Gohr
172506fa893SAndreas Gohr    $cnt = count($pages);
173506fa893SAndreas Gohr    for($i=0; $i<$cnt; $i++){
174506fa893SAndreas Gohr        if($pageonly){
175506fa893SAndreas Gohr            if(!preg_match('/'.$id.'/',noNS($pages[$i]))){
176506fa893SAndreas Gohr                unset($pages[$i]);
177506fa893SAndreas Gohr                continue;
178506fa893SAndreas Gohr            }
179506fa893SAndreas Gohr        }
180506fa893SAndreas Gohr        if(!@file_exists(wikiFN($pages[$i]))){
181506fa893SAndreas Gohr            unset($pages[$i]);
182506fa893SAndreas Gohr            continue;
183506fa893SAndreas Gohr        }
184506fa893SAndreas Gohr    }
18563773904SAndreas Gohr
1860dc92c6fSAndreas Gohr    $pages = array_filter($pages,'isVisiblePage'); // discard hidden pages
18763773904SAndreas Gohr    if(!count($pages)) return array();
18863773904SAndreas Gohr
18963773904SAndreas Gohr    // check ACL permissions
19063773904SAndreas Gohr    foreach(array_keys($pages) as $idx){
19163773904SAndreas Gohr        if(auth_quickaclcheck($pages[$idx]) < AUTH_READ){
19263773904SAndreas Gohr            unset($pages[$idx]);
19363773904SAndreas Gohr        }
19463773904SAndreas Gohr    }
19563773904SAndreas Gohr
196506fa893SAndreas Gohr    sort($pages);
197506fa893SAndreas Gohr    return $pages;
198506fa893SAndreas Gohr}
199506fa893SAndreas Gohr
200506fa893SAndreas Gohr/**
201506fa893SAndreas Gohr * Creates a snippet extract
202506fa893SAndreas Gohr *
203506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
204506fa893SAndreas Gohr */
205506fa893SAndreas Gohrfunction ft_snippet($id,$poswords){
206506fa893SAndreas Gohr    $poswords = preg_quote($poswords,'#');
207506fa893SAndreas Gohr    $re       = '('.str_replace(' ','|',$poswords).')';
208506fa893SAndreas Gohr    $text     = rawWiki($id);
209bd2cb6fcSchris
210bd2cb6fcSchris// extra code to allow selection of search algorithm - remove before release
211bd2cb6fcSchrisglobal $conf;
212bd2cb6fcSchris$algorithm = '';
213bd2cb6fcSchrisif ($conf['allowdebug']) {
214bd2cb6fcSchris  if (!empty($_REQUEST['_search'])) $algorithm = $_REQUEST['_search'];
215bd2cb6fcSchris}
216bd2cb6fcSchris
217bd2cb6fcSchrisswitch ($algorithm) {
218bd2cb6fcSchris  case 'orig' :
219bd2cb6fcSchris// original code ... dokuwiki
220bd2cb6fcSchris
221506fa893SAndreas Gohr    //FIXME caseinsensitive matching doesn't work with UTF-8!?
222506fa893SAndreas Gohr    preg_match_all('#(.{0,50})'.$re.'(.{0,50})#iu',$text,$matches,PREG_SET_ORDER);
223506fa893SAndreas Gohr
224506fa893SAndreas Gohr    $cnt = 0;
225506fa893SAndreas Gohr    $snippet = '';
226506fa893SAndreas Gohr    foreach($matches as $match){
227506fa893SAndreas Gohr        $snippet .= '...'.htmlspecialchars($match[1]);
228506fa893SAndreas Gohr        $snippet .= '<span class="search_hit">';
229506fa893SAndreas Gohr        $snippet .= htmlspecialchars($match[2]);
230506fa893SAndreas Gohr        $snippet .= '</span>';
231506fa893SAndreas Gohr        $snippet .= htmlspecialchars($match[3]).'... ';
232506fa893SAndreas Gohr        if($cnt++ == 2) break;
233506fa893SAndreas Gohr    }
234506fa893SAndreas Gohr
235bd2cb6fcSchris  break;
236bd2cb6fcSchris
237bd2cb6fcSchris  case 'opt1' :
238bd2cb6fcSchris// my snippet algorithm, first cut ... CS 2006-08-25
239bd2cb6fcSchris// reduce the impact of the original regex
240bd2cb6fcSchris    $matches = array();
241bd2cb6fcSchris    preg_match_all('#'.$re.'#iu',$text,$matches,PREG_OFFSET_CAPTURE|PREG_SET_ORDER);
242bd2cb6fcSchris
243bd2cb6fcSchris    $cnt = 3;
244bd2cb6fcSchris    $snippets = array();
245bd2cb6fcSchris    $len = strlen($text);
246bd2cb6fcSchris    foreach ($matches as $match) {
247bd2cb6fcSchris      list($str,$idx) = $match[0];
248bd2cb6fcSchris      if ($idx < $end) continue;
249bd2cb6fcSchris
250bd2cb6fcSchris      $pre = min($idx,50);
251ced0762eSchris      $start = utf8_correctIdx($text, $idx - $pre);
252ced0762eSchris      $end = utf8_correctIdx($text, min($idx+100+strlen($str)-$pre,$len));
253bd2cb6fcSchris      $snippets[] = substr($text,$start,$end-$start);
25495a12943Schris      if (!($cnt--)) break;
255bd2cb6fcSchris    }
256bd2cb6fcSchris
257bd2cb6fcSchris    $m = "\1";
258bd2cb6fcSchris    $snippets = preg_replace('#'.$re.'#iu',$m.'$1'.$m,$snippets);
259bd2cb6fcSchris    $snippet = preg_replace('#'.$m.'([^'.$m.']*?)'.$m.'#iu','<span class="search_hit">$1</span>',hsc(join('... ',$snippets)));
260bd2cb6fcSchris
261bd2cb6fcSchris  break;
262bd2cb6fcSchris
263bd2cb6fcSchris  case 'opt2' :
264bd2cb6fcSchris// option 2 ... CS 2006-08-25
265bd2cb6fcSchris// above + reduce amount of the file searched
266bd2cb6fcSchris    $match = array();
267bd2cb6fcSchris    $snippets = array();
268bd2cb6fcSchris    $offset = 0;
269bd2cb6fcSchris    $len = strlen($text);
27095a12943Schris    for ($cnt=3; $cnt--;) {
271bd2cb6fcSchris      if (!preg_match('#'.$re.'#iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) break;
272bd2cb6fcSchris
273bd2cb6fcSchris      list($str,$idx) = $match[0];
274bd2cb6fcSchris
2755953e889Schris      // establish context, 100 bytes surrounding the match string
27695a12943Schris      // first look to see if we can go 100 either side,
2775953e889Schris      // then drop to 50 adding any excess if the other side can't go to 50,
2785953e889Schris      // NOTE: these are byte adjustments and will have to be corrected for utf-8
27995a12943Schris      $pre = min($idx-$offset,100);
28095a12943Schris      $post = min($len-$idx-strlen($str),100);
28195a12943Schris
28295a12943Schris      if ($pre>50 && $post>50) {
28395a12943Schris        $pre = $post = 50;
28495a12943Schris      } else if ($pre>50) {
28595a12943Schris        $pre = min($pre,100-$post);
28695a12943Schris      } else if ($post>50) {
28795a12943Schris        $post = min($post, 100-$pre);
288ced0762eSchris      } else {
289ced0762eSchris        // means both pre & post are less than 50, the context is the whole string
290ced0762eSchris        // make it so and break out of this loop - there is no need for the complex snippet calculations
291ced0762eSchris        $snippets = array($text);
292ced0762eSchris        break;
29395a12943Schris      }
29495a12943Schris
29595a12943Schris      // establish context start and end points, try to append to previous context if possible
2965953e889Schris      $start = utf8_correctIdx($text,$idx - $pre);
29795a12943Schris      $append = ($start < $end) ? $end : false;                     // still the end of the previous context snippet
2985953e889Schris      $end = utf8_correctIdx($text, $idx + strlen($str) + $post);   // now set it to the end of this context
29995a12943Schris
30095a12943Schris      if ($append) {
30195a12943Schris        $snippets[count($snippets)-1] .= substr($text,$append,$end-$append);
30295a12943Schris      } else {
303bd2cb6fcSchris        $snippets[] = substr($text,$start,$end-$start);
30495a12943Schris      }
30595a12943Schris
30695a12943Schris      // set $offset for next match attempt
30795a12943Schris      //   substract strlen to avoid splitting a potential search success, this is an approximation as the
30895a12943Schris      //   search pattern may match strings of varying length and it will fail if the context snippet
30995a12943Schris      //   boundary breaks a matching string longer than the current match
31095a12943Schris      $offset = $end - strlen($str);
311bd2cb6fcSchris    }
312bd2cb6fcSchris    $m = "\1";
313bd2cb6fcSchris    $snippets = preg_replace('#'.$re.'#iu',$m.'$1'.$m,$snippets);
314bd2cb6fcSchris    $snippet = preg_replace('#'.$m.'([^'.$m.']*?)'.$m.'#iu','<span class="search_hit">$1</span>',hsc(join('... ',$snippets)));
315bd2cb6fcSchris
316bd2cb6fcSchris  break;
317ced0762eSchris
318ced0762eSchris  case 'utf8':
3199ee93076Schris  default :
3209ee93076Schris
321ced0762eSchris    $match = array();
322ced0762eSchris    $snippets = array();
3239ee93076Schris    $utf8_offset = $offset = $end = 0;
324ced0762eSchris    $len = utf8_strlen($text);
3259ee93076Schris
326ced0762eSchris    for ($cnt=3; $cnt--;) {
327ced0762eSchris      if (!preg_match('#'.$re.'#iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) break;
328ced0762eSchris
329ced0762eSchris      list($str,$idx) = $match[0];
330ced0762eSchris
3319ee93076Schris      // is it ok to use utf8_substr() -- see bug #891,
3329ee93076Schris      //   check idx against (2^16)-1 - 400 (100x4 byte utf-8 characters)
3339ee93076Schris      if ($idx <= 65135) {
3349ee93076Schris
335ced0762eSchris      // convert $idx (a byte offset) into a utf8 character offset
336ced0762eSchris      $utf8_idx = utf8_strlen(substr($text,0,$idx));
337ced0762eSchris      $utf8_len = utf8_strlen($str);
338ced0762eSchris
339ced0762eSchris      // establish context, 100 bytes surrounding the match string
340ced0762eSchris      // first look to see if we can go 100 either side,
341ced0762eSchris      // then drop to 50 adding any excess if the other side can't go to 50,
342ced0762eSchris        $pre = min($utf8_idx-$utf8_offset,100);
343ced0762eSchris        $post = min($len-$utf8_idx-$utf8_len,100);
344ced0762eSchris
345ced0762eSchris        if ($pre>50 && $post>50) {
346ced0762eSchris          $pre = $post = 50;
347ced0762eSchris        } else if ($pre>50) {
348ced0762eSchris          $pre = min($pre,100-$post);
349ced0762eSchris        } else if ($post>50) {
350ced0762eSchris          $post = min($post, 100-$pre);
351ced0762eSchris        } else {
352ced0762eSchris          // both are less than 50, means the context is the whole string
353ced0762eSchris          // make it so and break out of this loop - there is no need for the complex snippet calculations
354ced0762eSchris          $snippets = array($text);
355ced0762eSchris          break;
356ced0762eSchris        }
357ced0762eSchris
358ced0762eSchris        // establish context start and end points, try to append to previous context if possible
3599ee93076Schris        $start = $utf8_idx - $pre;
360ced0762eSchris        $append = ($start < $end) ? $end : false;       // still the end of the previous context snippet
3619ee93076Schris        $end = $utf8_idx + $utf8_len + $post;           // now set it to the end of this context
362ced0762eSchris
363ced0762eSchris        if ($append) {
364ced0762eSchris          $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append);
365ced0762eSchris        } else {
366ced0762eSchris          $snippets[] = utf8_substr($text,$start,$end-$start);
367ced0762eSchris        }
368ced0762eSchris
369ced0762eSchris        // set $offset for next match attempt
370ced0762eSchris        //   substract strlen to avoid splitting a potential search success, this is an approximation as the
371ced0762eSchris        //   search pattern may match strings of varying length and it will fail if the context snippet
372ced0762eSchris        //   boundary breaks a matching string longer than the current match
3739ee93076Schris        $utf8_offset = $utf8_idx + $post;
3749ee93076Schris        $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$post));
3759ee93076Schris        $offset = utf8_correctIdx($text,$offset);
3769ee93076Schris      } else {
3779ee93076Schris        // code for strings too large for utf8_substr
3789ee93076Schris        // use a larger context number as its bytes not characters
3790e70946dSchris        // no need to check for short pre, $idx is nearly 64k
3809ee93076Schris        $post = min(strlen($text)-$idx-strlen($str), 70);
3810e70946dSchris        $pre = ($post < 70) ?  140 - $post : 70;
3829ee93076Schris
3839ee93076Schris        $start = utf8_correctIdx($text,$idx - $pre);
3849ee93076Schris        $end = utf8_correctIdx($text, $idx + strlen($str) + $post);
3859ee93076Schris
3869ee93076Schris        $snippets[] = substr($text,$start,$end-$start);
3879ee93076Schris        $offset = $end - strlen($str);
3889ee93076Schris      }
3899ee93076Schris
390ced0762eSchris    }
391ced0762eSchris    $m = "\1";
392ced0762eSchris    $snippets = preg_replace('#'.$re.'#iu',$m.'$1'.$m,$snippets);
393ced0762eSchris    $snippet = preg_replace('#'.$m.'([^'.$m.']*?)'.$m.'#iu','<span class="search_hit">$1</span>',hsc(join('... ',$snippets)));
394ced0762eSchris  break;
395bd2cb6fcSchris}
396bd2cb6fcSchris
3975953e889Schris    return $snippet;
398506fa893SAndreas Gohr}
399506fa893SAndreas Gohr
400506fa893SAndreas Gohr/**
401f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores
402f5eb7cf0SAndreas Gohr *
403f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical
404f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned.
405f5eb7cf0SAndreas Gohr *
406f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key()
407f5eb7cf0SAndreas Gohr *
408f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays
409f5eb7cf0SAndreas Gohr */
410f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){
411f5eb7cf0SAndreas Gohr    $array_count = count($args);
412134f4ab2SAndreas Gohr    if($array_count == 1){
413134f4ab2SAndreas Gohr        return $args[0];
414134f4ab2SAndreas Gohr    }
415134f4ab2SAndreas Gohr
416f5eb7cf0SAndreas Gohr    $result = array();
417f5eb7cf0SAndreas Gohr    foreach ($args[0] as $key1 => $value1) {
418f5eb7cf0SAndreas Gohr        for ($i = 1; $i !== $array_count; $i++) {
419f5eb7cf0SAndreas Gohr            foreach ($args[$i] as $key2 => $value2) {
420f5eb7cf0SAndreas Gohr                if ((string) $key1 === (string) $key2) {
421f5eb7cf0SAndreas Gohr                    if(!isset($result[$key1])) $result[$key1] = $value1;
422f5eb7cf0SAndreas Gohr                    $result[$key1] += $value2;
423f5eb7cf0SAndreas Gohr                }
424f5eb7cf0SAndreas Gohr            }
425f5eb7cf0SAndreas Gohr        }
426f5eb7cf0SAndreas Gohr    }
427f5eb7cf0SAndreas Gohr    return $result;
428f5eb7cf0SAndreas Gohr}
429f5eb7cf0SAndreas Gohr
430f5eb7cf0SAndreas Gohr/**
431f5eb7cf0SAndreas Gohr * Builds an array of search words from a query
432f5eb7cf0SAndreas Gohr *
433f5eb7cf0SAndreas Gohr * @todo support OR and parenthesises?
43493a60ad2SAndreas Gohr * @todo add namespace handling
435f5eb7cf0SAndreas Gohr */
436f5eb7cf0SAndreas Gohrfunction ft_queryParser($query){
437f5eb7cf0SAndreas Gohr    global $conf;
438f5eb7cf0SAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
439f5eb7cf0SAndreas Gohr    if(@file_exists($swfile)){
440f5eb7cf0SAndreas Gohr        $stopwords = file($swfile);
441f5eb7cf0SAndreas Gohr    }else{
442f5eb7cf0SAndreas Gohr        $stopwords = array();
443f5eb7cf0SAndreas Gohr    }
444f5eb7cf0SAndreas Gohr
445f5eb7cf0SAndreas Gohr    $q = array();
446f5eb7cf0SAndreas Gohr    $q['query']   = $query;
447a219c1f0SMichael Klier chi@chimeric.de    $q['ns']      = array();
448f5eb7cf0SAndreas Gohr    $q['phrases'] = array();
449f5eb7cf0SAndreas Gohr    $q['and']     = array();
450f5eb7cf0SAndreas Gohr    $q['not']     = array();
451f5eb7cf0SAndreas Gohr
452d0ab54f6SMichael Klier chi@chimeric.de    // strip namespace from query
453a219c1f0SMichael Klier chi@chimeric.de    if(preg_match('/([^@]*)@(.*)/',$query,$match))  {
454d0ab54f6SMichael Klier chi@chimeric.de        $query = $match[1];
455a219c1f0SMichael Klier chi@chimeric.de        $q['ns'] = explode('@',preg_replace("/ /",'',$match[2]));
456d0ab54f6SMichael Klier chi@chimeric.de    }
457d0ab54f6SMichael Klier chi@chimeric.de
458f5eb7cf0SAndreas Gohr    // handle phrase searches
459f5eb7cf0SAndreas Gohr    while(preg_match('/"(.*?)"/',$query,$match)){
46093a60ad2SAndreas Gohr        $q['phrases'][] = $match[1];
461f5eb7cf0SAndreas Gohr        $q['and'] = array_merge(idx_tokenizer($match[0],$stopwords));
462f5eb7cf0SAndreas Gohr        $query = preg_replace('/"(.*?)"/','',$query,1);
463f5eb7cf0SAndreas Gohr    }
464f5eb7cf0SAndreas Gohr
465f5eb7cf0SAndreas Gohr    $words = explode(' ',$query);
466f5eb7cf0SAndreas Gohr    foreach($words as $w){
467f5eb7cf0SAndreas Gohr        if($w{0} == '-'){
468ad81d431SAndreas Gohr            $token = idx_tokenizer($w,$stopwords,true);
469f5eb7cf0SAndreas Gohr            if(count($token)) $q['not'] = array_merge($q['not'],$token);
470f5eb7cf0SAndreas Gohr        }else{
47193a60ad2SAndreas Gohr            // asian "words" need to be searched as phrases
47291bb5faaSAndreas Gohr            if(@preg_match_all('/('.IDX_ASIAN.'+)/u',$w,$matches)){
47393a60ad2SAndreas Gohr                $q['phrases'] = array_merge($q['phrases'],$matches[1]);
47493a60ad2SAndreas Gohr
47593a60ad2SAndreas Gohr            }
476ad81d431SAndreas Gohr            $token = idx_tokenizer($w,$stopwords,true);
477f5eb7cf0SAndreas Gohr            if(count($token)) $q['and'] = array_merge($q['and'],$token);
478f5eb7cf0SAndreas Gohr        }
479f5eb7cf0SAndreas Gohr    }
480f5eb7cf0SAndreas Gohr
481f5eb7cf0SAndreas Gohr    return $q;
482f5eb7cf0SAndreas Gohr}
483f5eb7cf0SAndreas Gohr
484506fa893SAndreas Gohr//Setup VIM: ex: et ts=4 enc=utf-8 :
485