xref: /dokuwiki/inc/fulltext.php (revision 009768124df70258806ec3120189432d1b2bb912)
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
9*00976812SAndreas Gohr  if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
10f5eb7cf0SAndreas Gohr  require_once(DOKU_INC.'inc/indexer.php');
11f5eb7cf0SAndreas Gohr
12f5eb7cf0SAndreas Gohr
13f5eb7cf0SAndreas Gohr/**
14d7d7bed5SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
15d7d7bed5SAndreas Gohr */
16d7d7bed5SAndreas Gohrfunction ft_preg_quote_cb($string){
17d7d7bed5SAndreas Gohr    return preg_quote($string,'/');
18d7d7bed5SAndreas Gohr}
19d7d7bed5SAndreas Gohr
20d7d7bed5SAndreas Gohr/**
21f5eb7cf0SAndreas Gohr * The fulltext search
22f5eb7cf0SAndreas Gohr *
23f5eb7cf0SAndreas Gohr * Returns a list of matching documents for the given query
24506fa893SAndreas Gohr *
25f5eb7cf0SAndreas Gohr */
26506fa893SAndreas Gohrfunction ft_pageSearch($query,&$poswords){
27f5eb7cf0SAndreas Gohr    $q = ft_queryParser($query);
28506fa893SAndreas Gohr    // use this for higlighting later:
29ad81d431SAndreas Gohr    $poswords = str_replace('*','',join(' ',$q['and']));
30506fa893SAndreas Gohr
31f5eb7cf0SAndreas Gohr    // lookup all words found in the query
32f5eb7cf0SAndreas Gohr    $words  = array_merge($q['and'],$q['not']);
33f5eb7cf0SAndreas Gohr    if(!count($words)) return array();
34f5eb7cf0SAndreas Gohr    $result = idx_lookup($words);
3505082375SAndreas Gohr    if(!count($result)) return array();
36f5eb7cf0SAndreas Gohr
37f5eb7cf0SAndreas Gohr    // merge search results with query
38f5eb7cf0SAndreas Gohr    foreach($q['and'] as $pos => $w){
39f5eb7cf0SAndreas Gohr        $q['and'][$pos] = $result[$w];
40f5eb7cf0SAndreas Gohr    }
41f5eb7cf0SAndreas Gohr    // create a list of unwanted docs
42f5eb7cf0SAndreas Gohr    $not = array();
43f5eb7cf0SAndreas Gohr    foreach($q['not'] as $pos => $w){
44f5eb7cf0SAndreas Gohr        $not = array_merge($not,array_keys($result[$w]));
45f5eb7cf0SAndreas Gohr    }
46f5eb7cf0SAndreas Gohr
47506fa893SAndreas Gohr    // combine and-words
48f5eb7cf0SAndreas Gohr    if(count($q['and']) > 1){
49f5eb7cf0SAndreas Gohr        $docs = ft_resultCombine($q['and']);
50f5eb7cf0SAndreas Gohr    }else{
51f5eb7cf0SAndreas Gohr        $docs = $q['and'][0];
52f5eb7cf0SAndreas Gohr    }
53f5eb7cf0SAndreas Gohr    if(!count($docs)) return array();
54f5eb7cf0SAndreas Gohr
550dc92c6fSAndreas Gohr    // create a list of hidden pages in the result
560dc92c6fSAndreas Gohr    $hidden = array();
570dc92c6fSAndreas Gohr    $hidden = array_filter(array_keys($docs),'isHiddenPage');
580dc92c6fSAndreas Gohr    $not = array_merge($not,$hidden);
590dc92c6fSAndreas Gohr
60d0ab54f6SMichael Klier chi@chimeric.de    // filter unmatched namespaces
61d0ab54f6SMichael Klier chi@chimeric.de    if(!empty($q['ns'])) {
62a219c1f0SMichael Klier chi@chimeric.de        $pattern = implode('|^',$q['ns']);
63d0ab54f6SMichael Klier chi@chimeric.de        foreach($docs as $key => $val) {
64a219c1f0SMichael Klier chi@chimeric.de            if(!preg_match('/^'.$pattern.'/',$key)) {
65d0ab54f6SMichael Klier chi@chimeric.de                unset($docs[$key]);
66d0ab54f6SMichael Klier chi@chimeric.de            }
67d0ab54f6SMichael Klier chi@chimeric.de        }
68d0ab54f6SMichael Klier chi@chimeric.de    }
69d0ab54f6SMichael Klier chi@chimeric.de
70f5eb7cf0SAndreas Gohr    // remove negative matches
71f5eb7cf0SAndreas Gohr    foreach($not as $n){
72f5eb7cf0SAndreas Gohr        unset($docs[$n]);
73f5eb7cf0SAndreas Gohr    }
74f5eb7cf0SAndreas Gohr
75f5eb7cf0SAndreas Gohr    if(!count($docs)) return array();
76f5eb7cf0SAndreas Gohr    // handle phrases
77f5eb7cf0SAndreas Gohr    if(count($q['phrases'])){
78f5eb7cf0SAndreas Gohr        //build a regexp
79f5eb7cf0SAndreas Gohr        $q['phrases'] = array_map('utf8_strtolower',$q['phrases']);
80d7d7bed5SAndreas Gohr        $q['phrases'] = array_map('ft_preg_quote_cb',$q['phrases']);
81f5eb7cf0SAndreas Gohr        // check the source of all documents for the exact phrases
82f5eb7cf0SAndreas Gohr        foreach(array_keys($docs) as $id){
83f5eb7cf0SAndreas Gohr            $text  = utf8_strtolower(rawWiki($id));
84a21136cdSAndreas Gohr            foreach($q['phrases'] as $phrase){
85a21136cdSAndreas Gohr                if(!preg_match('/'.$phrase.'/usi',$text)){
86f5eb7cf0SAndreas Gohr                    unset($docs[$id]); // no hit - remove
87a21136cdSAndreas Gohr                    break;
88a21136cdSAndreas Gohr                }
89f5eb7cf0SAndreas Gohr            }
90f5eb7cf0SAndreas Gohr        }
91f5eb7cf0SAndreas Gohr    }
92f5eb7cf0SAndreas Gohr
93f5eb7cf0SAndreas Gohr    if(!count($docs)) return array();
94f5eb7cf0SAndreas Gohr
9563773904SAndreas Gohr    // check ACL permissions
9663773904SAndreas Gohr    foreach(array_keys($docs) as $doc){
9763773904SAndreas Gohr        if(auth_quickaclcheck($doc) < AUTH_READ){
9863773904SAndreas Gohr            unset($docs[$doc]);
9963773904SAndreas Gohr        }
10063773904SAndreas Gohr    }
10163773904SAndreas Gohr
10263773904SAndreas Gohr    if(!count($docs)) return array();
10363773904SAndreas Gohr
104f5eb7cf0SAndreas Gohr    // if there are any hits left, sort them by count
105f5eb7cf0SAndreas Gohr    arsort($docs);
106f5eb7cf0SAndreas Gohr
107f5eb7cf0SAndreas Gohr    return $docs;
108f5eb7cf0SAndreas Gohr}
109f5eb7cf0SAndreas Gohr
110f5eb7cf0SAndreas Gohr/**
11154f4c056SAndreas Gohr * Returns the backlinks for a given page
11254f4c056SAndreas Gohr *
11354f4c056SAndreas Gohr * Does a quick lookup with the fulltext index, then
11454f4c056SAndreas Gohr * evaluates the instructions of the found pages
11554f4c056SAndreas Gohr */
11654f4c056SAndreas Gohrfunction ft_backlinks($id){
11754f4c056SAndreas Gohr    global $conf;
1186b06b652Schris    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
1196b06b652Schris    $stopwords = @file_exists($swfile) ? file($swfile) : array();
1206b06b652Schris
12154f4c056SAndreas Gohr    $result = array();
12254f4c056SAndreas Gohr
12354f4c056SAndreas Gohr    // quick lookup of the pagename
12454f4c056SAndreas Gohr    $page    = noNS($id);
1256b06b652Schris    $matches = idx_lookup(idx_tokenizer($page,$stopwords));  // pagename may contain specials (_ or .)
1260dc92c6fSAndreas Gohr    $docs    = array_keys(ft_resultCombine(array_values($matches)));
1270dc92c6fSAndreas Gohr    $docs    = array_filter($docs,'isVisiblePage'); // discard hidden pages
1283cbaa9a4SAndreas Gohr    if(!count($docs)) return $result;
12954f4c056SAndreas Gohr    require_once(DOKU_INC.'inc/parserutils.php');
13054f4c056SAndreas Gohr
13110ffc9ddSAndreas Gohr    // check metadata for matching links
1320dc92c6fSAndreas Gohr    foreach($docs as $match){
13310ffc9ddSAndreas Gohr        // metadata relation reference links are already resolved
1346b06b652Schris        $links = p_get_metadata($match,'relation references');
1353be6e394Schris        if (isset($links[$id])) $result[] = $match;
13654f4c056SAndreas Gohr    }
13754f4c056SAndreas Gohr
13863773904SAndreas Gohr    if(!count($result)) return $result;
13963773904SAndreas Gohr
14063773904SAndreas Gohr    // check ACL permissions
14163773904SAndreas Gohr    foreach(array_keys($result) as $idx){
14263773904SAndreas Gohr        if(auth_quickaclcheck($result[$idx]) < AUTH_READ){
14363773904SAndreas Gohr            unset($result[$idx]);
14463773904SAndreas Gohr        }
14563773904SAndreas Gohr    }
14663773904SAndreas Gohr
14754f4c056SAndreas Gohr    sort($result);
14854f4c056SAndreas Gohr    return $result;
14954f4c056SAndreas Gohr}
15054f4c056SAndreas Gohr
15154f4c056SAndreas Gohr/**
152506fa893SAndreas Gohr * Quicksearch for pagenames
153506fa893SAndreas Gohr *
154506fa893SAndreas Gohr * By default it only matches the pagename and ignores the
155506fa893SAndreas Gohr * namespace. This can be changed with the second parameter
156506fa893SAndreas Gohr *
157506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
158506fa893SAndreas Gohr */
159506fa893SAndreas Gohrfunction ft_pageLookup($id,$pageonly=true){
160506fa893SAndreas Gohr    global $conf;
161506fa893SAndreas Gohr    $id    = preg_quote($id,'/');
162579b0f7eSTNHarris    $pages = file($conf['indexdir'].'/page.idx');
1636798a86aSAndreas Gohr    if($id) $pages = array_values(preg_grep('/'.$id.'/',$pages));
164506fa893SAndreas Gohr
165506fa893SAndreas Gohr    $cnt = count($pages);
166506fa893SAndreas Gohr    for($i=0; $i<$cnt; $i++){
167506fa893SAndreas Gohr        if($pageonly){
168506fa893SAndreas Gohr            if(!preg_match('/'.$id.'/',noNS($pages[$i]))){
169506fa893SAndreas Gohr                unset($pages[$i]);
170506fa893SAndreas Gohr                continue;
171506fa893SAndreas Gohr            }
172506fa893SAndreas Gohr        }
173506fa893SAndreas Gohr        if(!@file_exists(wikiFN($pages[$i]))){
174506fa893SAndreas Gohr            unset($pages[$i]);
175506fa893SAndreas Gohr            continue;
176506fa893SAndreas Gohr        }
177506fa893SAndreas Gohr    }
17863773904SAndreas Gohr
1790dc92c6fSAndreas Gohr    $pages = array_filter($pages,'isVisiblePage'); // discard hidden pages
18063773904SAndreas Gohr    if(!count($pages)) return array();
18163773904SAndreas Gohr
18263773904SAndreas Gohr    // check ACL permissions
18363773904SAndreas Gohr    foreach(array_keys($pages) as $idx){
18463773904SAndreas Gohr        if(auth_quickaclcheck($pages[$idx]) < AUTH_READ){
18563773904SAndreas Gohr            unset($pages[$idx]);
18663773904SAndreas Gohr        }
18763773904SAndreas Gohr    }
18863773904SAndreas Gohr
1896798a86aSAndreas Gohr    $pages = array_map('trim',$pages);
190506fa893SAndreas Gohr    sort($pages);
191506fa893SAndreas Gohr    return $pages;
192506fa893SAndreas Gohr}
193506fa893SAndreas Gohr
194506fa893SAndreas Gohr/**
195506fa893SAndreas Gohr * Creates a snippet extract
196506fa893SAndreas Gohr *
197506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
198506fa893SAndreas Gohr */
199506fa893SAndreas Gohrfunction ft_snippet($id,$poswords){
200506fa893SAndreas Gohr    $poswords = preg_quote($poswords,'#');
201506fa893SAndreas Gohr    $re       = '('.str_replace(' ','|',$poswords).')';
202506fa893SAndreas Gohr    $text     = rawWiki($id);
203bd2cb6fcSchris
204ced0762eSchris    $match = array();
205ced0762eSchris    $snippets = array();
2069ee93076Schris    $utf8_offset = $offset = $end = 0;
207ced0762eSchris    $len = utf8_strlen($text);
2089ee93076Schris
209ced0762eSchris    for ($cnt=3; $cnt--;) {
210ced0762eSchris      if (!preg_match('#'.$re.'#iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) break;
211ced0762eSchris
212ced0762eSchris      list($str,$idx) = $match[0];
213ced0762eSchris
214ced0762eSchris      // convert $idx (a byte offset) into a utf8 character offset
215ced0762eSchris      $utf8_idx = utf8_strlen(substr($text,0,$idx));
216ced0762eSchris      $utf8_len = utf8_strlen($str);
217ced0762eSchris
218ced0762eSchris      // establish context, 100 bytes surrounding the match string
219ced0762eSchris      // first look to see if we can go 100 either side,
220ced0762eSchris      // then drop to 50 adding any excess if the other side can't go to 50,
221ced0762eSchris      $pre = min($utf8_idx-$utf8_offset,100);
222ced0762eSchris      $post = min($len-$utf8_idx-$utf8_len,100);
223ced0762eSchris
224ced0762eSchris      if ($pre>50 && $post>50) {
225ced0762eSchris        $pre = $post = 50;
226ced0762eSchris      } else if ($pre>50) {
227ced0762eSchris        $pre = min($pre,100-$post);
228ced0762eSchris      } else if ($post>50) {
229ced0762eSchris        $post = min($post, 100-$pre);
230ced0762eSchris      } else {
231ced0762eSchris        // both are less than 50, means the context is the whole string
23210ffc9ddSAndreas Gohr        // make it so and break out of this loop - there is no need for the
23310ffc9ddSAndreas Gohr        // complex snippet calculations
234ced0762eSchris        $snippets = array($text);
235ced0762eSchris        break;
236ced0762eSchris      }
237ced0762eSchris
23810ffc9ddSAndreas Gohr      // establish context start and end points, try to append to previous
23910ffc9ddSAndreas Gohr      // context if possible
2409ee93076Schris      $start = $utf8_idx - $pre;
241ced0762eSchris      $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
2429ee93076Schris      $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
243ced0762eSchris
244ced0762eSchris      if ($append) {
245ced0762eSchris        $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append);
246ced0762eSchris      } else {
247ced0762eSchris        $snippets[] = utf8_substr($text,$start,$end-$start);
248ced0762eSchris      }
249ced0762eSchris
250ced0762eSchris      // set $offset for next match attempt
25110ffc9ddSAndreas Gohr      //   substract strlen to avoid splitting a potential search success,
25210ffc9ddSAndreas Gohr      //   this is an approximation as the search pattern may match strings
25310ffc9ddSAndreas Gohr      //   of varying length and it will fail if the context snippet
254ced0762eSchris      //   boundary breaks a matching string longer than the current match
2559ee93076Schris      $utf8_offset = $utf8_idx + $post;
2569ee93076Schris      $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$post));
2579ee93076Schris      $offset = utf8_correctIdx($text,$offset);
2589ee93076Schris    }
2599ee93076Schris
260ced0762eSchris    $m = "\1";
261ced0762eSchris    $snippets = preg_replace('#'.$re.'#iu',$m.'$1'.$m,$snippets);
262ed7ecb79SAnika Henke    $snippet = preg_replace('#'.$m.'([^'.$m.']*?)'.$m.'#iu','<strong class="search_hit">$1</strong>',hsc(join('... ',$snippets)));
263bd2cb6fcSchris
2645953e889Schris    return $snippet;
265506fa893SAndreas Gohr}
266506fa893SAndreas Gohr
267506fa893SAndreas Gohr/**
268f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores
269f5eb7cf0SAndreas Gohr *
270f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical
271f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned.
272f5eb7cf0SAndreas Gohr *
273f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key()
274f5eb7cf0SAndreas Gohr *
275f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays
276f5eb7cf0SAndreas Gohr */
277f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){
278f5eb7cf0SAndreas Gohr    $array_count = count($args);
279134f4ab2SAndreas Gohr    if($array_count == 1){
280134f4ab2SAndreas Gohr        return $args[0];
281134f4ab2SAndreas Gohr    }
282134f4ab2SAndreas Gohr
283f5eb7cf0SAndreas Gohr    $result = array();
28409c27a6dSGuy Brand    if ($array_count > 1) {
285a21136cdSAndreas Gohr      foreach ($args[0] as $key => $value) {
286a21136cdSAndreas Gohr        $result[$key] = $value;
287f5eb7cf0SAndreas Gohr        for ($i = 1; $i !== $array_count; $i++) {
288a21136cdSAndreas Gohr            if (!isset($args[$i][$key])) {
289a21136cdSAndreas Gohr                unset($result[$key]);
290a21136cdSAndreas Gohr                break;
291f5eb7cf0SAndreas Gohr            }
292a21136cdSAndreas Gohr            $result[$key] += $args[$i][$key];
293f5eb7cf0SAndreas Gohr        }
294f5eb7cf0SAndreas Gohr      }
29509c27a6dSGuy Brand    }
296f5eb7cf0SAndreas Gohr    return $result;
297f5eb7cf0SAndreas Gohr}
298f5eb7cf0SAndreas Gohr
299f5eb7cf0SAndreas Gohr/**
300f5eb7cf0SAndreas Gohr * Builds an array of search words from a query
301f5eb7cf0SAndreas Gohr *
302f5eb7cf0SAndreas Gohr * @todo support OR and parenthesises?
303f5eb7cf0SAndreas Gohr */
304f5eb7cf0SAndreas Gohrfunction ft_queryParser($query){
305f5eb7cf0SAndreas Gohr    global $conf;
306f5eb7cf0SAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
307f5eb7cf0SAndreas Gohr    if(@file_exists($swfile)){
308f5eb7cf0SAndreas Gohr        $stopwords = file($swfile);
309f5eb7cf0SAndreas Gohr    }else{
310f5eb7cf0SAndreas Gohr        $stopwords = array();
311f5eb7cf0SAndreas Gohr    }
312f5eb7cf0SAndreas Gohr
313f5eb7cf0SAndreas Gohr    $q = array();
314f5eb7cf0SAndreas Gohr    $q['query']   = $query;
315a219c1f0SMichael Klier chi@chimeric.de    $q['ns']      = array();
316f5eb7cf0SAndreas Gohr    $q['phrases'] = array();
317f5eb7cf0SAndreas Gohr    $q['and']     = array();
318f5eb7cf0SAndreas Gohr    $q['not']     = array();
319f5eb7cf0SAndreas Gohr
320d0ab54f6SMichael Klier chi@chimeric.de    // strip namespace from query
321a219c1f0SMichael Klier chi@chimeric.de    if(preg_match('/([^@]*)@(.*)/',$query,$match))  {
322d0ab54f6SMichael Klier chi@chimeric.de        $query = $match[1];
323a219c1f0SMichael Klier chi@chimeric.de        $q['ns'] = explode('@',preg_replace("/ /",'',$match[2]));
324d0ab54f6SMichael Klier chi@chimeric.de    }
325d0ab54f6SMichael Klier chi@chimeric.de
326f5eb7cf0SAndreas Gohr    // handle phrase searches
327f5eb7cf0SAndreas Gohr    while(preg_match('/"(.*?)"/',$query,$match)){
32893a60ad2SAndreas Gohr        $q['phrases'][] = $match[1];
329235cf363SAndreas Gohr        $q['and'] = array_merge($q['and'], idx_tokenizer($match[0],$stopwords));
330f5eb7cf0SAndreas Gohr        $query = preg_replace('/"(.*?)"/','',$query,1);
331f5eb7cf0SAndreas Gohr    }
332f5eb7cf0SAndreas Gohr
333f5eb7cf0SAndreas Gohr    $words = explode(' ',$query);
334f5eb7cf0SAndreas Gohr    foreach($words as $w){
335f5eb7cf0SAndreas Gohr        if($w{0} == '-'){
336ad81d431SAndreas Gohr            $token = idx_tokenizer($w,$stopwords,true);
337f5eb7cf0SAndreas Gohr            if(count($token)) $q['not'] = array_merge($q['not'],$token);
338f5eb7cf0SAndreas Gohr        }else{
33993a60ad2SAndreas Gohr            // asian "words" need to be searched as phrases
34091bb5faaSAndreas Gohr            if(@preg_match_all('/('.IDX_ASIAN.'+)/u',$w,$matches)){
34193a60ad2SAndreas Gohr                $q['phrases'] = array_merge($q['phrases'],$matches[1]);
34293a60ad2SAndreas Gohr
34393a60ad2SAndreas Gohr            }
344ad81d431SAndreas Gohr            $token = idx_tokenizer($w,$stopwords,true);
345f5eb7cf0SAndreas Gohr            if(count($token)) $q['and'] = array_merge($q['and'],$token);
346f5eb7cf0SAndreas Gohr        }
347f5eb7cf0SAndreas Gohr    }
348f5eb7cf0SAndreas Gohr
349f5eb7cf0SAndreas Gohr    return $q;
350f5eb7cf0SAndreas Gohr}
351f5eb7cf0SAndreas Gohr
352506fa893SAndreas Gohr//Setup VIM: ex: et ts=4 enc=utf-8 :
353