xref: /dokuwiki/inc/fulltext.php (revision 54f4c05648c376908a736854a2ad279d57ec5b19)
1<?php
2/**
3 * DokuWiki fulltextsearch functions using the index
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 */
8
9  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
10  require_once(DOKU_INC.'inc/indexer.php');
11
12
13/**
14 * The fulltext search
15 *
16 * Returns a list of matching documents for the given query
17 *
18 */
19function ft_pageSearch($query,&$poswords){
20    $q = ft_queryParser($query);
21
22    // use this for higlighting later:
23    $poswords = join(' ',$q['and']);
24
25    // lookup all words found in the query
26    $words  = array_merge($q['and'],$q['not']);
27    if(!count($words)) return array();
28    $result = idx_lookup($words);
29
30    // merge search results with query
31    foreach($q['and'] as $pos => $w){
32        $q['and'][$pos] = $result[$w];
33    }
34    // create a list of unwanted docs
35    $not = array();
36    foreach($q['not'] as $pos => $w){
37        $not = array_merge($not,array_keys($result[$w]));
38    }
39
40    // combine and-words
41    if(count($q['and']) > 1){
42        $docs = ft_resultCombine($q['and']);
43    }else{
44        $docs = $q['and'][0];
45    }
46    if(!count($docs)) return array();
47
48    // remove negative matches
49    foreach($not as $n){
50        unset($docs[$n]);
51    }
52
53    if(!count($docs)) return array();
54
55    // handle phrases
56    if(count($q['phrases'])){
57        //build a regexp
58        $q['phrases'] = array_map('utf8_strtolower',$q['phrases']);
59        $q['phrases'] = array_map('preg_quote',$q['phrases']);
60        $regex = '('.join('|',$q['phrases']).')';
61
62        // check the source of all documents for the exact phrases
63        foreach(array_keys($docs) as $id){
64            $text  = utf8_strtolower(rawWiki($id));
65            if(!preg_match('/'.$regex.'/usi',$text)){
66                unset($docs[$id]); // no hit - remove
67            }
68        }
69    }
70
71    if(!count($docs)) return array();
72
73    // if there are any hits left, sort them by count
74    arsort($docs);
75
76    return $docs;
77}
78
79/**
80 * Returns the backlinks for a given page
81 *
82 * Does a quick lookup with the fulltext index, then
83 * evaluates the instructions of the found pages
84 */
85function ft_backlinks($id){
86    global $conf;
87    $result = array();
88
89    // quick lookup of the pagename
90    $page    = noNS($id);
91    $matches = idx_lookup(array($page));
92
93    if(!count($matches)) return $result;
94    require_once(DOKU_INC.'inc/parserutils.php');
95
96
97    // check instructions for matching links
98    foreach(array_keys($matches[$page]) as $match){
99        $instructions = p_cached_instructions(wikiFN($match),true);
100        if(is_null($instructions)) continue;
101
102        $match_ns =  getNS($match);
103
104        foreach($instructions as $ins){
105            if($ins[0] == 'internallink' || ($conf['camelcase'] && $ins[0] == 'camelcaselink') ){
106                $link = $ins[1][0];
107                resolve_pageid($match_ns,$link,$exists); //exists is not used
108                if($link == $id){
109                    //we have a match - finish
110                    $result[] = $match;
111                    break;
112                }
113            }
114        }
115    }
116
117    sort($result);
118    return $result;
119}
120
121/**
122 * Quicksearch for pagenames
123 *
124 * By default it only matches the pagename and ignores the
125 * namespace. This can be changed with the second parameter
126 *
127 * @author Andreas Gohr <andi@splitbrain.org>
128 */
129function ft_pageLookup($id,$pageonly=true){
130    global $conf;
131    $id    = preg_quote($id,'/');
132    $pages = file($conf['cachedir'].'/page.idx');
133    $pages = array_values(preg_grep('/'.$id.'/',$pages));
134
135    $cnt = count($pages);
136    for($i=0; $i<$cnt; $i++){
137        if($pageonly){
138            if(!preg_match('/'.$id.'/',noNS($pages[$i]))){
139                unset($pages[$i]);
140                continue;
141            }
142        }
143        if(!@file_exists(wikiFN($pages[$i]))){
144            unset($pages[$i]);
145            continue;
146        }
147    }
148    sort($pages);
149    return $pages;
150}
151
152/**
153 * Creates a snippet extract
154 *
155 * @author Andreas Gohr <andi@splitbrain.org>
156 */
157function ft_snippet($id,$poswords){
158    $poswords = preg_quote($poswords,'#');
159    $re       = '('.str_replace(' ','|',$poswords).')';
160    $text     = rawWiki($id);
161    //FIXME caseinsensitive matching doesn't work with UTF-8!?
162    preg_match_all('#(.{0,50})'.$re.'(.{0,50})#iu',$text,$matches,PREG_SET_ORDER);
163
164    $cnt = 0;
165    $snippet = '';
166    foreach($matches as $match){
167        $snippet .= '...'.htmlspecialchars($match[1]);
168        $snippet .= '<span class="search_hit">';
169        $snippet .= htmlspecialchars($match[2]);
170        $snippet .= '</span>';
171        $snippet .= htmlspecialchars($match[3]).'... ';
172        if($cnt++ == 2) break;
173    }
174
175    return $snippet;
176}
177
178/**
179 * Combine found documents and sum up their scores
180 *
181 * This function is used to combine searched words with a logical
182 * AND. Only documents available in all arrays are returned.
183 *
184 * based upon PEAR's PHP_Compat function for array_intersect_key()
185 *
186 * @param array $args An array of page arrays
187 */
188function ft_resultCombine($args){
189    $array_count = count($args);
190    $result = array();
191    foreach ($args[0] as $key1 => $value1) {
192        for ($i = 1; $i !== $array_count; $i++) {
193            foreach ($args[$i] as $key2 => $value2) {
194                if ((string) $key1 === (string) $key2) {
195                    if(!isset($result[$key1])) $result[$key1] = $value1;
196                    $result[$key1] += $value2;
197                }
198            }
199        }
200    }
201    return $result;
202}
203
204/**
205 * Builds an array of search words from a query
206 *
207 * @todo support OR and parenthesises?
208 */
209function ft_queryParser($query){
210    global $conf;
211    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
212    if(@file_exists($swfile)){
213        $stopwords = file($swfile);
214    }else{
215        $stopwords = array();
216    }
217
218    $q = array();
219    $q['query']   = $query;
220    $q['phrases'] = array();
221    $q['and']     = array();
222    $q['not']     = array();
223
224    // handle phrase searches
225    while(preg_match('/"(.*?)"/',$query,$match)){
226        $q['phrases'][] = $match[0];
227        $q['and'] = array_merge(idx_tokenizer($match[0],$stopwords));
228        $query = preg_replace('/"(.*?)"/','',$query,1);
229    }
230
231    $words = explode(' ',$query);
232    foreach($words as $w){
233        if($w{0} == '-'){
234            $token = idx_tokenizer($w,$stopwords);
235            if(count($token)) $q['not'] = array_merge($q['not'],$token);
236        }else{
237            $token = idx_tokenizer($w,$stopwords);
238            if(count($token)) $q['and'] = array_merge($q['and'],$token);
239        }
240    }
241
242    return $q;
243}
244
245//Setup VIM: ex: et ts=4 enc=utf-8 :
246