xref: /dokuwiki/inc/fulltext.php (revision b571ff2dc2f7b3db879de14daefb02597190ca13)
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 Gohrrequire_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 *
186840140fSChris Smith * refactored into ft_pageSearch(), _ft_pageSearch() and trigger_event()
196840140fSChris Smith *
20f5eb7cf0SAndreas Gohr */
21546d3a99SAndreas Gohrfunction ft_pageSearch($query,&$highlight){
226840140fSChris Smith
236840140fSChris Smith  $data['query'] = $query;
246840140fSChris Smith  $data['highlight'] =& $highlight;
256840140fSChris Smith
266840140fSChris Smith  return trigger_event('SEARCH_QUERY_FULLPAGE', $data, '_ft_pageSearch');
276840140fSChris Smith}
286840140fSChris Smithfunction _ft_pageSearch(&$data){
296840140fSChris Smith    // split out original parameters
306840140fSChris Smith    $query = $data['query'];
316840140fSChris Smith    $highlight =& $data['highlight'];
326840140fSChris Smith
33f5eb7cf0SAndreas Gohr    $q = ft_queryParser($query);
3460c15d7dSAndreas Gohr
35546d3a99SAndreas Gohr    $highlight = array();
36546d3a99SAndreas Gohr
3760c15d7dSAndreas Gohr    // remember for hilighting later
38546d3a99SAndreas Gohr    foreach($q['words'] as $wrd){
39546d3a99SAndreas Gohr        $highlight[] =  str_replace('*','',$wrd);
40546d3a99SAndreas Gohr    }
41506fa893SAndreas Gohr
42f5eb7cf0SAndreas Gohr    // lookup all words found in the query
43f5eb7cf0SAndreas Gohr    $words  = array_merge($q['and'],$q['not']);
44f5eb7cf0SAndreas Gohr    if(!count($words)) return array();
45f5eb7cf0SAndreas Gohr    $result = idx_lookup($words);
4605082375SAndreas Gohr    if(!count($result)) return array();
47f5eb7cf0SAndreas Gohr
48f5eb7cf0SAndreas Gohr    // merge search results with query
49f5eb7cf0SAndreas Gohr    foreach($q['and'] as $pos => $w){
50f5eb7cf0SAndreas Gohr        $q['and'][$pos] = $result[$w];
51f5eb7cf0SAndreas Gohr    }
52f5eb7cf0SAndreas Gohr    // create a list of unwanted docs
53f5eb7cf0SAndreas Gohr    $not = array();
54f5eb7cf0SAndreas Gohr    foreach($q['not'] as $pos => $w){
55f5eb7cf0SAndreas Gohr        $not = array_merge($not,array_keys($result[$w]));
56f5eb7cf0SAndreas Gohr    }
57f5eb7cf0SAndreas Gohr
58506fa893SAndreas Gohr    // combine and-words
59f5eb7cf0SAndreas Gohr    if(count($q['and']) > 1){
60f5eb7cf0SAndreas Gohr        $docs = ft_resultCombine($q['and']);
61f5eb7cf0SAndreas Gohr    }else{
62f5eb7cf0SAndreas Gohr        $docs = $q['and'][0];
63f5eb7cf0SAndreas Gohr    }
64f5eb7cf0SAndreas Gohr    if(!count($docs)) return array();
65f5eb7cf0SAndreas Gohr
660dc92c6fSAndreas Gohr    // create a list of hidden pages in the result
670dc92c6fSAndreas Gohr    $hidden = array();
680dc92c6fSAndreas Gohr    $hidden = array_filter(array_keys($docs),'isHiddenPage');
690dc92c6fSAndreas Gohr    $not = array_merge($not,$hidden);
700dc92c6fSAndreas Gohr
71d0ab54f6SMichael Klier chi@chimeric.de    // filter unmatched namespaces
72d0ab54f6SMichael Klier chi@chimeric.de    if(!empty($q['ns'])) {
73a219c1f0SMichael Klier chi@chimeric.de        $pattern = implode('|^',$q['ns']);
74d0ab54f6SMichael Klier chi@chimeric.de        foreach($docs as $key => $val) {
75a219c1f0SMichael Klier chi@chimeric.de            if(!preg_match('/^'.$pattern.'/',$key)) {
76d0ab54f6SMichael Klier chi@chimeric.de                unset($docs[$key]);
77d0ab54f6SMichael Klier chi@chimeric.de            }
78d0ab54f6SMichael Klier chi@chimeric.de        }
79d0ab54f6SMichael Klier chi@chimeric.de    }
80d0ab54f6SMichael Klier chi@chimeric.de
81b42bcfe7Sdaniel.lindgren    // filter unwanted namespaces
82b42bcfe7Sdaniel.lindgren    if(!empty($q['notns'])) {
83b42bcfe7Sdaniel.lindgren        $pattern = implode('|^',$q['notns']);
84b42bcfe7Sdaniel.lindgren        foreach($docs as $key => $val) {
85b42bcfe7Sdaniel.lindgren            if(preg_match('/^'.$pattern.'/',$key)) {
86b42bcfe7Sdaniel.lindgren                unset($docs[$key]);
87b42bcfe7Sdaniel.lindgren            }
88b42bcfe7Sdaniel.lindgren        }
89b42bcfe7Sdaniel.lindgren    }
90b42bcfe7Sdaniel.lindgren
91f5eb7cf0SAndreas Gohr    // remove negative matches
92f5eb7cf0SAndreas Gohr    foreach($not as $n){
93f5eb7cf0SAndreas Gohr        unset($docs[$n]);
94f5eb7cf0SAndreas Gohr    }
95f5eb7cf0SAndreas Gohr
96f5eb7cf0SAndreas Gohr    if(!count($docs)) return array();
97f5eb7cf0SAndreas Gohr    // handle phrases
98f5eb7cf0SAndreas Gohr    if(count($q['phrases'])){
99f5eb7cf0SAndreas Gohr        $q['phrases'] = array_map('utf8_strtolower',$q['phrases']);
10060c15d7dSAndreas Gohr        // use this for higlighting later:
101546d3a99SAndreas Gohr        $highlight = array_merge($highlight,$q['phrases']);
102546d3a99SAndreas Gohr        $q['phrases'] = array_map('preg_quote_cb',$q['phrases']);
103f5eb7cf0SAndreas Gohr        // check the source of all documents for the exact phrases
104f5eb7cf0SAndreas Gohr        foreach(array_keys($docs) as $id){
105f5eb7cf0SAndreas Gohr            $text  = utf8_strtolower(rawWiki($id));
106a21136cdSAndreas Gohr            foreach($q['phrases'] as $phrase){
107a21136cdSAndreas Gohr                if(!preg_match('/'.$phrase.'/usi',$text)){
108f5eb7cf0SAndreas Gohr                    unset($docs[$id]); // no hit - remove
109a21136cdSAndreas Gohr                    break;
110a21136cdSAndreas Gohr                }
111f5eb7cf0SAndreas Gohr            }
112f5eb7cf0SAndreas Gohr        }
113f5eb7cf0SAndreas Gohr    }
114f5eb7cf0SAndreas Gohr
115f5eb7cf0SAndreas Gohr    if(!count($docs)) return array();
116f5eb7cf0SAndreas Gohr
11763773904SAndreas Gohr    // check ACL permissions
11863773904SAndreas Gohr    foreach(array_keys($docs) as $doc){
11963773904SAndreas Gohr        if(auth_quickaclcheck($doc) < AUTH_READ){
12063773904SAndreas Gohr            unset($docs[$doc]);
12163773904SAndreas Gohr        }
12263773904SAndreas Gohr    }
12363773904SAndreas Gohr
12463773904SAndreas Gohr    if(!count($docs)) return array();
12563773904SAndreas Gohr
126f5eb7cf0SAndreas Gohr    // if there are any hits left, sort them by count
127f5eb7cf0SAndreas Gohr    arsort($docs);
128f5eb7cf0SAndreas Gohr
129f5eb7cf0SAndreas Gohr    return $docs;
130f5eb7cf0SAndreas Gohr}
131f5eb7cf0SAndreas Gohr
132f5eb7cf0SAndreas Gohr/**
13354f4c056SAndreas Gohr * Returns the backlinks for a given page
13454f4c056SAndreas Gohr *
13554f4c056SAndreas Gohr * Does a quick lookup with the fulltext index, then
13654f4c056SAndreas Gohr * evaluates the instructions of the found pages
13754f4c056SAndreas Gohr */
13854f4c056SAndreas Gohrfunction ft_backlinks($id){
13954f4c056SAndreas Gohr    global $conf;
1406b06b652Schris    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
1416b06b652Schris    $stopwords = @file_exists($swfile) ? file($swfile) : array();
1426b06b652Schris
14354f4c056SAndreas Gohr    $result = array();
14454f4c056SAndreas Gohr
14554f4c056SAndreas Gohr    // quick lookup of the pagename
14654f4c056SAndreas Gohr    $page    = noNS($id);
1476b06b652Schris    $matches = idx_lookup(idx_tokenizer($page,$stopwords));  // pagename may contain specials (_ or .)
1480dc92c6fSAndreas Gohr    $docs    = array_keys(ft_resultCombine(array_values($matches)));
1490dc92c6fSAndreas Gohr    $docs    = array_filter($docs,'isVisiblePage'); // discard hidden pages
1503cbaa9a4SAndreas Gohr    if(!count($docs)) return $result;
15154f4c056SAndreas Gohr    require_once(DOKU_INC.'inc/parserutils.php');
15254f4c056SAndreas Gohr
15310ffc9ddSAndreas Gohr    // check metadata for matching links
1540dc92c6fSAndreas Gohr    foreach($docs as $match){
15510ffc9ddSAndreas Gohr        // metadata relation reference links are already resolved
1566b06b652Schris        $links = p_get_metadata($match,'relation references');
1573be6e394Schris        if (isset($links[$id])) $result[] = $match;
15854f4c056SAndreas Gohr    }
15954f4c056SAndreas Gohr
16063773904SAndreas Gohr    if(!count($result)) return $result;
16163773904SAndreas Gohr
16263773904SAndreas Gohr    // check ACL permissions
16363773904SAndreas Gohr    foreach(array_keys($result) as $idx){
16463773904SAndreas Gohr        if(auth_quickaclcheck($result[$idx]) < AUTH_READ){
16563773904SAndreas Gohr            unset($result[$idx]);
16663773904SAndreas Gohr        }
16763773904SAndreas Gohr    }
16863773904SAndreas Gohr
16954f4c056SAndreas Gohr    sort($result);
17054f4c056SAndreas Gohr    return $result;
17154f4c056SAndreas Gohr}
17254f4c056SAndreas Gohr
17354f4c056SAndreas Gohr/**
174a05e297aSAndreas Gohr * Returns the pages that use a given media file
175a05e297aSAndreas Gohr *
176a05e297aSAndreas Gohr * Does a quick lookup with the fulltext index, then
177a05e297aSAndreas Gohr * evaluates the instructions of the found pages
178a05e297aSAndreas Gohr *
179a05e297aSAndreas Gohr * Aborts after $max found results
180a05e297aSAndreas Gohr */
181a05e297aSAndreas Gohrfunction ft_mediause($id,$max){
182a05e297aSAndreas Gohr    global $conf;
183a05e297aSAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
184a05e297aSAndreas Gohr    $stopwords = @file_exists($swfile) ? file($swfile) : array();
185a05e297aSAndreas Gohr
186a05e297aSAndreas Gohr    if(!$max) $max = 1; // need to find at least one
187a05e297aSAndreas Gohr
188a05e297aSAndreas Gohr    $result = array();
189a05e297aSAndreas Gohr
190a05e297aSAndreas Gohr    // quick lookup of the mediafile
191a05e297aSAndreas Gohr    $media   = noNS($id);
192a05e297aSAndreas Gohr    $matches = idx_lookup(idx_tokenizer($media,$stopwords));
193a05e297aSAndreas Gohr    $docs    = array_keys(ft_resultCombine(array_values($matches)));
194a05e297aSAndreas Gohr    if(!count($docs)) return $result;
195a05e297aSAndreas Gohr
196a05e297aSAndreas Gohr    // go through all found pages
197a05e297aSAndreas Gohr    $found = 0;
198a05e297aSAndreas Gohr    $pcre  = preg_quote($media,'/');
199a05e297aSAndreas Gohr    foreach($docs as $doc){
200a05e297aSAndreas Gohr        $ns = getNS($doc);
201a05e297aSAndreas Gohr        preg_match_all('/\{\{([^|}]*'.$pcre.'[^|}]*)(|[^}]+)?\}\}/i',rawWiki($doc),$matches);
202a05e297aSAndreas Gohr        foreach($matches[1] as $img){
203a05e297aSAndreas Gohr            $img = trim($img);
204a05e297aSAndreas Gohr            if(preg_match('/^https?:\/\//i',$img)) continue; // skip external images
205a05e297aSAndreas Gohr            list($img) = explode('?',$img);                  // remove any parameters
206a05e297aSAndreas Gohr            resolve_mediaid($ns,$img,$exists);               // resolve the possibly relative img
207a05e297aSAndreas Gohr
208a05e297aSAndreas Gohr            if($img == $id){                                 // we have a match
209a05e297aSAndreas Gohr                $result[] = $doc;
210a05e297aSAndreas Gohr                $found++;
211a05e297aSAndreas Gohr                break;
212a05e297aSAndreas Gohr            }
213a05e297aSAndreas Gohr        }
214a05e297aSAndreas Gohr        if($found >= $max) break;
215a05e297aSAndreas Gohr    }
216a05e297aSAndreas Gohr
217a05e297aSAndreas Gohr    sort($result);
218a05e297aSAndreas Gohr    return $result;
219a05e297aSAndreas Gohr}
220a05e297aSAndreas Gohr
221a05e297aSAndreas Gohr
222a05e297aSAndreas Gohr
223a05e297aSAndreas Gohr/**
224506fa893SAndreas Gohr * Quicksearch for pagenames
225506fa893SAndreas Gohr *
226506fa893SAndreas Gohr * By default it only matches the pagename and ignores the
227506fa893SAndreas Gohr * namespace. This can be changed with the second parameter
228506fa893SAndreas Gohr *
2296840140fSChris Smith * refactored into ft_pageLookup(), _ft_pageLookup() and trigger_event()
2306840140fSChris Smith *
231506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
232506fa893SAndreas Gohr */
233506fa893SAndreas Gohrfunction ft_pageLookup($id,$pageonly=true){
2346840140fSChris Smith    $data = array('id' => $id, 'pageonly' => $pageonly);
2356840140fSChris Smith    return trigger_event('SEARCH_QUERY_PAGELOOKUP',$data,'_ft_pageLookup');
2366840140fSChris Smith}
2376840140fSChris Smith
2386840140fSChris Smithfunction _ft_pageLookup(&$data){
2396840140fSChris Smith    // split out original parameterrs
2406840140fSChris Smith    $id = $data['id'];
2416840140fSChris Smith    $pageonly = $data['pageonly'];
2426840140fSChris Smith
243506fa893SAndreas Gohr    global $conf;
244506fa893SAndreas Gohr    $id    = preg_quote($id,'/');
245579b0f7eSTNHarris    $pages = file($conf['indexdir'].'/page.idx');
2466798a86aSAndreas Gohr    if($id) $pages = array_values(preg_grep('/'.$id.'/',$pages));
247506fa893SAndreas Gohr
248506fa893SAndreas Gohr    $cnt = count($pages);
249506fa893SAndreas Gohr    for($i=0; $i<$cnt; $i++){
250506fa893SAndreas Gohr        if($pageonly){
251506fa893SAndreas Gohr            if(!preg_match('/'.$id.'/',noNS($pages[$i]))){
252506fa893SAndreas Gohr                unset($pages[$i]);
253506fa893SAndreas Gohr                continue;
254506fa893SAndreas Gohr            }
255506fa893SAndreas Gohr        }
256103c256aSChris Smith        if(!page_exists($pages[$i])){
257506fa893SAndreas Gohr            unset($pages[$i]);
258506fa893SAndreas Gohr            continue;
259506fa893SAndreas Gohr        }
260506fa893SAndreas Gohr    }
26163773904SAndreas Gohr
2620dc92c6fSAndreas Gohr    $pages = array_filter($pages,'isVisiblePage'); // discard hidden pages
26363773904SAndreas Gohr    if(!count($pages)) return array();
26463773904SAndreas Gohr
26563773904SAndreas Gohr    // check ACL permissions
26663773904SAndreas Gohr    foreach(array_keys($pages) as $idx){
26732ee5830SChris Smith        if(auth_quickaclcheck(trim($pages[$idx])) < AUTH_READ){
26863773904SAndreas Gohr            unset($pages[$idx]);
26963773904SAndreas Gohr        }
27063773904SAndreas Gohr    }
27163773904SAndreas Gohr
2726798a86aSAndreas Gohr    $pages = array_map('trim',$pages);
273f31eb72bSAndreas Gohr    usort($pages,'ft_pagesorter');
274506fa893SAndreas Gohr    return $pages;
275506fa893SAndreas Gohr}
276506fa893SAndreas Gohr
277506fa893SAndreas Gohr/**
278f31eb72bSAndreas Gohr * Sort pages based on their namespace level first, then on their string
279f31eb72bSAndreas Gohr * values. This makes higher hierarchy pages rank higher than lower hierarchy
280f31eb72bSAndreas Gohr * pages.
281f31eb72bSAndreas Gohr */
282f31eb72bSAndreas Gohrfunction ft_pagesorter($a, $b){
283f31eb72bSAndreas Gohr    $ac = count(explode(':',$a));
284f31eb72bSAndreas Gohr    $bc = count(explode(':',$b));
285f31eb72bSAndreas Gohr    if($ac < $bc){
286f31eb72bSAndreas Gohr        return -1;
287f31eb72bSAndreas Gohr    }elseif($ac > $bc){
288f31eb72bSAndreas Gohr        return 1;
289f31eb72bSAndreas Gohr    }
290f31eb72bSAndreas Gohr    return strcmp ($a,$b);
291f31eb72bSAndreas Gohr}
292f31eb72bSAndreas Gohr
293f31eb72bSAndreas Gohr/**
294506fa893SAndreas Gohr * Creates a snippet extract
295506fa893SAndreas Gohr *
296506fa893SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
297506fa893SAndreas Gohr */
298546d3a99SAndreas Gohrfunction ft_snippet($id,$highlight){
299506fa893SAndreas Gohr    $text     = rawWiki($id);
300ced0762eSchris    $match = array();
301ced0762eSchris    $snippets = array();
3029ee93076Schris    $utf8_offset = $offset = $end = 0;
303ced0762eSchris    $len = utf8_strlen($text);
3049ee93076Schris
305546d3a99SAndreas Gohr    // build a regexp from the phrases to highlight
306*b571ff2dSChuck Kollars    $re1 = '('.join('|',array_map('preg_quote_cb',array_filter((array) $highlight))).')';
307*b571ff2dSChuck Kollars    $re2 = "$re1.{0,75}(?!\\1)$re1";
308*b571ff2dSChuck Kollars    $re3 = "$re1.{0,45}(?!\\1)$re1.{0,45}(?!\\1)(?!\\2)$re1";
309546d3a99SAndreas Gohr
310*b571ff2dSChuck Kollars    for ($cnt=4; $cnt--;) {
311*b571ff2dSChuck Kollars      if (0) {
312*b571ff2dSChuck Kollars      } else if (preg_match('/'.$re3.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
313*b571ff2dSChuck Kollars      } else if (preg_match('/'.$re2.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
314*b571ff2dSChuck Kollars      } else if (preg_match('/'.$re1.'/iu',$text,$match,PREG_OFFSET_CAPTURE,$offset)) {
315*b571ff2dSChuck Kollars      } else {
316*b571ff2dSChuck Kollars        break;
317*b571ff2dSChuck Kollars      }
318ced0762eSchris
319ced0762eSchris      list($str,$idx) = $match[0];
320ced0762eSchris
321ced0762eSchris      // convert $idx (a byte offset) into a utf8 character offset
322ced0762eSchris      $utf8_idx = utf8_strlen(substr($text,0,$idx));
323ced0762eSchris      $utf8_len = utf8_strlen($str);
324ced0762eSchris
325ced0762eSchris      // establish context, 100 bytes surrounding the match string
326ced0762eSchris      // first look to see if we can go 100 either side,
327ced0762eSchris      // then drop to 50 adding any excess if the other side can't go to 50,
328ced0762eSchris      $pre = min($utf8_idx-$utf8_offset,100);
329ced0762eSchris      $post = min($len-$utf8_idx-$utf8_len,100);
330ced0762eSchris
331ced0762eSchris      if ($pre>50 && $post>50) {
332ced0762eSchris        $pre = $post = 50;
333ced0762eSchris      } else if ($pre>50) {
334ced0762eSchris        $pre = min($pre,100-$post);
335ced0762eSchris      } else if ($post>50) {
336ced0762eSchris        $post = min($post, 100-$pre);
337ced0762eSchris      } else {
338ced0762eSchris        // both are less than 50, means the context is the whole string
33910ffc9ddSAndreas Gohr        // make it so and break out of this loop - there is no need for the
34010ffc9ddSAndreas Gohr        // complex snippet calculations
341ced0762eSchris        $snippets = array($text);
342ced0762eSchris        break;
343ced0762eSchris      }
344ced0762eSchris
34510ffc9ddSAndreas Gohr      // establish context start and end points, try to append to previous
34610ffc9ddSAndreas Gohr      // context if possible
3479ee93076Schris      $start = $utf8_idx - $pre;
348ced0762eSchris      $append = ($start < $end) ? $end : false;  // still the end of the previous context snippet
3499ee93076Schris      $end = $utf8_idx + $utf8_len + $post;      // now set it to the end of this context
350ced0762eSchris
351ced0762eSchris      if ($append) {
352ced0762eSchris        $snippets[count($snippets)-1] .= utf8_substr($text,$append,$end-$append);
353ced0762eSchris      } else {
354ced0762eSchris        $snippets[] = utf8_substr($text,$start,$end-$start);
355ced0762eSchris      }
356ced0762eSchris
357ced0762eSchris      // set $offset for next match attempt
35810ffc9ddSAndreas Gohr      //   substract strlen to avoid splitting a potential search success,
35910ffc9ddSAndreas Gohr      //   this is an approximation as the search pattern may match strings
36010ffc9ddSAndreas Gohr      //   of varying length and it will fail if the context snippet
361ced0762eSchris      //   boundary breaks a matching string longer than the current match
3629ee93076Schris      $utf8_offset = $utf8_idx + $post;
3639ee93076Schris      $offset = $idx + strlen(utf8_substr($text,$utf8_idx,$post));
3649ee93076Schris      $offset = utf8_correctIdx($text,$offset);
3659ee93076Schris    }
3669ee93076Schris
367ced0762eSchris    $m = "\1";
368*b571ff2dSChuck Kollars    $snippets = preg_replace('/'.$re1.'/iu',$m.'$1'.$m,$snippets);
369*b571ff2dSChuck Kollars    $snippet = preg_replace('/'.$m.'([^'.$m.']*?)'.$m.'/iu','<strong class="search_hit">$1</strong>',hsc(join('... ',$snippets)));
370bd2cb6fcSchris
3715953e889Schris    return $snippet;
372506fa893SAndreas Gohr}
373506fa893SAndreas Gohr
374506fa893SAndreas Gohr/**
375f5eb7cf0SAndreas Gohr * Combine found documents and sum up their scores
376f5eb7cf0SAndreas Gohr *
377f5eb7cf0SAndreas Gohr * This function is used to combine searched words with a logical
378f5eb7cf0SAndreas Gohr * AND. Only documents available in all arrays are returned.
379f5eb7cf0SAndreas Gohr *
380f5eb7cf0SAndreas Gohr * based upon PEAR's PHP_Compat function for array_intersect_key()
381f5eb7cf0SAndreas Gohr *
382f5eb7cf0SAndreas Gohr * @param array $args An array of page arrays
383f5eb7cf0SAndreas Gohr */
384f5eb7cf0SAndreas Gohrfunction ft_resultCombine($args){
385f5eb7cf0SAndreas Gohr    $array_count = count($args);
386134f4ab2SAndreas Gohr    if($array_count == 1){
387134f4ab2SAndreas Gohr        return $args[0];
388134f4ab2SAndreas Gohr    }
389134f4ab2SAndreas Gohr
390f5eb7cf0SAndreas Gohr    $result = array();
39109c27a6dSGuy Brand    if ($array_count > 1) {
392a21136cdSAndreas Gohr      foreach ($args[0] as $key => $value) {
393a21136cdSAndreas Gohr        $result[$key] = $value;
394f5eb7cf0SAndreas Gohr        for ($i = 1; $i !== $array_count; $i++) {
395a21136cdSAndreas Gohr            if (!isset($args[$i][$key])) {
396a21136cdSAndreas Gohr                unset($result[$key]);
397a21136cdSAndreas Gohr                break;
398f5eb7cf0SAndreas Gohr            }
399a21136cdSAndreas Gohr            $result[$key] += $args[$i][$key];
400f5eb7cf0SAndreas Gohr        }
401f5eb7cf0SAndreas Gohr      }
40209c27a6dSGuy Brand    }
403f5eb7cf0SAndreas Gohr    return $result;
404f5eb7cf0SAndreas Gohr}
405f5eb7cf0SAndreas Gohr
406f5eb7cf0SAndreas Gohr/**
407f5eb7cf0SAndreas Gohr * Builds an array of search words from a query
408f5eb7cf0SAndreas Gohr *
409f5eb7cf0SAndreas Gohr * @todo support OR and parenthesises?
410f5eb7cf0SAndreas Gohr */
411f5eb7cf0SAndreas Gohrfunction ft_queryParser($query){
412f5eb7cf0SAndreas Gohr    global $conf;
413f5eb7cf0SAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
414f5eb7cf0SAndreas Gohr    if(@file_exists($swfile)){
415f5eb7cf0SAndreas Gohr        $stopwords = file($swfile);
416f5eb7cf0SAndreas Gohr    }else{
417f5eb7cf0SAndreas Gohr        $stopwords = array();
418f5eb7cf0SAndreas Gohr    }
419f5eb7cf0SAndreas Gohr
420f5eb7cf0SAndreas Gohr    $q = array();
421f5eb7cf0SAndreas Gohr    $q['query']   = $query;
422a219c1f0SMichael Klier chi@chimeric.de    $q['ns']      = array();
423b42bcfe7Sdaniel.lindgren    $q['notns']   = array();
424f5eb7cf0SAndreas Gohr    $q['phrases'] = array();
42560c15d7dSAndreas Gohr    $q['words']   = array();
426f5eb7cf0SAndreas Gohr    $q['and']     = array();
427f5eb7cf0SAndreas Gohr    $q['not']     = array();
428f5eb7cf0SAndreas Gohr
429f5eb7cf0SAndreas Gohr    // handle phrase searches
430f5eb7cf0SAndreas Gohr    while(preg_match('/"(.*?)"/',$query,$match)){
43193a60ad2SAndreas Gohr        $q['phrases'][] = $match[1];
432235cf363SAndreas Gohr        $q['and'] = array_merge($q['and'], idx_tokenizer($match[0],$stopwords));
433f5eb7cf0SAndreas Gohr        $query = preg_replace('/"(.*?)"/','',$query,1);
434f5eb7cf0SAndreas Gohr    }
435f5eb7cf0SAndreas Gohr
436f5eb7cf0SAndreas Gohr    $words = explode(' ',$query);
437f5eb7cf0SAndreas Gohr    foreach($words as $w){
438f5eb7cf0SAndreas Gohr        if($w{0} == '-'){
439ad81d431SAndreas Gohr            $token = idx_tokenizer($w,$stopwords,true);
440f5eb7cf0SAndreas Gohr            if(count($token)) $q['not'] = array_merge($q['not'],$token);
441b42bcfe7Sdaniel.lindgren        } else if ($w{0} == '@') { // Namespace to search?
442b42bcfe7Sdaniel.lindgren            $w = substr($w,1);
443b42bcfe7Sdaniel.lindgren            $q['ns'] = array_merge($q['ns'],(array)$w);
444b42bcfe7Sdaniel.lindgren        } else if ($w{0} == '^') { // Namespace not to search?
445b42bcfe7Sdaniel.lindgren            $w = substr($w,1);
446b42bcfe7Sdaniel.lindgren            $q['notns'] = array_merge($q['notns'],(array)$w);
447f5eb7cf0SAndreas Gohr        }else{
44893a60ad2SAndreas Gohr            // asian "words" need to be searched as phrases
44960c15d7dSAndreas Gohr            if(@preg_match_all('/(('.IDX_ASIAN.')+)/u',$w,$matches)){
45093a60ad2SAndreas Gohr                $q['phrases'] = array_merge($q['phrases'],$matches[1]);
45193a60ad2SAndreas Gohr
45293a60ad2SAndreas Gohr            }
453ad81d431SAndreas Gohr            $token = idx_tokenizer($w,$stopwords,true);
45460c15d7dSAndreas Gohr            if(count($token)){
45560c15d7dSAndreas Gohr                $q['and']   = array_merge($q['and'],$token);
45660c15d7dSAndreas Gohr                $q['words'] = array_merge($q['words'],$token);
45760c15d7dSAndreas Gohr            }
458f5eb7cf0SAndreas Gohr        }
459f5eb7cf0SAndreas Gohr    }
460f5eb7cf0SAndreas Gohr
461f5eb7cf0SAndreas Gohr    return $q;
462f5eb7cf0SAndreas Gohr}
463f5eb7cf0SAndreas Gohr
464506fa893SAndreas Gohr//Setup VIM: ex: et ts=4 enc=utf-8 :
465