xref: /dokuwiki/inc/fulltext.php (revision 6798a86a10e58a8c235f7c405c016d56353dc030)
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;
1086b06b652Schris    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
1096b06b652Schris    $stopwords = @file_exists($swfile) ? file($swfile) : array();
1106b06b652Schris
11154f4c056SAndreas Gohr    $result = array();
11254f4c056SAndreas Gohr
11354f4c056SAndreas Gohr    // quick lookup of the pagename
11454f4c056SAndreas Gohr    $page    = noNS($id);
1156b06b652Schris    $matches = idx_lookup(idx_tokenizer($page,$stopwords));  // pagename may contain specials (_ or .)
1160dc92c6fSAndreas Gohr    $docs    = array_keys(ft_resultCombine(array_values($matches)));
1170dc92c6fSAndreas Gohr    $docs    = array_filter($docs,'isVisiblePage'); // discard hidden pages
1183cbaa9a4SAndreas Gohr    if(!count($docs)) return $result;
11954f4c056SAndreas Gohr    require_once(DOKU_INC.'inc/parserutils.php');
12054f4c056SAndreas Gohr
12110ffc9ddSAndreas Gohr    // check metadata for matching links
1220dc92c6fSAndreas Gohr    foreach($docs as $match){
12310ffc9ddSAndreas Gohr        // metadata relation reference links are already resolved
1246b06b652Schris        $links = p_get_metadata($match,'relation references');
1253be6e394Schris        if (isset($links[$id])) $result[] = $match;
12654f4c056SAndreas Gohr    }
12754f4c056SAndreas Gohr
12863773904SAndreas Gohr    if(!count($result)) return $result;
12963773904SAndreas Gohr
13063773904SAndreas Gohr    // check ACL permissions
13163773904SAndreas Gohr    foreach(array_keys($result) as $idx){
13263773904SAndreas Gohr        if(auth_quickaclcheck($result[$idx]) < AUTH_READ){
13363773904SAndreas Gohr            unset($result[$idx]);
13463773904SAndreas Gohr        }
13563773904SAndreas Gohr    }
13663773904SAndreas Gohr
13754f4c056SAndreas Gohr    sort($result);
13854f4c056SAndreas Gohr    return $result;
13954f4c056SAndreas Gohr}
14054f4c056SAndreas Gohr
14154f4c056SAndreas Gohr/**
142506fa893SAndreas Gohr * Quicksearch for pagenames
143506fa893SAndreas Gohr *
144506fa893SAndreas Gohr * By default it only matches the pagename and ignores the
145506fa893SAndreas Gohr * namespace. This can be changed with the second parameter
146506fa893SAndreas Gohr *
147506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
148506fa893SAndreas Gohr */
149506fa893SAndreas Gohrfunction ft_pageLookup($id,$pageonly=true){
150506fa893SAndreas Gohr    global $conf;
151506fa893SAndreas Gohr    $id    = preg_quote($id,'/');
152579b0f7eSTNHarris    $pages = file($conf['indexdir'].'/page.idx');
153*6798a86aSAndreas Gohr    if($id) $pages = array_values(preg_grep('/'.$id.'/',$pages));
154506fa893SAndreas Gohr
155506fa893SAndreas Gohr    $cnt = count($pages);
156506fa893SAndreas Gohr    for($i=0; $i<$cnt; $i++){
157506fa893SAndreas Gohr        if($pageonly){
158506fa893SAndreas Gohr            if(!preg_match('/'.$id.'/',noNS($pages[$i]))){
159506fa893SAndreas Gohr                unset($pages[$i]);
160506fa893SAndreas Gohr                continue;
161506fa893SAndreas Gohr            }
162506fa893SAndreas Gohr        }
163506fa893SAndreas Gohr        if(!@file_exists(wikiFN($pages[$i]))){
164506fa893SAndreas Gohr            unset($pages[$i]);
165506fa893SAndreas Gohr            continue;
166506fa893SAndreas Gohr        }
167506fa893SAndreas Gohr    }
16863773904SAndreas Gohr
1690dc92c6fSAndreas Gohr    $pages = array_filter($pages,'isVisiblePage'); // discard hidden pages
17063773904SAndreas Gohr    if(!count($pages)) return array();
17163773904SAndreas Gohr
17263773904SAndreas Gohr    // check ACL permissions
17363773904SAndreas Gohr    foreach(array_keys($pages) as $idx){
17463773904SAndreas Gohr        if(auth_quickaclcheck($pages[$idx]) < AUTH_READ){
17563773904SAndreas Gohr            unset($pages[$idx]);
17663773904SAndreas Gohr        }
17763773904SAndreas Gohr    }
17863773904SAndreas Gohr
179*6798a86aSAndreas Gohr    $pages = array_map('trim',$pages);
180506fa893SAndreas Gohr    sort($pages);
181506fa893SAndreas Gohr    return $pages;
182506fa893SAndreas Gohr}
183506fa893SAndreas Gohr
184506fa893SAndreas Gohr/**
185506fa893SAndreas Gohr * Creates a snippet extract
186506fa893SAndreas Gohr *
187506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
188506fa893SAndreas Gohr */
189506fa893SAndreas Gohrfunction ft_snippet($id,$poswords){
190506fa893SAndreas Gohr    $poswords = preg_quote($poswords,'#');
191506fa893SAndreas Gohr    $re       = '('.str_replace(' ','|',$poswords).')';
192506fa893SAndreas Gohr    $text     = rawWiki($id);
193bd2cb6fcSchris
194ced0762eSchris    $match = array();
195ced0762eSchris    $snippets = array();
1969ee93076Schris    $utf8_offset = $offset = $end = 0;
197ced0762eSchris    $len = utf8_strlen($text);
1989ee93076Schris
199ced0762eSchris    for ($cnt=3; $cnt--;) {
200ced0762eSchris      if (!preg_match('#'.$re.'#iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) break;
201ced0762eSchris
202ced0762eSchris      list($str,$idx) = $match[0];
203ced0762eSchris
204ced0762eSchris      // convert $idx (a byte offset) into a utf8 character offset
205ced0762eSchris      $utf8_idx = utf8_strlen(substr($text,0,$idx));
206ced0762eSchris      $utf8_len = utf8_strlen($str);
207ced0762eSchris
208ced0762eSchris      // establish context, 100 bytes surrounding the match string
209ced0762eSchris      // first look to see if we can go 100 either side,
210ced0762eSchris      // then drop to 50 adding any excess if the other side can't go to 50,
211ced0762eSchris      $pre = min($utf8_idx-$utf8_offset,100);
212ced0762eSchris      $post = min($len-$utf8_idx-$utf8_len,100);
213ced0762eSchris
214ced0762eSchris      if ($pre>50 && $post>50) {
215ced0762eSchris        $pre = $post = 50;
216ced0762eSchris      } else if ($pre>50) {
217ced0762eSchris        $pre = min($pre,100-$post);
218ced0762eSchris      } else if ($post>50) {
219ced0762eSchris        $post = min($post, 100-$pre);
220ced0762eSchris      } else {
221ced0762eSchris        // both are less than 50, means the context is the whole string
22210ffc9ddSAndreas Gohr        // make it so and break out of this loop - there is no need for the
22310ffc9ddSAndreas Gohr        // complex snippet calculations
224ced0762eSchris        $snippets = array($text);
225ced0762eSchris        break;
226ced0762eSchris      }
227ced0762eSchris
22810ffc9ddSAndreas Gohr      // establish context start and end points, try to append to previous
22910ffc9ddSAndreas Gohr      // context if possible
2309ee93076Schris      $start = $utf8_idx - $pre;
231ced0762eSchris      $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
2329ee93076Schris      $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
233ced0762eSchris
234ced0762eSchris      if ($append) {
235ced0762eSchris        $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append);
236ced0762eSchris      } else {
237ced0762eSchris        $snippets[] = utf8_substr($text,$start,$end-$start);
238ced0762eSchris      }
239ced0762eSchris
240ced0762eSchris      // set $offset for next match attempt
24110ffc9ddSAndreas Gohr      //   substract strlen to avoid splitting a potential search success,
24210ffc9ddSAndreas Gohr      //   this is an approximation as the search pattern may match strings
24310ffc9ddSAndreas Gohr      //   of varying length and it will fail if the context snippet
244ced0762eSchris      //   boundary breaks a matching string longer than the current match
2459ee93076Schris      $utf8_offset = $utf8_idx + $post;
2469ee93076Schris      $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$post));
2479ee93076Schris      $offset = utf8_correctIdx($text,$offset);
2489ee93076Schris    }
2499ee93076Schris
250ced0762eSchris    $m = "\1";
251ced0762eSchris    $snippets = preg_replace('#'.$re.'#iu',$m.'$1'.$m,$snippets);
252ced0762eSchris    $snippet = preg_replace('#'.$m.'([^'.$m.']*?)'.$m.'#iu','<span class="search_hit">$1</span>',hsc(join('... ',$snippets)));
253bd2cb6fcSchris
2545953e889Schris    return $snippet;
255506fa893SAndreas Gohr}
256506fa893SAndreas Gohr
257506fa893SAndreas Gohr/**
258f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores
259f5eb7cf0SAndreas Gohr *
260f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical
261f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned.
262f5eb7cf0SAndreas Gohr *
263f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key()
264f5eb7cf0SAndreas Gohr *
265f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays
266f5eb7cf0SAndreas Gohr */
267f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){
268f5eb7cf0SAndreas Gohr    $array_count = count($args);
269134f4ab2SAndreas Gohr    if($array_count == 1){
270134f4ab2SAndreas Gohr        return $args[0];
271134f4ab2SAndreas Gohr    }
272134f4ab2SAndreas Gohr
273f5eb7cf0SAndreas Gohr    $result = array();
274f5eb7cf0SAndreas Gohr    foreach ($args[0] as $key1 => $value1) {
275f5eb7cf0SAndreas Gohr        for ($i = 1; $i !== $array_count; $i++) {
276f5eb7cf0SAndreas Gohr            foreach ($args[$i] as $key2 => $value2) {
277f5eb7cf0SAndreas Gohr                if ((string) $key1 === (string) $key2) {
278f5eb7cf0SAndreas Gohr                    if(!isset($result[$key1])) $result[$key1] = $value1;
279f5eb7cf0SAndreas Gohr                    $result[$key1] += $value2;
280f5eb7cf0SAndreas Gohr                }
281f5eb7cf0SAndreas Gohr            }
282f5eb7cf0SAndreas Gohr        }
283f5eb7cf0SAndreas Gohr    }
284f5eb7cf0SAndreas Gohr    return $result;
285f5eb7cf0SAndreas Gohr}
286f5eb7cf0SAndreas Gohr
287f5eb7cf0SAndreas Gohr/**
288f5eb7cf0SAndreas Gohr * Builds an array of search words from a query
289f5eb7cf0SAndreas Gohr *
290f5eb7cf0SAndreas Gohr * @todo support OR and parenthesises?
291f5eb7cf0SAndreas Gohr */
292f5eb7cf0SAndreas Gohrfunction ft_queryParser($query){
293f5eb7cf0SAndreas Gohr    global $conf;
294f5eb7cf0SAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
295f5eb7cf0SAndreas Gohr    if(@file_exists($swfile)){
296f5eb7cf0SAndreas Gohr        $stopwords = file($swfile);
297f5eb7cf0SAndreas Gohr    }else{
298f5eb7cf0SAndreas Gohr        $stopwords = array();
299f5eb7cf0SAndreas Gohr    }
300f5eb7cf0SAndreas Gohr
301f5eb7cf0SAndreas Gohr    $q = array();
302f5eb7cf0SAndreas Gohr    $q['query']   = $query;
303a219c1f0SMichael Klier chi@chimeric.de    $q['ns']      = array();
304f5eb7cf0SAndreas Gohr    $q['phrases'] = array();
305f5eb7cf0SAndreas Gohr    $q['and']     = array();
306f5eb7cf0SAndreas Gohr    $q['not']     = array();
307f5eb7cf0SAndreas Gohr
308d0ab54f6SMichael Klier chi@chimeric.de    // strip namespace from query
309a219c1f0SMichael Klier chi@chimeric.de    if(preg_match('/([^@]*)@(.*)/',$query,$match))  {
310d0ab54f6SMichael Klier chi@chimeric.de        $query = $match[1];
311a219c1f0SMichael Klier chi@chimeric.de        $q['ns'] = explode('@',preg_replace("/ /",'',$match[2]));
312d0ab54f6SMichael Klier chi@chimeric.de    }
313d0ab54f6SMichael Klier chi@chimeric.de
314f5eb7cf0SAndreas Gohr    // handle phrase searches
315f5eb7cf0SAndreas Gohr    while(preg_match('/"(.*?)"/',$query,$match)){
31693a60ad2SAndreas Gohr        $q['phrases'][] = $match[1];
317f5eb7cf0SAndreas Gohr        $q['and'] = array_merge(idx_tokenizer($match[0],$stopwords));
318f5eb7cf0SAndreas Gohr        $query = preg_replace('/"(.*?)"/','',$query,1);
319f5eb7cf0SAndreas Gohr    }
320f5eb7cf0SAndreas Gohr
321f5eb7cf0SAndreas Gohr    $words = explode(' ',$query);
322f5eb7cf0SAndreas Gohr    foreach($words as $w){
323f5eb7cf0SAndreas Gohr        if($w{0} == '-'){
324ad81d431SAndreas Gohr            $token = idx_tokenizer($w,$stopwords,true);
325f5eb7cf0SAndreas Gohr            if(count($token)) $q['not'] = array_merge($q['not'],$token);
326f5eb7cf0SAndreas Gohr        }else{
32793a60ad2SAndreas Gohr            // asian "words" need to be searched as phrases
32891bb5faaSAndreas Gohr            if(@preg_match_all('/('.IDX_ASIAN.'+)/u',$w,$matches)){
32993a60ad2SAndreas Gohr                $q['phrases'] = array_merge($q['phrases'],$matches[1]);
33093a60ad2SAndreas Gohr
33193a60ad2SAndreas Gohr            }
332ad81d431SAndreas Gohr            $token = idx_tokenizer($w,$stopwords,true);
333f5eb7cf0SAndreas Gohr            if(count($token)) $q['and'] = array_merge($q['and'],$token);
334f5eb7cf0SAndreas Gohr        }
335f5eb7cf0SAndreas Gohr    }
336f5eb7cf0SAndreas Gohr
337f5eb7cf0SAndreas Gohr    return $q;
338f5eb7cf0SAndreas Gohr}
339f5eb7cf0SAndreas Gohr
340506fa893SAndreas Gohr//Setup VIM: ex: et ts=4 enc=utf-8 :
341