xref: /dokuwiki/inc/indexer.php (revision c9db30f969ec4cb1dd52dd6a54aa8ab15b1ce37b)
1b4ce25e9SAndreas Gohr<?php
2b4ce25e9SAndreas Gohr/**
3b4ce25e9SAndreas Gohr * Common DokuWiki functions
4b4ce25e9SAndreas Gohr *
5b4ce25e9SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6b4ce25e9SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
7b4ce25e9SAndreas Gohr */
8b4ce25e9SAndreas Gohr
9b4ce25e9SAndreas Gohr  if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../').'/');
10b4ce25e9SAndreas Gohr  require_once(DOKU_CONF.'dokuwiki.php');
11b4ce25e9SAndreas Gohr  require_once(DOKU_INC.'inc/io.php');
12b4ce25e9SAndreas Gohr  require_once(DOKU_INC.'inc/utf8.php');
13b4ce25e9SAndreas Gohr  require_once(DOKU_INC.'inc/parserutils.php');
14b4ce25e9SAndreas Gohr
1593a60ad2SAndreas Gohr// Asian characters are handled as words. The following regexp defines the
1693a60ad2SAndreas Gohr// Unicode-Ranges for Asian characters
1793a60ad2SAndreas Gohr// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block
1893a60ad2SAndreas Gohr// I'm no language expert. If you think some ranges are wrongly chosen or
1993a60ad2SAndreas Gohr// a range is missing, please contact me
20d5b23302STom N Harrisdefine('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai
21d5b23302STom N Harrisdefine('IDX_ASIAN2','['.
22d5b23302STom N Harris                   '\x{2E80}-\x{3040}'.  // CJK -> Hangul
23d5b23302STom N Harris                   '\x{309D}-\x{30A0}'.
24d5b23302STom N Harris                   '\x{30FB}-\x{31EF}\x{3200}-\x{D7AF}'.
2593a60ad2SAndreas Gohr                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
2693a60ad2SAndreas Gohr                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
2793a60ad2SAndreas Gohr                   ']');
28d5b23302STom N Harrisdefine('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
29d5b23302STom N Harris                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
30d5b23302STom N Harris                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
31d5b23302STom N Harris                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
32d5b23302STom N Harris                   '\x{308F}-\x{3094}'.
33d5b23302STom N Harris                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
34d5b23302STom N Harris                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
35d5b23302STom N Harris                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
36d5b23302STom N Harris                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
37d5b23302STom N Harris                   ']['.
38d5b23302STom N Harris                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
39d5b23302STom N Harris                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
40d5b23302STom N Harris                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
41d5b23302STom N Harris                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
42d5b23302STom N Harris                   '\x{31F0}-\x{31FF}'.
43d5b23302STom N Harris                   ']?');
44699b8a0bSAndreas Gohrdefine('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
4593a60ad2SAndreas Gohr
46b4ce25e9SAndreas Gohr/**
47d5b23302STom N Harris * Measure the length of a string.
48d5b23302STom N Harris * Differs from strlen in handling of asian characters.
49d5b23302STom N Harris *
50d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
51d5b23302STom N Harris */
52d5b23302STom N Harrisfunction wordlen($w){
53d5b23302STom N Harris    $l = strlen($w);
54d5b23302STom N Harris    // If left alone, all chinese "words" will get put into w3.idx
55d5b23302STom N Harris    // So the "length" of a "word" is faked
56d5b23302STom N Harris    if(preg_match('/'.IDX_ASIAN2.'/u',$w))
57d5b23302STom N Harris        $l += ord($w) - 0xE1;  // Lead bytes from 0xE2-0xEF
58d5b23302STom N Harris    return $l;
59d5b23302STom N Harris}
60d5b23302STom N Harris
61d5b23302STom N Harris/**
62579b0f7eSTNHarris * Write a list of strings to an index file.
63579b0f7eSTNHarris *
64579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
65579b0f7eSTNHarris */
66579b0f7eSTNHarrisfunction idx_saveIndex($pre, $wlen, $idx){
67579b0f7eSTNHarris    global $conf;
68579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen;
69579b0f7eSTNHarris    $fh = @fopen($fn.'.tmp','w');
70579b0f7eSTNHarris    if(!$fh) return false;
71579b0f7eSTNHarris    fwrite($fh,join('',$idx));
72579b0f7eSTNHarris    fclose($fh);
73579b0f7eSTNHarris    if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
74579b0f7eSTNHarris    io_rename($fn.'.tmp', $fn.'.idx');
75579b0f7eSTNHarris    return true;
76579b0f7eSTNHarris}
77579b0f7eSTNHarris
78579b0f7eSTNHarris/**
79579b0f7eSTNHarris * Read the list of words in an index (if it exists).
80579b0f7eSTNHarris *
81579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
82579b0f7eSTNHarris */
83579b0f7eSTNHarrisfunction idx_getIndex($pre, $wlen){
84579b0f7eSTNHarris    global $conf;
85579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
86579b0f7eSTNHarris    if(!@file_exists($fn)) return array();
87579b0f7eSTNHarris    return file($fn);
88579b0f7eSTNHarris}
89579b0f7eSTNHarris
90579b0f7eSTNHarris/**
91579b0f7eSTNHarris * Create an empty index file if it doesn't exist yet.
92579b0f7eSTNHarris *
93579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
94579b0f7eSTNHarris */
95579b0f7eSTNHarrisfunction idx_touchIndex($pre, $wlen){
96579b0f7eSTNHarris    global $conf;
97579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
98579b0f7eSTNHarris    if(!@file_exists($fn)){
99579b0f7eSTNHarris        touch($fn);
100579b0f7eSTNHarris        if($conf['fperm']) chmod($fn, $conf['fperm']);
101579b0f7eSTNHarris    }
102579b0f7eSTNHarris}
103579b0f7eSTNHarris
104579b0f7eSTNHarris/**
10544ca0adfSAndreas Gohr * Split a page into words
10644ca0adfSAndreas Gohr *
107*c9db30f9SAndreas Gohr * Returns an array of word counts, false if an error occurred.
108579b0f7eSTNHarris * Array is keyed on the word length, then the word index.
10944ca0adfSAndreas Gohr *
11044ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
11117f42b01SChris Smith * @author Christopher Smith <chris@jalakai.co.uk>
112b4ce25e9SAndreas Gohr */
11344ca0adfSAndreas Gohrfunction idx_getPageWords($page){
11444ca0adfSAndreas Gohr    global $conf;
1157367b368SAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
1167367b368SAndreas Gohr    if(@file_exists($swfile)){
1177367b368SAndreas Gohr        $stopwords = file($swfile);
1187367b368SAndreas Gohr    }else{
1197367b368SAndreas Gohr        $stopwords = array();
1207367b368SAndreas Gohr    }
12144ca0adfSAndreas Gohr
122a6a30c1aSEsther Brunner    $body = '';
12315018435SAndreas Gohr    $data = array($page, $body);
12415018435SAndreas Gohr    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
12515018435SAndreas Gohr    if ($evt->advise_before()) $data[1] .= rawWiki($page);
126a6a30c1aSEsther Brunner    $evt->advise_after();
127a6a30c1aSEsther Brunner    unset($evt);
128a6a30c1aSEsther Brunner
12915018435SAndreas Gohr    list($page,$body) = $data;
13015018435SAndreas Gohr
13117f42b01SChris Smith    $body   = strtr($body, "\r\n\t", '   ');
13217f42b01SChris Smith    $tokens = explode(' ', $body);
13317f42b01SChris Smith    $tokens = array_count_values($tokens);   // count the frequency of each token
13417f42b01SChris Smith
1356b06b652Schris    // ensure the deaccented or romanised page names of internal links are added to the token array
1366b06b652Schris    // (this is necessary for the backlink function -- there maybe a better way!)
1376b06b652Schris    if ($conf['deaccent']) {
1386b06b652Schris      $links = p_get_metadata($page,'relation references');
1396b06b652Schris
1403fc667cfSchris      if (!empty($links)) {
1416b06b652Schris        $tmp = join(' ',array_keys($links));                // make a single string
1426b06b652Schris        $tmp = strtr($tmp, ':', ' ');                       // replace namespace separator with a space
1436b06b652Schris        $link_tokens = array_unique(explode(' ', $tmp));    // break into tokens
1446b06b652Schris
1456b06b652Schris        foreach ($link_tokens as $link_token) {
1466b06b652Schris          if (isset($tokens[$link_token])) continue;
1476b06b652Schris          $tokens[$link_token] = 1;
1486b06b652Schris        }
1496b06b652Schris      }
1503fc667cfSchris    }
1516b06b652Schris
15217f42b01SChris Smith    $words = array();
15317f42b01SChris Smith    foreach ($tokens as $word => $count) {
154579b0f7eSTNHarris        $arr = idx_tokenizer($word,$stopwords);
15517f42b01SChris Smith        $arr = array_count_values($arr);
15617f42b01SChris Smith        foreach ($arr as $w => $c) {
157d5b23302STom N Harris            $l = wordlen($w);
158579b0f7eSTNHarris            if(isset($words[$l])){
159b2bc63f0SAndreas Gohr                $words[$l][$w] = $c * $count + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
16017f42b01SChris Smith            }else{
161579b0f7eSTNHarris                $words[$l] = array($w => $c * $count);
162579b0f7eSTNHarris            }
16317f42b01SChris Smith        }
16417f42b01SChris Smith    }
16517f42b01SChris Smith
166579b0f7eSTNHarris    // arrive here with $words = array(wordlen => array(word => frequency))
167b4ce25e9SAndreas Gohr
168b4ce25e9SAndreas Gohr    $index = array(); //resulting index
169579b0f7eSTNHarris    foreach (array_keys($words) as $wlen){
170579b0f7eSTNHarris        $word_idx = idx_getIndex('w',$wlen);
171579b0f7eSTNHarris        foreach ($words[$wlen] as $word => $freq) {
17244ca0adfSAndreas Gohr            $wid = array_search("$word\n",$word_idx);
17344ca0adfSAndreas Gohr            if(!is_int($wid)){
174d5b23302STom N Harris                $wid = count($word_idx);
17544ca0adfSAndreas Gohr                $word_idx[] = "$word\n";
176b4ce25e9SAndreas Gohr            }
177579b0f7eSTNHarris            if(!isset($index[$wlen]))
178579b0f7eSTNHarris                $index[$wlen] = array();
179579b0f7eSTNHarris            $index[$wlen][$wid] = $freq;
18044ca0adfSAndreas Gohr        }
18144ca0adfSAndreas Gohr
18244ca0adfSAndreas Gohr        // save back word index
183579b0f7eSTNHarris        if(!idx_saveIndex('w',$wlen,$word_idx)){
184579b0f7eSTNHarris            trigger_error("Failed to write word index", E_USER_ERROR);
18544ca0adfSAndreas Gohr            return false;
18644ca0adfSAndreas Gohr        }
187579b0f7eSTNHarris    }
188b4ce25e9SAndreas Gohr
189b4ce25e9SAndreas Gohr    return $index;
190b4ce25e9SAndreas Gohr}
191b4ce25e9SAndreas Gohr
19244ca0adfSAndreas Gohr/**
19344ca0adfSAndreas Gohr * Adds/updates the search for the given page
19444ca0adfSAndreas Gohr *
19544ca0adfSAndreas Gohr * This is the core function of the indexer which does most
19644ca0adfSAndreas Gohr * of the work. This function needs to be called with proper
19744ca0adfSAndreas Gohr * locking!
19844ca0adfSAndreas Gohr *
19944ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
20044ca0adfSAndreas Gohr */
20144ca0adfSAndreas Gohrfunction idx_addPage($page){
20244ca0adfSAndreas Gohr    global $conf;
203b4ce25e9SAndreas Gohr
204488dd6ceSAndreas Gohr    // load known documents
205579b0f7eSTNHarris    $page_idx = idx_getIndex('page','');
20644ca0adfSAndreas Gohr
20744ca0adfSAndreas Gohr    // get page id (this is the linenumber in page.idx)
20844ca0adfSAndreas Gohr    $pid = array_search("$page\n",$page_idx);
20944ca0adfSAndreas Gohr    if(!is_int($pid)){
21044ca0adfSAndreas Gohr        $page_idx[] = "$page\n";
21144ca0adfSAndreas Gohr        $pid = count($page_idx)-1;
21244ca0adfSAndreas Gohr        // page was new - write back
213d5b23302STom N Harris        if (!idx_saveIndex('page','',$page_idx)){
214d5b23302STom N Harris            trigger_error("Failed to write page index", E_USER_ERROR);
215579b0f7eSTNHarris            return false;
21644ca0adfSAndreas Gohr        }
217d5b23302STom N Harris    }
21844ca0adfSAndreas Gohr
21944ca0adfSAndreas Gohr    // get word usage in page
22044ca0adfSAndreas Gohr    $words = idx_getPageWords($page);
22144ca0adfSAndreas Gohr    if($words === false) return false;
22244ca0adfSAndreas Gohr    if(!count($words)) return true;
22344ca0adfSAndreas Gohr
224579b0f7eSTNHarris    foreach(array_keys($words) as $wlen){
225d5b23302STom N Harris        $index = idx_getIndex('i',$wlen);
226d5b23302STom N Harris        foreach($words[$wlen] as $wid => $freq){
227d5b23302STom N Harris            if($wid<count($index)){
228d5b23302STom N Harris                $index[$wid] = idx_updateIndexLine($index[$wid],$pid,$freq);
229d5b23302STom N Harris            }else{
230d5b23302STom N Harris                // New words **should** have been added in increasing order
231d5b23302STom N Harris                // starting with the first unassigned index.
232d5b23302STom N Harris                // If someone can show how this isn't true, then I'll need to sort
233d5b23302STom N Harris                // or do something special.
234d5b23302STom N Harris                $index[$wid] = idx_updateIndexLine('',$pid,$freq);
235d5b23302STom N Harris            }
236d5b23302STom N Harris        }
237d5b23302STom N Harris        // save back word index
238d5b23302STom N Harris        if(!idx_saveIndex('i',$wlen,$index)){
239d5b23302STom N Harris            trigger_error("Failed to write index", E_USER_ERROR);
24044ca0adfSAndreas Gohr            return false;
24144ca0adfSAndreas Gohr        }
242579b0f7eSTNHarris    }
243579b0f7eSTNHarris
244579b0f7eSTNHarris    return true;
24544ca0adfSAndreas Gohr}
24644ca0adfSAndreas Gohr
24744ca0adfSAndreas Gohr/**
24844ca0adfSAndreas Gohr * Write a new index line to the filehandle
24944ca0adfSAndreas Gohr *
25044ca0adfSAndreas Gohr * This function writes an line for the index file to the
25144ca0adfSAndreas Gohr * given filehandle. It removes the given document from
25244ca0adfSAndreas Gohr * the given line and readds it when $count is >0.
25344ca0adfSAndreas Gohr *
254d5b23302STom N Harris * @deprecated - see idx_updateIndexLine
25544ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
25644ca0adfSAndreas Gohr */
25744ca0adfSAndreas Gohrfunction idx_writeIndexLine($fh,$line,$pid,$count){
258d5b23302STom N Harris    fwrite($fh,idx_updateIndexLine($line,$pid,$count));
259d5b23302STom N Harris}
26044ca0adfSAndreas Gohr
261d5b23302STom N Harris/**
262d5b23302STom N Harris * Modify an index line with new information
263d5b23302STom N Harris *
264d5b23302STom N Harris * This returns a line of the index. It removes the
265d5b23302STom N Harris * given document from the line and readds it if
266d5b23302STom N Harris * $count is >0.
267d5b23302STom N Harris *
268d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
269d5b23302STom N Harris * @author Andreas Gohr <andi@splitbrain.org>
270d5b23302STom N Harris */
271d5b23302STom N Harrisfunction idx_updateIndexLine($line,$pid,$count){
272d5b23302STom N Harris    $line = trim($line);
273d5b23302STom N Harris    $updated = array();
27444ca0adfSAndreas Gohr    if($line != ''){
27544ca0adfSAndreas Gohr        $parts = explode(':',$line);
27644ca0adfSAndreas Gohr        // remove doc from given line
27744ca0adfSAndreas Gohr        foreach($parts as $part){
27844ca0adfSAndreas Gohr            if($part == '') continue;
27944ca0adfSAndreas Gohr            list($doc,$cnt) = explode('*',$part);
28044ca0adfSAndreas Gohr            if($doc != $pid){
281d5b23302STom N Harris                $updated[] = $part;
28244ca0adfSAndreas Gohr            }
28344ca0adfSAndreas Gohr        }
28444ca0adfSAndreas Gohr    }
28544ca0adfSAndreas Gohr
28644ca0adfSAndreas Gohr    // add doc
28744ca0adfSAndreas Gohr    if ($count){
288d5b23302STom N Harris        $updated[] = "$pid*$count";
28944ca0adfSAndreas Gohr    }
29044ca0adfSAndreas Gohr
291d5b23302STom N Harris    return join(':',$updated)."\n";
29244ca0adfSAndreas Gohr}
293b4ce25e9SAndreas Gohr
294488dd6ceSAndreas Gohr/**
295579b0f7eSTNHarris * Get the word lengths that have been indexed.
296579b0f7eSTNHarris *
297579b0f7eSTNHarris * Reads the index directory and returns an array of lengths
298579b0f7eSTNHarris * that there are indices for.
299579b0f7eSTNHarris *
300579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
301579b0f7eSTNHarris */
302d5b23302STom N Harrisfunction idx_indexLengths(&$filter){
303579b0f7eSTNHarris    global $conf;
304579b0f7eSTNHarris    $dir = @opendir($conf['indexdir']);
305579b0f7eSTNHarris    if($dir===false)
306579b0f7eSTNHarris        return array();
307579b0f7eSTNHarris    $idx = array();
308d5b23302STom N Harris    if(is_array($filter)){
309579b0f7eSTNHarris        while (($f = readdir($dir)) !== false) {
310579b0f7eSTNHarris            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
311579b0f7eSTNHarris                $i = substr($f,1,-4);
312d5b23302STom N Harris                if (is_numeric($i) && isset($filter[(int)$i]))
313d5b23302STom N Harris                    $idx[] = (int)$i;
314d5b23302STom N Harris            }
315d5b23302STom N Harris        }
316d5b23302STom N Harris    }else{
317d5b23302STom N Harris        // Exact match first.
318d5b23302STom N Harris        if(@file_exists($conf['indexdir']."/i$filter.idx"))
319d5b23302STom N Harris            $idx[] = $filter;
320d5b23302STom N Harris        while (($f = readdir($dir)) !== false) {
321d5b23302STom N Harris            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
322d5b23302STom N Harris                $i = substr($f,1,-4);
323d5b23302STom N Harris                if (is_numeric($i) && $i > $filter)
324d5b23302STom N Harris                    $idx[] = (int)$i;
325d5b23302STom N Harris            }
326579b0f7eSTNHarris        }
327579b0f7eSTNHarris    }
328579b0f7eSTNHarris    closedir($dir);
329579b0f7eSTNHarris    return $idx;
330579b0f7eSTNHarris}
331579b0f7eSTNHarris
332579b0f7eSTNHarris/**
333d5b23302STom N Harris * Find the the index number of each search term.
334d5b23302STom N Harris *
335adb16d4fSAndreas Gohr * This will group together words that appear in the same index.
336d5b23302STom N Harris * So it should perform better, because it only opens each index once.
337d5b23302STom N Harris * Actually, it's not that great. (in my experience) Probably because of the disk cache.
338d5b23302STom N Harris * And the sorted function does more work, making it slightly slower in some cases.
339d5b23302STom N Harris *
340d5b23302STom N Harris * @param array    $words   The query terms. Words should only contain valid characters,
341d5b23302STom N Harris *                          with a '*' at either the beginning or end of the word (or both)
342d5b23302STom N Harris * @param arrayref $result  Set to word => array("length*id" ...), use this to merge the
343d5b23302STom N Harris *                          index locations with the appropriate query term.
344d5b23302STom N Harris * @return array            Set to length => array(id ...)
345d5b23302STom N Harris *
346d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
347d5b23302STom N Harris */
348d5b23302STom N Harrisfunction idx_getIndexWordsSorted($words,&$result){
349d5b23302STom N Harris    // parse and sort tokens
350d5b23302STom N Harris    $tokens = array();
351d5b23302STom N Harris    $tokenlength = array();
352d5b23302STom N Harris    $tokenwild = array();
353d5b23302STom N Harris    foreach($words as $word){
354d5b23302STom N Harris        $result[$word] = array();
355d5b23302STom N Harris        $wild = 0;
356d5b23302STom N Harris        $xword = $word;
357d5b23302STom N Harris        $wlen = wordlen($word);
358d5b23302STom N Harris
359d5b23302STom N Harris        // check for wildcards
360d5b23302STom N Harris        if(substr($xword,0,1) == '*'){
361d5b23302STom N Harris            $xword = substr($xword,1);
362d5b23302STom N Harris            $wild |= 1;
363d5b23302STom N Harris            $wlen -= 1;
364d5b23302STom N Harris        }
365d5b23302STom N Harris        if(substr($xword,-1,1) == '*'){
366d5b23302STom N Harris            $xword = substr($xword,0,-1);
367d5b23302STom N Harris            $wild |= 2;
368d5b23302STom N Harris            $wlen -= 1;
369d5b23302STom N Harris        }
370d5b23302STom N Harris        if ($wlen < 3 && $wild == 0 && !is_numeric($xword)) continue;
371d5b23302STom N Harris        if(!isset($tokens[$xword])){
372d5b23302STom N Harris            $tokenlength[$wlen][] = $xword;
373d5b23302STom N Harris        }
374d5b23302STom N Harris        if($wild){
375d5b23302STom N Harris            $ptn = preg_quote($xword,'/');
376d5b23302STom N Harris            if(($wild&1) == 0) $ptn = '^'.$ptn;
377d5b23302STom N Harris            if(($wild&2) == 0) $ptn = $ptn.'$';
378d5b23302STom N Harris            $tokens[$xword][] = array($word, '/'.$ptn.'/');
379d5b23302STom N Harris            if(!isset($tokenwild[$xword])) $tokenwild[$xword] = $wlen;
380d5b23302STom N Harris        }else
381d5b23302STom N Harris            $tokens[$xword][] = array($word, null);
382d5b23302STom N Harris    }
383d5b23302STom N Harris    asort($tokenwild);
384d5b23302STom N Harris    // $tokens = array( base word => array( [ query word , grep pattern ] ... ) ... )
385d5b23302STom N Harris    // $tokenlength = array( base word length => base word ... )
386d5b23302STom N Harris    // $tokenwild = array( base word => base word length ... )
387d5b23302STom N Harris
388d5b23302STom N Harris    $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
389d5b23302STom N Harris    $indexes_known = idx_indexLengths($length_filter);
390d5b23302STom N Harris    if(!empty($tokenwild)) sort($indexes_known);
391d5b23302STom N Harris    // get word IDs
392d5b23302STom N Harris    $wids = array();
393d5b23302STom N Harris    echo "\n";
394d5b23302STom N Harris    foreach($indexes_known as $ixlen){
395d5b23302STom N Harris        $word_idx = idx_getIndex('w',$ixlen);
396d5b23302STom N Harris        // handle exact search
397d5b23302STom N Harris        if(isset($tokenlength[$ixlen])){
398d5b23302STom N Harris            foreach($tokenlength[$ixlen] as $xword){
399d5b23302STom N Harris                $wid = array_search("$xword\n",$word_idx);
400d5b23302STom N Harris                if(is_int($wid)){
401d5b23302STom N Harris                    $wids[$ixlen][] = $wid;
402d5b23302STom N Harris                    foreach($tokens[$xword] as $w)
403d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
404d5b23302STom N Harris                }
405d5b23302STom N Harris            }
406d5b23302STom N Harris        }
407d5b23302STom N Harris        // handle wildcard search
408d5b23302STom N Harris        foreach($tokenwild as $xword => $wlen){
409d5b23302STom N Harris            if($wlen >= $ixlen) break;
410d5b23302STom N Harris            foreach($tokens[$xword] as $w){
411d5b23302STom N Harris                if(is_null($w[1])) continue;
412d5b23302STom N Harris                foreach(array_keys(preg_grep($w[1],$word_idx)) as $wid){
413d5b23302STom N Harris                    $wids[$ixlen][] = $wid;
414d5b23302STom N Harris                    $result[$w[0]][] = "$ixlen*$wid";
415d5b23302STom N Harris                }
416d5b23302STom N Harris            }
417d5b23302STom N Harris        }
418d5b23302STom N Harris    }
419d5b23302STom N Harris  return $wids;
420d5b23302STom N Harris}
421d5b23302STom N Harris
422d5b23302STom N Harris/**
423488dd6ceSAndreas Gohr * Lookup words in index
424488dd6ceSAndreas Gohr *
425488dd6ceSAndreas Gohr * Takes an array of word and will return a list of matching
426488dd6ceSAndreas Gohr * documents for each one.
427488dd6ceSAndreas Gohr *
42863773904SAndreas Gohr * Important: No ACL checking is done here! All results are
42963773904SAndreas Gohr *            returned, regardless of permissions
43063773904SAndreas Gohr *
431488dd6ceSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
432488dd6ceSAndreas Gohr */
433488dd6ceSAndreas Gohrfunction idx_lookup($words){
434488dd6ceSAndreas Gohr    global $conf;
435488dd6ceSAndreas Gohr
436488dd6ceSAndreas Gohr    $result = array();
437488dd6ceSAndreas Gohr
438d5b23302STom N Harris    $wids = idx_getIndexWordsSorted($words, $result);
439d5b23302STom N Harris    if(empty($wids)) return array();
440d5b23302STom N Harris
441488dd6ceSAndreas Gohr    // load known words and documents
442579b0f7eSTNHarris    $page_idx = idx_getIndex('page','');
443488dd6ceSAndreas Gohr
444579b0f7eSTNHarris    $docs = array();                          // hold docs found
445579b0f7eSTNHarris    foreach(array_keys($wids) as $wlen){
446579b0f7eSTNHarris        $wids[$wlen] = array_unique($wids[$wlen]);
447d5b23302STom N Harris        $index = idx_getIndex('i',$wlen);
448d5b23302STom N Harris        foreach($wids[$wlen] as $ixid){
449d5b23302STom N Harris            if($ixid < count($index))
450d5b23302STom N Harris                $docs["$wlen*$ixid"] = idx_parseIndexLine($page_idx,$index[$ixid]);
451488dd6ceSAndreas Gohr        }
452488dd6ceSAndreas Gohr    }
453488dd6ceSAndreas Gohr
454ad81d431SAndreas Gohr    // merge found pages into final result array
455ad81d431SAndreas Gohr    $final = array();
456ad81d431SAndreas Gohr    foreach(array_keys($result) as $word){
457ad81d431SAndreas Gohr        $final[$word] = array();
458ad81d431SAndreas Gohr        foreach($result[$word] as $wid){
459ad81d431SAndreas Gohr            $hits = &$docs[$wid];
460ad81d431SAndreas Gohr            foreach ($hits as $hitkey => $hitcnt) {
461ad81d431SAndreas Gohr                $final[$word][$hitkey] = $hitcnt + $final[$word][$hitkey];
462ad81d431SAndreas Gohr            }
463ad81d431SAndreas Gohr        }
464ad81d431SAndreas Gohr    }
465ad81d431SAndreas Gohr    return $final;
466488dd6ceSAndreas Gohr}
467488dd6ceSAndreas Gohr
468488dd6ceSAndreas Gohr/**
469488dd6ceSAndreas Gohr * Returns a list of documents and counts from a index line
470488dd6ceSAndreas Gohr *
471488dd6ceSAndreas Gohr * It omits docs with a count of 0 and pages that no longer
472488dd6ceSAndreas Gohr * exist.
473488dd6ceSAndreas Gohr *
474488dd6ceSAndreas Gohr * @param  array  $page_idx The list of known pages
475488dd6ceSAndreas Gohr * @param  string $line     A line from the main index
476488dd6ceSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
477488dd6ceSAndreas Gohr */
478488dd6ceSAndreas Gohrfunction idx_parseIndexLine(&$page_idx,$line){
479488dd6ceSAndreas Gohr    $result = array();
480488dd6ceSAndreas Gohr
481488dd6ceSAndreas Gohr    $line = trim($line);
482f5eb7cf0SAndreas Gohr    if($line == '') return $result;
483488dd6ceSAndreas Gohr
484488dd6ceSAndreas Gohr    $parts = explode(':',$line);
485488dd6ceSAndreas Gohr    foreach($parts as $part){
486488dd6ceSAndreas Gohr        if($part == '') continue;
487488dd6ceSAndreas Gohr        list($doc,$cnt) = explode('*',$part);
488488dd6ceSAndreas Gohr        if(!$cnt) continue;
489488dd6ceSAndreas Gohr        $doc = trim($page_idx[$doc]);
490488dd6ceSAndreas Gohr        if(!$doc) continue;
491488dd6ceSAndreas Gohr        // make sure the document still exists
4920d8ea614Schris        if(!@file_exists(wikiFN($doc,'',false))) continue;
493488dd6ceSAndreas Gohr
494488dd6ceSAndreas Gohr        $result[$doc] = $cnt;
495488dd6ceSAndreas Gohr    }
496488dd6ceSAndreas Gohr    return $result;
497488dd6ceSAndreas Gohr}
498488dd6ceSAndreas Gohr
499f5eb7cf0SAndreas Gohr/**
500f5eb7cf0SAndreas Gohr * Tokenizes a string into an array of search words
501f5eb7cf0SAndreas Gohr *
502f5eb7cf0SAndreas Gohr * Uses the same algorithm as idx_getPageWords()
503f5eb7cf0SAndreas Gohr *
504ad81d431SAndreas Gohr * @param string   $string     the query as given by the user
505ad81d431SAndreas Gohr * @param arrayref $stopwords  array of stopwords
506ad81d431SAndreas Gohr * @param boolean  $wc         are wildcards allowed?
507f5eb7cf0SAndreas Gohr */
508ad81d431SAndreas Gohrfunction idx_tokenizer($string,&$stopwords,$wc=false){
509f5eb7cf0SAndreas Gohr    $words = array();
5104efb9a42SAndreas Gohr    $wc = ($wc) ? '' : $wc = '\*';
511f5eb7cf0SAndreas Gohr
512f5eb7cf0SAndreas Gohr    if(preg_match('/[^0-9A-Za-z]/u', $string)){
51391bb5faaSAndreas Gohr        // handle asian chars as single words (may fail on older PHP version)
514d5b23302STom N Harris        $asia = @preg_replace('/('.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')/u',' \1 ',$string);
51591bb5faaSAndreas Gohr        if(!is_null($asia)) $string = $asia; //recover from regexp failure
51693a60ad2SAndreas Gohr
5174efb9a42SAndreas Gohr        $arr = explode(' ', utf8_stripspecials($string,' ','\._\-:'.$wc));
518f5eb7cf0SAndreas Gohr        foreach ($arr as $w) {
519f5eb7cf0SAndreas Gohr            if (!is_numeric($w) && strlen($w) < 3) continue;
520f5eb7cf0SAndreas Gohr            $w = utf8_strtolower($w);
5213cbaa9a4SAndreas Gohr            if($stopwords && is_int(array_search("$w\n",$stopwords))) continue;
522f5eb7cf0SAndreas Gohr            $words[] = $w;
523f5eb7cf0SAndreas Gohr        }
524f5eb7cf0SAndreas Gohr    }else{
525f5eb7cf0SAndreas Gohr        $w = $string;
526f5eb7cf0SAndreas Gohr        if (!is_numeric($w) && strlen($w) < 3) return $words;
527f5eb7cf0SAndreas Gohr        $w = strtolower($w);
528f5eb7cf0SAndreas Gohr        if(is_int(array_search("$w\n",$stopwords))) return $words;
529f5eb7cf0SAndreas Gohr        $words[] = $w;
530f5eb7cf0SAndreas Gohr    }
531f5eb7cf0SAndreas Gohr
532f5eb7cf0SAndreas Gohr    return $words;
533f5eb7cf0SAndreas Gohr}
534f5eb7cf0SAndreas Gohr
535b4ce25e9SAndreas Gohr//Setup VIM: ex: et ts=4 enc=utf-8 :
536