xref: /dokuwiki/inc/indexer.php (revision 33815ce27ad57e922146632ece1f6d9464db0225)
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
900976812SAndreas Gohr  if(!defined('DOKU_INC')) define('DOKU_INC',fullpath(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
15*33815ce2SChris Smith// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens)
16*33815ce2SChris Smithif (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',3);
17*33815ce2SChris Smith
1893a60ad2SAndreas Gohr// Asian characters are handled as words. The following regexp defines the
1993a60ad2SAndreas Gohr// Unicode-Ranges for Asian characters
2093a60ad2SAndreas Gohr// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block
2193a60ad2SAndreas Gohr// I'm no language expert. If you think some ranges are wrongly chosen or
2293a60ad2SAndreas Gohr// a range is missing, please contact me
23d5b23302STom N Harrisdefine('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai
24d5b23302STom N Harrisdefine('IDX_ASIAN2','['.
25d5b23302STom N Harris                   '\x{2E80}-\x{3040}'.  // CJK -> Hangul
26d5b23302STom N Harris                   '\x{309D}-\x{30A0}'.
27a0c5c349STom N Harris                   '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'.
2893a60ad2SAndreas Gohr                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
2993a60ad2SAndreas Gohr                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
3093a60ad2SAndreas Gohr                   ']');
31d5b23302STom N Harrisdefine('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
32d5b23302STom N Harris                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
33d5b23302STom N Harris                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
34d5b23302STom N Harris                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
35d5b23302STom N Harris                   '\x{308F}-\x{3094}'.
36d5b23302STom N Harris                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
37d5b23302STom N Harris                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
38d5b23302STom N Harris                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
39d5b23302STom N Harris                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
40d5b23302STom N Harris                   ']['.
41d5b23302STom N Harris                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
42d5b23302STom N Harris                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
43d5b23302STom N Harris                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
44d5b23302STom N Harris                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
45d5b23302STom N Harris                   '\x{31F0}-\x{31FF}'.
46d5b23302STom N Harris                   ']?');
47699b8a0bSAndreas Gohrdefine('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
4893a60ad2SAndreas Gohr
49b4ce25e9SAndreas Gohr/**
50d5b23302STom N Harris * Measure the length of a string.
51d5b23302STom N Harris * Differs from strlen in handling of asian characters.
52d5b23302STom N Harris *
53d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
54d5b23302STom N Harris */
55d5b23302STom N Harrisfunction wordlen($w){
56d5b23302STom N Harris    $l = strlen($w);
57d5b23302STom N Harris    // If left alone, all chinese "words" will get put into w3.idx
58d5b23302STom N Harris    // So the "length" of a "word" is faked
59d5b23302STom N Harris    if(preg_match('/'.IDX_ASIAN2.'/u',$w))
60d5b23302STom N Harris        $l += ord($w) - 0xE1;  // Lead bytes from 0xE2-0xEF
61d5b23302STom N Harris    return $l;
62d5b23302STom N Harris}
63d5b23302STom N Harris
64d5b23302STom N Harris/**
65579b0f7eSTNHarris * Write a list of strings to an index file.
66579b0f7eSTNHarris *
67579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
68579b0f7eSTNHarris */
69b6344591STom N Harrisfunction idx_saveIndex($pre, $wlen, &$idx){
70579b0f7eSTNHarris    global $conf;
71579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen;
72579b0f7eSTNHarris    $fh = @fopen($fn.'.tmp','w');
73579b0f7eSTNHarris    if(!$fh) return false;
74b6344591STom N Harris    foreach ($idx as $line) {
75b6344591STom N Harris        fwrite($fh,$line);
76b6344591STom N Harris    }
77579b0f7eSTNHarris    fclose($fh);
78579b0f7eSTNHarris    if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
79579b0f7eSTNHarris    io_rename($fn.'.tmp', $fn.'.idx');
80579b0f7eSTNHarris    return true;
81579b0f7eSTNHarris}
82579b0f7eSTNHarris
83579b0f7eSTNHarris/**
84579b0f7eSTNHarris * Read the list of words in an index (if it exists).
85579b0f7eSTNHarris *
86579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
87579b0f7eSTNHarris */
88579b0f7eSTNHarrisfunction idx_getIndex($pre, $wlen){
89579b0f7eSTNHarris    global $conf;
90579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
91579b0f7eSTNHarris    if(!@file_exists($fn)) return array();
92579b0f7eSTNHarris    return file($fn);
93579b0f7eSTNHarris}
94579b0f7eSTNHarris
95579b0f7eSTNHarris/**
96579b0f7eSTNHarris * Create an empty index file if it doesn't exist yet.
97579b0f7eSTNHarris *
98b6344591STom N Harris * FIXME: This function isn't currently used. It will probably be removed soon.
99b6344591STom N Harris *
100579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
101579b0f7eSTNHarris */
102579b0f7eSTNHarrisfunction idx_touchIndex($pre, $wlen){
103579b0f7eSTNHarris    global $conf;
104579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
105579b0f7eSTNHarris    if(!@file_exists($fn)){
106579b0f7eSTNHarris        touch($fn);
107579b0f7eSTNHarris        if($conf['fperm']) chmod($fn, $conf['fperm']);
108579b0f7eSTNHarris    }
109579b0f7eSTNHarris}
110579b0f7eSTNHarris
111579b0f7eSTNHarris/**
112b6344591STom N Harris * Read a line ending with \n.
113b6344591STom N Harris * Returns false on EOF.
114b6344591STom N Harris *
115b6344591STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
116b6344591STom N Harris */
117b6344591STom N Harrisfunction _freadline($fh) {
118b6344591STom N Harris    if (feof($fh)) return false;
119b6344591STom N Harris    $ln = '';
120b6344591STom N Harris    while (($buf = fgets($fh,4096)) !== false) {
121b6344591STom N Harris        $ln .= $buf;
122b6344591STom N Harris        if (substr($buf,-1) == "\n") break;
123b6344591STom N Harris    }
124b6344591STom N Harris    if ($ln === '') return false;
125b6344591STom N Harris    if (substr($ln,-1) != "\n") $ln .= "\n";
126b6344591STom N Harris    return $ln;
127b6344591STom N Harris}
128b6344591STom N Harris
129b6344591STom N Harris/**
130b6344591STom N Harris * Write a line to an index file.
131b6344591STom N Harris *
132b6344591STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
133b6344591STom N Harris */
134b6344591STom N Harrisfunction idx_saveIndexLine($pre, $wlen, $idx, $line){
135b6344591STom N Harris    global $conf;
136b6344591STom N Harris    if(substr($line,-1) != "\n") $line .= "\n";
137b6344591STom N Harris    $fn = $conf['indexdir'].'/'.$pre.$wlen;
138b6344591STom N Harris    $fh = @fopen($fn.'.tmp','w');
139b6344591STom N Harris    if(!$fh) return false;
140b6344591STom N Harris    $ih = @fopen($fn.'.idx','r');
141b6344591STom N Harris    if ($ih) {
142b6344591STom N Harris        $ln = -1;
143b6344591STom N Harris        while (($curline = _freadline($ih)) !== false) {
144b6344591STom N Harris            if (++$ln == $idx) {
145b6344591STom N Harris                fwrite($fh, $line);
146b6344591STom N Harris            } else {
147b6344591STom N Harris                fwrite($fh, $curline);
148b6344591STom N Harris            }
149b6344591STom N Harris        }
150b6344591STom N Harris        if ($idx > $ln) {
151b6344591STom N Harris            fwrite($fh,$line);
152b6344591STom N Harris        }
153b6344591STom N Harris        fclose($ih);
154b6344591STom N Harris    } else {
155b6344591STom N Harris        fwrite($fh,$line);
156b6344591STom N Harris    }
157b6344591STom N Harris    fclose($fh);
158b6344591STom N Harris    if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
159b6344591STom N Harris    io_rename($fn.'.tmp', $fn.'.idx');
160b6344591STom N Harris    return true;
161b6344591STom N Harris}
162b6344591STom N Harris
163b6344591STom N Harris/**
164b6344591STom N Harris * Read a single line from an index (if it exists).
165b6344591STom N Harris *
166b6344591STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
167b6344591STom N Harris */
168b6344591STom N Harrisfunction idx_getIndexLine($pre, $wlen, $idx){
169b6344591STom N Harris    global $conf;
170b6344591STom N Harris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
171b6344591STom N Harris    if(!@file_exists($fn)) return '';
172b6344591STom N Harris    $fh = @fopen($fn,'r');
173b6344591STom N Harris    if(!$fh) return '';
174b6344591STom N Harris    $ln = -1;
175b6344591STom N Harris    while (($line = _freadline($fh)) !== false) {
176b6344591STom N Harris        if (++$ln == $idx) break;
177b6344591STom N Harris    }
178b6344591STom N Harris    fclose($fh);
179b6344591STom N Harris    return "$line";
180b6344591STom N Harris}
181b6344591STom N Harris
182b6344591STom N Harris/**
18344ca0adfSAndreas Gohr * Split a page into words
18444ca0adfSAndreas Gohr *
185c9db30f9SAndreas Gohr * Returns an array of word counts, false if an error occurred.
186579b0f7eSTNHarris * Array is keyed on the word length, then the word index.
18744ca0adfSAndreas Gohr *
18844ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
18917f42b01SChris Smith * @author Christopher Smith <chris@jalakai.co.uk>
190b4ce25e9SAndreas Gohr */
19144ca0adfSAndreas Gohrfunction idx_getPageWords($page){
19244ca0adfSAndreas Gohr    global $conf;
1937367b368SAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
1947367b368SAndreas Gohr    if(@file_exists($swfile)){
1957367b368SAndreas Gohr        $stopwords = file($swfile);
1967367b368SAndreas Gohr    }else{
1977367b368SAndreas Gohr        $stopwords = array();
1987367b368SAndreas Gohr    }
19944ca0adfSAndreas Gohr
200a6a30c1aSEsther Brunner    $body = '';
20115018435SAndreas Gohr    $data = array($page, $body);
20215018435SAndreas Gohr    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
20315018435SAndreas Gohr    if ($evt->advise_before()) $data[1] .= rawWiki($page);
204a6a30c1aSEsther Brunner    $evt->advise_after();
205a6a30c1aSEsther Brunner    unset($evt);
206a6a30c1aSEsther Brunner
20715018435SAndreas Gohr    list($page,$body) = $data;
20815018435SAndreas Gohr
20917f42b01SChris Smith    $body   = strtr($body, "\r\n\t", '   ');
21017f42b01SChris Smith    $tokens = explode(' ', $body);
21117f42b01SChris Smith    $tokens = array_count_values($tokens);   // count the frequency of each token
21217f42b01SChris Smith
2136b06b652Schris    // ensure the deaccented or romanised page names of internal links are added to the token array
2146b06b652Schris    // (this is necessary for the backlink function -- there maybe a better way!)
2156b06b652Schris    if ($conf['deaccent']) {
2166b06b652Schris      $links = p_get_metadata($page,'relation references');
2176b06b652Schris
2183fc667cfSchris      if (!empty($links)) {
2196b06b652Schris        $tmp = join(' ',array_keys($links));                // make a single string
2206b06b652Schris        $tmp = strtr($tmp, ':', ' ');                       // replace namespace separator with a space
2216b06b652Schris        $link_tokens = array_unique(explode(' ', $tmp));    // break into tokens
2226b06b652Schris
2236b06b652Schris        foreach ($link_tokens as $link_token) {
2246b06b652Schris          if (isset($tokens[$link_token])) continue;
2256b06b652Schris          $tokens[$link_token] = 1;
2266b06b652Schris        }
2276b06b652Schris      }
2283fc667cfSchris    }
2296b06b652Schris
23017f42b01SChris Smith    $words = array();
23117f42b01SChris Smith    foreach ($tokens as $word => $count) {
232579b0f7eSTNHarris        $arr = idx_tokenizer($word,$stopwords);
23317f42b01SChris Smith        $arr = array_count_values($arr);
23417f42b01SChris Smith        foreach ($arr as $w => $c) {
235d5b23302STom N Harris            $l = wordlen($w);
236579b0f7eSTNHarris            if(isset($words[$l])){
237b2bc63f0SAndreas Gohr                $words[$l][$w] = $c * $count + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
23817f42b01SChris Smith            }else{
239579b0f7eSTNHarris                $words[$l] = array($w => $c * $count);
240579b0f7eSTNHarris            }
24117f42b01SChris Smith        }
24217f42b01SChris Smith    }
24317f42b01SChris Smith
244579b0f7eSTNHarris    // arrive here with $words = array(wordlen => array(word => frequency))
245b4ce25e9SAndreas Gohr
246b4ce25e9SAndreas Gohr    $index = array(); //resulting index
247579b0f7eSTNHarris    foreach (array_keys($words) as $wlen){
248579b0f7eSTNHarris        $word_idx = idx_getIndex('w',$wlen);
249579b0f7eSTNHarris        foreach ($words[$wlen] as $word => $freq) {
25044ca0adfSAndreas Gohr            $wid = array_search("$word\n",$word_idx);
25144ca0adfSAndreas Gohr            if(!is_int($wid)){
252d5b23302STom N Harris                $wid = count($word_idx);
25344ca0adfSAndreas Gohr                $word_idx[] = "$word\n";
254b4ce25e9SAndreas Gohr            }
255579b0f7eSTNHarris            if(!isset($index[$wlen]))
256579b0f7eSTNHarris                $index[$wlen] = array();
257579b0f7eSTNHarris            $index[$wlen][$wid] = $freq;
25844ca0adfSAndreas Gohr        }
25944ca0adfSAndreas Gohr
26044ca0adfSAndreas Gohr        // save back word index
261579b0f7eSTNHarris        if(!idx_saveIndex('w',$wlen,$word_idx)){
262579b0f7eSTNHarris            trigger_error("Failed to write word index", E_USER_ERROR);
26344ca0adfSAndreas Gohr            return false;
26444ca0adfSAndreas Gohr        }
265579b0f7eSTNHarris    }
266b4ce25e9SAndreas Gohr
267b4ce25e9SAndreas Gohr    return $index;
268b4ce25e9SAndreas Gohr}
269b4ce25e9SAndreas Gohr
27044ca0adfSAndreas Gohr/**
27144ca0adfSAndreas Gohr * Adds/updates the search for the given page
27244ca0adfSAndreas Gohr *
27344ca0adfSAndreas Gohr * This is the core function of the indexer which does most
27444ca0adfSAndreas Gohr * of the work. This function needs to be called with proper
27544ca0adfSAndreas Gohr * locking!
27644ca0adfSAndreas Gohr *
27744ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
27844ca0adfSAndreas Gohr */
27944ca0adfSAndreas Gohrfunction idx_addPage($page){
28044ca0adfSAndreas Gohr    global $conf;
281b4ce25e9SAndreas Gohr
282488dd6ceSAndreas Gohr    // load known documents
283579b0f7eSTNHarris    $page_idx = idx_getIndex('page','');
28444ca0adfSAndreas Gohr
28544ca0adfSAndreas Gohr    // get page id (this is the linenumber in page.idx)
28644ca0adfSAndreas Gohr    $pid = array_search("$page\n",$page_idx);
28744ca0adfSAndreas Gohr    if(!is_int($pid)){
28844ca0adfSAndreas Gohr        $page_idx[] = "$page\n";
28944ca0adfSAndreas Gohr        $pid = count($page_idx)-1;
29044ca0adfSAndreas Gohr        // page was new - write back
291d5b23302STom N Harris        if (!idx_saveIndex('page','',$page_idx)){
292d5b23302STom N Harris            trigger_error("Failed to write page index", E_USER_ERROR);
293579b0f7eSTNHarris            return false;
29444ca0adfSAndreas Gohr        }
295d5b23302STom N Harris    }
29644ca0adfSAndreas Gohr
297a0c5c349STom N Harris    $pagewords = array();
29844ca0adfSAndreas Gohr    // get word usage in page
29944ca0adfSAndreas Gohr    $words = idx_getPageWords($page);
30044ca0adfSAndreas Gohr    if($words === false) return false;
30144ca0adfSAndreas Gohr
302a0c5c349STom N Harris    if(!empty($words)) {
303579b0f7eSTNHarris        foreach(array_keys($words) as $wlen){
304d5b23302STom N Harris            $index = idx_getIndex('i',$wlen);
305d5b23302STom N Harris            foreach($words[$wlen] as $wid => $freq){
306d5b23302STom N Harris                if($wid<count($index)){
307d5b23302STom N Harris                    $index[$wid] = idx_updateIndexLine($index[$wid],$pid,$freq);
308d5b23302STom N Harris                }else{
309d5b23302STom N Harris                    // New words **should** have been added in increasing order
310d5b23302STom N Harris                    // starting with the first unassigned index.
311d5b23302STom N Harris                    // If someone can show how this isn't true, then I'll need to sort
312d5b23302STom N Harris                    // or do something special.
313d5b23302STom N Harris                    $index[$wid] = idx_updateIndexLine('',$pid,$freq);
314d5b23302STom N Harris                }
315a0c5c349STom N Harris                $pagewords[] = "$wlen*$wid";
316d5b23302STom N Harris            }
317d5b23302STom N Harris            // save back word index
318d5b23302STom N Harris            if(!idx_saveIndex('i',$wlen,$index)){
319d5b23302STom N Harris                trigger_error("Failed to write index", E_USER_ERROR);
32044ca0adfSAndreas Gohr                return false;
32144ca0adfSAndreas Gohr            }
322579b0f7eSTNHarris        }
323a0c5c349STom N Harris    }
324a0c5c349STom N Harris
325a0c5c349STom N Harris    // Remove obsolete index entries
326b6344591STom N Harris    $pageword_idx = trim(idx_getIndexLine('pageword','',$pid));
327b6344591STom N Harris    if ($pageword_idx !== '') {
328b6344591STom N Harris        $oldwords = explode(':',$pageword_idx);
329a0c5c349STom N Harris        $delwords = array_diff($oldwords, $pagewords);
330b6344591STom N Harris        $upwords = array();
331a0c5c349STom N Harris        foreach ($delwords as $word) {
332a0c5c349STom N Harris            if($word=='') continue;
333a0c5c349STom N Harris            list($wlen,$wid) = explode('*',$word);
334a0c5c349STom N Harris            $wid = (int)$wid;
335b6344591STom N Harris            $upwords[$wlen][] = $wid;
336b6344591STom N Harris        }
337b6344591STom N Harris        foreach ($upwords as $wlen => $widx) {
338a0c5c349STom N Harris            $index = idx_getIndex('i',$wlen);
339b6344591STom N Harris            foreach ($widx as $wid) {
340a0c5c349STom N Harris                $index[$wid] = idx_updateIndexLine($index[$wid],$pid,0);
341b6344591STom N Harris            }
342a0c5c349STom N Harris            idx_saveIndex('i',$wlen,$index);
343a0c5c349STom N Harris        }
344b6344591STom N Harris    }
345a0c5c349STom N Harris    // Save the reverse index
346b6344591STom N Harris    $pageword_idx = join(':',$pagewords)."\n";
347b6344591STom N Harris    if(!idx_saveIndexLine('pageword','',$pid,$pageword_idx)){
348a0c5c349STom N Harris        trigger_error("Failed to write word index", E_USER_ERROR);
349a0c5c349STom N Harris        return false;
350a0c5c349STom N Harris    }
351579b0f7eSTNHarris
352579b0f7eSTNHarris    return true;
35344ca0adfSAndreas Gohr}
35444ca0adfSAndreas Gohr
35544ca0adfSAndreas Gohr/**
35644ca0adfSAndreas Gohr * Write a new index line to the filehandle
35744ca0adfSAndreas Gohr *
35844ca0adfSAndreas Gohr * This function writes an line for the index file to the
35944ca0adfSAndreas Gohr * given filehandle. It removes the given document from
36044ca0adfSAndreas Gohr * the given line and readds it when $count is >0.
36144ca0adfSAndreas Gohr *
362d5b23302STom N Harris * @deprecated - see idx_updateIndexLine
36344ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
36444ca0adfSAndreas Gohr */
36544ca0adfSAndreas Gohrfunction idx_writeIndexLine($fh,$line,$pid,$count){
366d5b23302STom N Harris    fwrite($fh,idx_updateIndexLine($line,$pid,$count));
367d5b23302STom N Harris}
36844ca0adfSAndreas Gohr
369d5b23302STom N Harris/**
370d5b23302STom N Harris * Modify an index line with new information
371d5b23302STom N Harris *
372d5b23302STom N Harris * This returns a line of the index. It removes the
373d5b23302STom N Harris * given document from the line and readds it if
374d5b23302STom N Harris * $count is >0.
375d5b23302STom N Harris *
376d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
377d5b23302STom N Harris * @author Andreas Gohr <andi@splitbrain.org>
378d5b23302STom N Harris */
379d5b23302STom N Harrisfunction idx_updateIndexLine($line,$pid,$count){
380d5b23302STom N Harris    $line = trim($line);
381d5b23302STom N Harris    $updated = array();
38244ca0adfSAndreas Gohr    if($line != ''){
38344ca0adfSAndreas Gohr        $parts = explode(':',$line);
38444ca0adfSAndreas Gohr        // remove doc from given line
38544ca0adfSAndreas Gohr        foreach($parts as $part){
38644ca0adfSAndreas Gohr            if($part == '') continue;
38744ca0adfSAndreas Gohr            list($doc,$cnt) = explode('*',$part);
38844ca0adfSAndreas Gohr            if($doc != $pid){
389d5b23302STom N Harris                $updated[] = $part;
39044ca0adfSAndreas Gohr            }
39144ca0adfSAndreas Gohr        }
39244ca0adfSAndreas Gohr    }
39344ca0adfSAndreas Gohr
39444ca0adfSAndreas Gohr    // add doc
39544ca0adfSAndreas Gohr    if ($count){
396d5b23302STom N Harris        $updated[] = "$pid*$count";
39744ca0adfSAndreas Gohr    }
39844ca0adfSAndreas Gohr
399d5b23302STom N Harris    return join(':',$updated)."\n";
40044ca0adfSAndreas Gohr}
401b4ce25e9SAndreas Gohr
402488dd6ceSAndreas Gohr/**
403579b0f7eSTNHarris * Get the word lengths that have been indexed.
404579b0f7eSTNHarris *
405579b0f7eSTNHarris * Reads the index directory and returns an array of lengths
406579b0f7eSTNHarris * that there are indices for.
407579b0f7eSTNHarris *
408579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
409579b0f7eSTNHarris */
410d5b23302STom N Harrisfunction idx_indexLengths(&$filter){
411579b0f7eSTNHarris    global $conf;
412579b0f7eSTNHarris    $dir = @opendir($conf['indexdir']);
413579b0f7eSTNHarris    if($dir===false)
414579b0f7eSTNHarris        return array();
415579b0f7eSTNHarris    $idx = array();
416d5b23302STom N Harris    if(is_array($filter)){
417579b0f7eSTNHarris        while (($f = readdir($dir)) !== false) {
418579b0f7eSTNHarris            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
419579b0f7eSTNHarris                $i = substr($f,1,-4);
420d5b23302STom N Harris                if (is_numeric($i) && isset($filter[(int)$i]))
421d5b23302STom N Harris                    $idx[] = (int)$i;
422d5b23302STom N Harris            }
423d5b23302STom N Harris        }
424d5b23302STom N Harris    }else{
425d5b23302STom N Harris        // Exact match first.
426d5b23302STom N Harris        if(@file_exists($conf['indexdir']."/i$filter.idx"))
427d5b23302STom N Harris            $idx[] = $filter;
428d5b23302STom N Harris        while (($f = readdir($dir)) !== false) {
429d5b23302STom N Harris            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
430d5b23302STom N Harris                $i = substr($f,1,-4);
431d5b23302STom N Harris                if (is_numeric($i) && $i > $filter)
432d5b23302STom N Harris                    $idx[] = (int)$i;
433d5b23302STom N Harris            }
434579b0f7eSTNHarris        }
435579b0f7eSTNHarris    }
436579b0f7eSTNHarris    closedir($dir);
437579b0f7eSTNHarris    return $idx;
438579b0f7eSTNHarris}
439579b0f7eSTNHarris
440579b0f7eSTNHarris/**
441d5b23302STom N Harris * Find the the index number of each search term.
442d5b23302STom N Harris *
443adb16d4fSAndreas Gohr * This will group together words that appear in the same index.
444d5b23302STom N Harris * So it should perform better, because it only opens each index once.
445d5b23302STom N Harris * Actually, it's not that great. (in my experience) Probably because of the disk cache.
446d5b23302STom N Harris * And the sorted function does more work, making it slightly slower in some cases.
447d5b23302STom N Harris *
448d5b23302STom N Harris * @param array    $words   The query terms. Words should only contain valid characters,
449d5b23302STom N Harris *                          with a '*' at either the beginning or end of the word (or both)
450d5b23302STom N Harris * @param arrayref $result  Set to word => array("length*id" ...), use this to merge the
451d5b23302STom N Harris *                          index locations with the appropriate query term.
452d5b23302STom N Harris * @return array            Set to length => array(id ...)
453d5b23302STom N Harris *
454d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
455d5b23302STom N Harris */
456d5b23302STom N Harrisfunction idx_getIndexWordsSorted($words,&$result){
457d5b23302STom N Harris    // parse and sort tokens
458d5b23302STom N Harris    $tokens = array();
459d5b23302STom N Harris    $tokenlength = array();
460d5b23302STom N Harris    $tokenwild = array();
461d5b23302STom N Harris    foreach($words as $word){
462d5b23302STom N Harris        $result[$word] = array();
463d5b23302STom N Harris        $wild = 0;
464d5b23302STom N Harris        $xword = $word;
465d5b23302STom N Harris        $wlen = wordlen($word);
466d5b23302STom N Harris
467d5b23302STom N Harris        // check for wildcards
468d5b23302STom N Harris        if(substr($xword,0,1) == '*'){
469d5b23302STom N Harris            $xword = substr($xword,1);
470d5b23302STom N Harris            $wild |= 1;
471d5b23302STom N Harris            $wlen -= 1;
472d5b23302STom N Harris        }
473d5b23302STom N Harris        if(substr($xword,-1,1) == '*'){
474d5b23302STom N Harris            $xword = substr($xword,0,-1);
475d5b23302STom N Harris            $wild |= 2;
476d5b23302STom N Harris            $wlen -= 1;
477d5b23302STom N Harris        }
478*33815ce2SChris Smith        if ($wlen < IDX_MINWORDLENGTH && $wild == 0 && !is_numeric($xword)) continue;
479d5b23302STom N Harris        if(!isset($tokens[$xword])){
480d5b23302STom N Harris            $tokenlength[$wlen][] = $xword;
481d5b23302STom N Harris        }
482d5b23302STom N Harris        if($wild){
483d5b23302STom N Harris            $ptn = preg_quote($xword,'/');
484d5b23302STom N Harris            if(($wild&1) == 0) $ptn = '^'.$ptn;
485d5b23302STom N Harris            if(($wild&2) == 0) $ptn = $ptn.'$';
486d5b23302STom N Harris            $tokens[$xword][] = array($word, '/'.$ptn.'/');
487d5b23302STom N Harris            if(!isset($tokenwild[$xword])) $tokenwild[$xword] = $wlen;
488d5b23302STom N Harris        }else
489d5b23302STom N Harris            $tokens[$xword][] = array($word, null);
490d5b23302STom N Harris    }
491d5b23302STom N Harris    asort($tokenwild);
492d5b23302STom N Harris    // $tokens = array( base word => array( [ query word , grep pattern ] ... ) ... )
493d5b23302STom N Harris    // $tokenlength = array( base word length => base word ... )
494d5b23302STom N Harris    // $tokenwild = array( base word => base word length ... )
495d5b23302STom N Harris
496d5b23302STom N Harris    $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
497d5b23302STom N Harris    $indexes_known = idx_indexLengths($length_filter);
498d5b23302STom N Harris    if(!empty($tokenwild)) sort($indexes_known);
499d5b23302STom N Harris    // get word IDs
500d5b23302STom N Harris    $wids = array();
501d5b23302STom N Harris    foreach($indexes_known as $ixlen){
502d5b23302STom N Harris        $word_idx = idx_getIndex('w',$ixlen);
503d5b23302STom N Harris        // handle exact search
504d5b23302STom N Harris        if(isset($tokenlength[$ixlen])){
505d5b23302STom N Harris            foreach($tokenlength[$ixlen] as $xword){
506d5b23302STom N Harris                $wid = array_search("$xword\n",$word_idx);
507d5b23302STom N Harris                if(is_int($wid)){
508d5b23302STom N Harris                    $wids[$ixlen][] = $wid;
509d5b23302STom N Harris                    foreach($tokens[$xword] as $w)
510d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
511d5b23302STom N Harris                }
512d5b23302STom N Harris            }
513d5b23302STom N Harris        }
514d5b23302STom N Harris        // handle wildcard search
515d5b23302STom N Harris        foreach($tokenwild as $xword => $wlen){
516d5b23302STom N Harris            if($wlen >= $ixlen) break;
517d5b23302STom N Harris            foreach($tokens[$xword] as $w){
518d5b23302STom N Harris                if(is_null($w[1])) continue;
519d5b23302STom N Harris                foreach(array_keys(preg_grep($w[1],$word_idx)) as $wid){
520d5b23302STom N Harris                    $wids[$ixlen][] = $wid;
521d5b23302STom N Harris                    $result[$w[0]][] = "$ixlen*$wid";
522d5b23302STom N Harris                }
523d5b23302STom N Harris            }
524d5b23302STom N Harris        }
525d5b23302STom N Harris    }
526d5b23302STom N Harris  return $wids;
527d5b23302STom N Harris}
528d5b23302STom N Harris
529d5b23302STom N Harris/**
530488dd6ceSAndreas Gohr * Lookup words in index
531488dd6ceSAndreas Gohr *
532488dd6ceSAndreas Gohr * Takes an array of word and will return a list of matching
533488dd6ceSAndreas Gohr * documents for each one.
534488dd6ceSAndreas Gohr *
53563773904SAndreas Gohr * Important: No ACL checking is done here! All results are
53663773904SAndreas Gohr *            returned, regardless of permissions
53763773904SAndreas Gohr *
538488dd6ceSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
539488dd6ceSAndreas Gohr */
540488dd6ceSAndreas Gohrfunction idx_lookup($words){
541488dd6ceSAndreas Gohr    global $conf;
542488dd6ceSAndreas Gohr
543488dd6ceSAndreas Gohr    $result = array();
544488dd6ceSAndreas Gohr
545d5b23302STom N Harris    $wids = idx_getIndexWordsSorted($words, $result);
546d5b23302STom N Harris    if(empty($wids)) return array();
547d5b23302STom N Harris
548488dd6ceSAndreas Gohr    // load known words and documents
549579b0f7eSTNHarris    $page_idx = idx_getIndex('page','');
550488dd6ceSAndreas Gohr
551579b0f7eSTNHarris    $docs = array();                          // hold docs found
552579b0f7eSTNHarris    foreach(array_keys($wids) as $wlen){
553579b0f7eSTNHarris        $wids[$wlen] = array_unique($wids[$wlen]);
554d5b23302STom N Harris        $index = idx_getIndex('i',$wlen);
555d5b23302STom N Harris        foreach($wids[$wlen] as $ixid){
556d5b23302STom N Harris            if($ixid < count($index))
557d5b23302STom N Harris                $docs["$wlen*$ixid"] = idx_parseIndexLine($page_idx,$index[$ixid]);
558488dd6ceSAndreas Gohr        }
559488dd6ceSAndreas Gohr    }
560488dd6ceSAndreas Gohr
561ad81d431SAndreas Gohr    // merge found pages into final result array
562ad81d431SAndreas Gohr    $final = array();
563ad81d431SAndreas Gohr    foreach(array_keys($result) as $word){
564ad81d431SAndreas Gohr        $final[$word] = array();
565ad81d431SAndreas Gohr        foreach($result[$word] as $wid){
566ad81d431SAndreas Gohr            $hits = &$docs[$wid];
567ad81d431SAndreas Gohr            foreach ($hits as $hitkey => $hitcnt) {
568ad81d431SAndreas Gohr                $final[$word][$hitkey] = $hitcnt + $final[$word][$hitkey];
569ad81d431SAndreas Gohr            }
570ad81d431SAndreas Gohr        }
571ad81d431SAndreas Gohr    }
572ad81d431SAndreas Gohr    return $final;
573488dd6ceSAndreas Gohr}
574488dd6ceSAndreas Gohr
575488dd6ceSAndreas Gohr/**
576488dd6ceSAndreas Gohr * Returns a list of documents and counts from a index line
577488dd6ceSAndreas Gohr *
578488dd6ceSAndreas Gohr * It omits docs with a count of 0 and pages that no longer
579488dd6ceSAndreas Gohr * exist.
580488dd6ceSAndreas Gohr *
581488dd6ceSAndreas Gohr * @param  array  $page_idx The list of known pages
582488dd6ceSAndreas Gohr * @param  string $line     A line from the main index
583488dd6ceSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
584488dd6ceSAndreas Gohr */
585488dd6ceSAndreas Gohrfunction idx_parseIndexLine(&$page_idx,$line){
586488dd6ceSAndreas Gohr    $result = array();
587488dd6ceSAndreas Gohr
588488dd6ceSAndreas Gohr    $line = trim($line);
589f5eb7cf0SAndreas Gohr    if($line == '') return $result;
590488dd6ceSAndreas Gohr
591488dd6ceSAndreas Gohr    $parts = explode(':',$line);
592488dd6ceSAndreas Gohr    foreach($parts as $part){
593488dd6ceSAndreas Gohr        if($part == '') continue;
594488dd6ceSAndreas Gohr        list($doc,$cnt) = explode('*',$part);
595488dd6ceSAndreas Gohr        if(!$cnt) continue;
596488dd6ceSAndreas Gohr        $doc = trim($page_idx[$doc]);
597488dd6ceSAndreas Gohr        if(!$doc) continue;
598488dd6ceSAndreas Gohr        // make sure the document still exists
599103c256aSChris Smith        if(!page_exists($doc,'',false)) continue;
600488dd6ceSAndreas Gohr
601488dd6ceSAndreas Gohr        $result[$doc] = $cnt;
602488dd6ceSAndreas Gohr    }
603488dd6ceSAndreas Gohr    return $result;
604488dd6ceSAndreas Gohr}
605488dd6ceSAndreas Gohr
606f5eb7cf0SAndreas Gohr/**
607f5eb7cf0SAndreas Gohr * Tokenizes a string into an array of search words
608f5eb7cf0SAndreas Gohr *
609f5eb7cf0SAndreas Gohr * Uses the same algorithm as idx_getPageWords()
610f5eb7cf0SAndreas Gohr *
611ad81d431SAndreas Gohr * @param string   $string     the query as given by the user
612ad81d431SAndreas Gohr * @param arrayref $stopwords  array of stopwords
613ad81d431SAndreas Gohr * @param boolean  $wc         are wildcards allowed?
614f5eb7cf0SAndreas Gohr */
615ad81d431SAndreas Gohrfunction idx_tokenizer($string,&$stopwords,$wc=false){
616f5eb7cf0SAndreas Gohr    $words = array();
6174efb9a42SAndreas Gohr    $wc = ($wc) ? '' : $wc = '\*';
618f5eb7cf0SAndreas Gohr
619f5eb7cf0SAndreas Gohr    if(preg_match('/[^0-9A-Za-z]/u', $string)){
62091bb5faaSAndreas Gohr        // handle asian chars as single words (may fail on older PHP version)
62160c15d7dSAndreas Gohr        $asia = @preg_replace('/('.IDX_ASIAN.')/u',' \1 ',$string);
62291bb5faaSAndreas Gohr        if(!is_null($asia)) $string = $asia; //recover from regexp failure
62393a60ad2SAndreas Gohr
6244efb9a42SAndreas Gohr        $arr = explode(' ', utf8_stripspecials($string,' ','\._\-:'.$wc));
625f5eb7cf0SAndreas Gohr        foreach ($arr as $w) {
626*33815ce2SChris Smith            if (!is_numeric($w) && strlen($w) < IDX_MINWORDLENGTH) continue;
627f5eb7cf0SAndreas Gohr            $w = utf8_strtolower($w);
6283cbaa9a4SAndreas Gohr            if($stopwords && is_int(array_search("$w\n",$stopwords))) continue;
629f5eb7cf0SAndreas Gohr            $words[] = $w;
630f5eb7cf0SAndreas Gohr        }
631f5eb7cf0SAndreas Gohr    }else{
632f5eb7cf0SAndreas Gohr        $w = $string;
633*33815ce2SChris Smith        if (!is_numeric($w) && strlen($w) < IDX_MINWORDLENGTH) return $words;
634f5eb7cf0SAndreas Gohr        $w = strtolower($w);
635f5eb7cf0SAndreas Gohr        if(is_int(array_search("$w\n",$stopwords))) return $words;
636f5eb7cf0SAndreas Gohr        $words[] = $w;
637f5eb7cf0SAndreas Gohr    }
638f5eb7cf0SAndreas Gohr
639f5eb7cf0SAndreas Gohr    return $words;
640f5eb7cf0SAndreas Gohr}
641f5eb7cf0SAndreas Gohr
642a0c5c349STom N Harris/**
643a0c5c349STom N Harris * Create a pagewords index from the existing index.
644a0c5c349STom N Harris *
645a0c5c349STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
646a0c5c349STom N Harris */
647a0c5c349STom N Harrisfunction idx_upgradePageWords(){
648a0c5c349STom N Harris    global $conf;
649a0c5c349STom N Harris    $page_idx = idx_getIndex('page','');
650a0c5c349STom N Harris    if (empty($page_idx)) return;
651a0c5c349STom N Harris    $pagewords = array();
652a0c5c349STom N Harris    for ($n=0;$n<count($page_idx);$n++) $pagewords[] = array();
653a0c5c349STom N Harris    unset($page_idx);
654a0c5c349STom N Harris
655a0c5c349STom N Harris    $n=0;
656a0c5c349STom N Harris    foreach (idx_indexLengths($n) as $wlen) {
657a0c5c349STom N Harris        $lines = idx_getIndex('i',$wlen);
658a0c5c349STom N Harris        for ($wid=0;$wid<count($lines);$wid++) {
659a0c5c349STom N Harris            $wkey = "$wlen*$wid";
660a0c5c349STom N Harris            foreach (explode(':',trim($lines[$wid])) as $part) {
661a0c5c349STom N Harris                if($part == '') continue;
662a0c5c349STom N Harris                list($doc,$cnt) = explode('*',$part);
663a0c5c349STom N Harris                $pagewords[(int)$doc][] = $wkey;
664a0c5c349STom N Harris            }
665a0c5c349STom N Harris        }
666a0c5c349STom N Harris    }
667a0c5c349STom N Harris
668b6344591STom N Harris    $fn = $conf['indexdir'].'/pageword';
669b6344591STom N Harris    $fh = @fopen($fn.'.tmp','w');
670b6344591STom N Harris    if (!$fh){
671a0c5c349STom N Harris        trigger_error("Failed to write word index", E_USER_ERROR);
672a0c5c349STom N Harris        return false;
673a0c5c349STom N Harris    }
674b6344591STom N Harris    foreach ($pagewords as $line){
675b6344591STom N Harris        fwrite($fh, join(':',$line)."\n");
676b6344591STom N Harris    }
677b6344591STom N Harris    fclose($fh);
678b6344591STom N Harris    if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
679b6344591STom N Harris    io_rename($fn.'.tmp', $fn.'.idx');
680a0c5c349STom N Harris    return true;
681a0c5c349STom N Harris}
682a0c5c349STom N Harris
683b4ce25e9SAndreas Gohr//Setup VIM: ex: et ts=4 enc=utf-8 :
684