xref: /dokuwiki/inc/indexer.php (revision 229529655f061863ec76db9ea557fef8b1a5161b)
1b4ce25e9SAndreas Gohr<?php
2b4ce25e9SAndreas Gohr/**
3fcd3bb7cSAndreas Gohr * Functions to create the fulltext search index
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
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
10b4ce25e9SAndreas Gohr
1133815ce2SChris Smith// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens)
12d3fb3219SAndreas Gohrif (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2);
1333815ce2SChris Smith
1493a60ad2SAndreas Gohr// Asian characters are handled as words. The following regexp defines the
1593a60ad2SAndreas Gohr// Unicode-Ranges for Asian characters
1693a60ad2SAndreas Gohr// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block
1793a60ad2SAndreas Gohr// I'm no language expert. If you think some ranges are wrongly chosen or
1893a60ad2SAndreas Gohr// a range is missing, please contact me
19d5b23302STom N Harrisdefine('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai
20d5b23302STom N Harrisdefine('IDX_ASIAN2','['.
21d5b23302STom N Harris                   '\x{2E80}-\x{3040}'.  // CJK -> Hangul
22d5b23302STom N Harris                   '\x{309D}-\x{30A0}'.
23a0c5c349STom N Harris                   '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'.
2493a60ad2SAndreas Gohr                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
2593a60ad2SAndreas Gohr                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
2693a60ad2SAndreas Gohr                   ']');
27d5b23302STom N Harrisdefine('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
28d5b23302STom N Harris                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
29d5b23302STom N Harris                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
30d5b23302STom N Harris                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
31d5b23302STom N Harris                   '\x{308F}-\x{3094}'.
32d5b23302STom N Harris                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
33d5b23302STom N Harris                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
34d5b23302STom N Harris                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
35d5b23302STom N Harris                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
36d5b23302STom N Harris                   ']['.
37d5b23302STom N Harris                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
38d5b23302STom N Harris                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
39d5b23302STom N Harris                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
40d5b23302STom N Harris                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
41d5b23302STom N Harris                   '\x{31F0}-\x{31FF}'.
42d5b23302STom N Harris                   ']?');
43699b8a0bSAndreas Gohrdefine('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
4493a60ad2SAndreas Gohr
45b4ce25e9SAndreas Gohr/**
46d5b23302STom N Harris * Measure the length of a string.
47d5b23302STom N Harris * Differs from strlen in handling of asian characters.
48d5b23302STom N Harris *
49d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
50d5b23302STom N Harris */
51d5b23302STom N Harrisfunction wordlen($w){
52d5b23302STom N Harris    $l = strlen($w);
53d5b23302STom N Harris    // If left alone, all chinese "words" will get put into w3.idx
54d5b23302STom N Harris    // So the "length" of a "word" is faked
55d5b23302STom N Harris    if(preg_match('/'.IDX_ASIAN2.'/u',$w))
56d5b23302STom N Harris        $l += ord($w) - 0xE1;  // Lead bytes from 0xE2-0xEF
57d5b23302STom N Harris    return $l;
58d5b23302STom N Harris}
59d5b23302STom N Harris
60d5b23302STom N Harris/**
61579b0f7eSTNHarris * Write a list of strings to an index file.
62579b0f7eSTNHarris *
63579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
64579b0f7eSTNHarris */
65b6344591STom N Harrisfunction idx_saveIndex($pre, $wlen, &$idx){
66579b0f7eSTNHarris    global $conf;
67579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen;
68579b0f7eSTNHarris    $fh = @fopen($fn.'.tmp','w');
69579b0f7eSTNHarris    if(!$fh) return false;
70b6344591STom N Harris    foreach ($idx as $line) {
71b6344591STom N Harris        fwrite($fh,$line);
72b6344591STom N Harris    }
73579b0f7eSTNHarris    fclose($fh);
74c66972f2SAdrian Lang    if(isset($conf['fperm'])) chmod($fn.'.tmp', $conf['fperm']);
75579b0f7eSTNHarris    io_rename($fn.'.tmp', $fn.'.idx');
76579b0f7eSTNHarris    return true;
77579b0f7eSTNHarris}
78579b0f7eSTNHarris
79579b0f7eSTNHarris/**
80dd35e9c9SAndreas Gohr * Append a given line to an index file.
81dd35e9c9SAndreas Gohr *
82dd35e9c9SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
83dd35e9c9SAndreas Gohr */
84dd35e9c9SAndreas Gohrfunction idx_appendIndex($pre, $wlen, $line){
85dd35e9c9SAndreas Gohr    global $conf;
86dd35e9c9SAndreas Gohr    $fn = $conf['indexdir'].'/'.$pre.$wlen;
87dd35e9c9SAndreas Gohr    $fh = @fopen($fn.'.idx','a');
88dd35e9c9SAndreas Gohr    if(!$fh) return false;
89dd35e9c9SAndreas Gohr    fwrite($fh,$line);
90dd35e9c9SAndreas Gohr    fclose($fh);
91dd35e9c9SAndreas Gohr    return true;
92dd35e9c9SAndreas Gohr}
93dd35e9c9SAndreas Gohr
94dd35e9c9SAndreas Gohr/**
95579b0f7eSTNHarris * Read the list of words in an index (if it exists).
96579b0f7eSTNHarris *
97579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
98579b0f7eSTNHarris */
99579b0f7eSTNHarrisfunction idx_getIndex($pre, $wlen){
100579b0f7eSTNHarris    global $conf;
101579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
102579b0f7eSTNHarris    if(!@file_exists($fn)) return array();
103579b0f7eSTNHarris    return file($fn);
104579b0f7eSTNHarris}
105579b0f7eSTNHarris
106579b0f7eSTNHarris/**
107579b0f7eSTNHarris * Create an empty index file if it doesn't exist yet.
108579b0f7eSTNHarris *
109b6344591STom N Harris * FIXME: This function isn't currently used. It will probably be removed soon.
110b6344591STom N Harris *
111579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
112579b0f7eSTNHarris */
113579b0f7eSTNHarrisfunction idx_touchIndex($pre, $wlen){
114579b0f7eSTNHarris    global $conf;
115579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
116579b0f7eSTNHarris    if(!@file_exists($fn)){
117579b0f7eSTNHarris        touch($fn);
118579b0f7eSTNHarris        if($conf['fperm']) chmod($fn, $conf['fperm']);
119579b0f7eSTNHarris    }
120579b0f7eSTNHarris}
121579b0f7eSTNHarris
122579b0f7eSTNHarris/**
123b6344591STom N Harris * Read a line ending with \n.
124b6344591STom N Harris * Returns false on EOF.
125b6344591STom N Harris *
126b6344591STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
127b6344591STom N Harris */
128b6344591STom N Harrisfunction _freadline($fh) {
129b6344591STom N Harris    if (feof($fh)) return false;
130b6344591STom N Harris    $ln = '';
131b6344591STom N Harris    while (($buf = fgets($fh,4096)) !== false) {
132b6344591STom N Harris        $ln .= $buf;
133b6344591STom N Harris        if (substr($buf,-1) == "\n") break;
134b6344591STom N Harris    }
135b6344591STom N Harris    if ($ln === '') return false;
136b6344591STom N Harris    if (substr($ln,-1) != "\n") $ln .= "\n";
137b6344591STom N Harris    return $ln;
138b6344591STom N Harris}
139b6344591STom N Harris
140b6344591STom N Harris/**
141b6344591STom N Harris * Write a line to an index file.
142b6344591STom N Harris *
143b6344591STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
144b6344591STom N Harris */
145b6344591STom N Harrisfunction idx_saveIndexLine($pre, $wlen, $idx, $line){
146b6344591STom N Harris    global $conf;
147b6344591STom N Harris    if(substr($line,-1) != "\n") $line .= "\n";
148b6344591STom N Harris    $fn = $conf['indexdir'].'/'.$pre.$wlen;
149b6344591STom N Harris    $fh = @fopen($fn.'.tmp','w');
150b6344591STom N Harris    if(!$fh) return false;
151b6344591STom N Harris    $ih = @fopen($fn.'.idx','r');
152b6344591STom N Harris    if ($ih) {
153b6344591STom N Harris        $ln = -1;
154b6344591STom N Harris        while (($curline = _freadline($ih)) !== false) {
155b6344591STom N Harris            if (++$ln == $idx) {
156b6344591STom N Harris                fwrite($fh, $line);
157b6344591STom N Harris            } else {
158b6344591STom N Harris                fwrite($fh, $curline);
159b6344591STom N Harris            }
160b6344591STom N Harris        }
161b6344591STom N Harris        if ($idx > $ln) {
162b6344591STom N Harris            fwrite($fh,$line);
163b6344591STom N Harris        }
164b6344591STom N Harris        fclose($ih);
165b6344591STom N Harris    } else {
166b6344591STom N Harris        fwrite($fh,$line);
167b6344591STom N Harris    }
168b6344591STom N Harris    fclose($fh);
169b6344591STom N Harris    if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
170b6344591STom N Harris    io_rename($fn.'.tmp', $fn.'.idx');
171b6344591STom N Harris    return true;
172b6344591STom N Harris}
173b6344591STom N Harris
174b6344591STom N Harris/**
175b6344591STom N Harris * Read a single line from an index (if it exists).
176b6344591STom N Harris *
177b6344591STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
178b6344591STom N Harris */
179b6344591STom N Harrisfunction idx_getIndexLine($pre, $wlen, $idx){
180b6344591STom N Harris    global $conf;
181b6344591STom N Harris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
182b6344591STom N Harris    if(!@file_exists($fn)) return '';
183b6344591STom N Harris    $fh = @fopen($fn,'r');
184b6344591STom N Harris    if(!$fh) return '';
185b6344591STom N Harris    $ln = -1;
186b6344591STom N Harris    while (($line = _freadline($fh)) !== false) {
187b6344591STom N Harris        if (++$ln == $idx) break;
188b6344591STom N Harris    }
189b6344591STom N Harris    fclose($fh);
190b6344591STom N Harris    return "$line";
191b6344591STom N Harris}
192b6344591STom N Harris
193b6344591STom N Harris/**
19444ca0adfSAndreas Gohr * Split a page into words
19544ca0adfSAndreas Gohr *
196c9db30f9SAndreas Gohr * Returns an array of word counts, false if an error occurred.
197579b0f7eSTNHarris * Array is keyed on the word length, then the word index.
19844ca0adfSAndreas Gohr *
19944ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
20017f42b01SChris Smith * @author Christopher Smith <chris@jalakai.co.uk>
201b4ce25e9SAndreas Gohr */
20244ca0adfSAndreas Gohrfunction idx_getPageWords($page){
20344ca0adfSAndreas Gohr    global $conf;
2047367b368SAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
2057367b368SAndreas Gohr    if(@file_exists($swfile)){
2067367b368SAndreas Gohr        $stopwords = file($swfile);
2077367b368SAndreas Gohr    }else{
2087367b368SAndreas Gohr        $stopwords = array();
2097367b368SAndreas Gohr    }
21044ca0adfSAndreas Gohr
211a6a30c1aSEsther Brunner    $body = '';
21215018435SAndreas Gohr    $data = array($page, $body);
21315018435SAndreas Gohr    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
21415018435SAndreas Gohr    if ($evt->advise_before()) $data[1] .= rawWiki($page);
215a6a30c1aSEsther Brunner    $evt->advise_after();
216a6a30c1aSEsther Brunner    unset($evt);
217a6a30c1aSEsther Brunner
21815018435SAndreas Gohr    list($page,$body) = $data;
21915018435SAndreas Gohr
22017f42b01SChris Smith    $body   = strtr($body, "\r\n\t", '   ');
22117f42b01SChris Smith    $tokens = explode(' ', $body);
22217f42b01SChris Smith    $tokens = array_count_values($tokens);   // count the frequency of each token
22317f42b01SChris Smith
2246b06b652Schris    // ensure the deaccented or romanised page names of internal links are added to the token array
2256b06b652Schris    // (this is necessary for the backlink function -- there maybe a better way!)
2266b06b652Schris    if ($conf['deaccent']) {
2276b06b652Schris        $links = p_get_metadata($page,'relation references');
2286b06b652Schris
2293fc667cfSchris        if (!empty($links)) {
2306b06b652Schris            $tmp = join(' ',array_keys($links));                // make a single string
2316b06b652Schris            $tmp = strtr($tmp, ':', ' ');                       // replace namespace separator with a space
2326b06b652Schris            $link_tokens = array_unique(explode(' ', $tmp));    // break into tokens
2336b06b652Schris
2346b06b652Schris            foreach ($link_tokens as $link_token) {
2356b06b652Schris                if (isset($tokens[$link_token])) continue;
2366b06b652Schris                $tokens[$link_token] = 1;
2376b06b652Schris            }
2386b06b652Schris        }
2393fc667cfSchris    }
2406b06b652Schris
24117f42b01SChris Smith    $words = array();
24217f42b01SChris Smith    foreach ($tokens as $word => $count) {
243579b0f7eSTNHarris        $arr = idx_tokenizer($word,$stopwords);
24417f42b01SChris Smith        $arr = array_count_values($arr);
24517f42b01SChris Smith        foreach ($arr as $w => $c) {
246d5b23302STom N Harris            $l = wordlen($w);
247579b0f7eSTNHarris            if(isset($words[$l])){
248b2bc63f0SAndreas Gohr                $words[$l][$w] = $c * $count + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
24917f42b01SChris Smith            }else{
250579b0f7eSTNHarris                $words[$l] = array($w => $c * $count);
251579b0f7eSTNHarris            }
25217f42b01SChris Smith        }
25317f42b01SChris Smith    }
25417f42b01SChris Smith
255579b0f7eSTNHarris    // arrive here with $words = array(wordlen => array(word => frequency))
256b4ce25e9SAndreas Gohr
257b4ce25e9SAndreas Gohr    $index = array(); //resulting index
258579b0f7eSTNHarris    foreach (array_keys($words) as $wlen){
259579b0f7eSTNHarris        $word_idx = idx_getIndex('w',$wlen);
260579b0f7eSTNHarris        foreach ($words[$wlen] as $word => $freq) {
26144ca0adfSAndreas Gohr            $wid = array_search("$word\n",$word_idx);
26244ca0adfSAndreas Gohr            if(!is_int($wid)){
263d5b23302STom N Harris                $wid = count($word_idx);
26444ca0adfSAndreas Gohr                $word_idx[] = "$word\n";
265b4ce25e9SAndreas Gohr            }
266579b0f7eSTNHarris            if(!isset($index[$wlen]))
267579b0f7eSTNHarris                $index[$wlen] = array();
268579b0f7eSTNHarris            $index[$wlen][$wid] = $freq;
26944ca0adfSAndreas Gohr        }
27044ca0adfSAndreas Gohr
27144ca0adfSAndreas Gohr        // save back word index
272579b0f7eSTNHarris        if(!idx_saveIndex('w',$wlen,$word_idx)){
273579b0f7eSTNHarris            trigger_error("Failed to write word index", E_USER_ERROR);
27444ca0adfSAndreas Gohr            return false;
27544ca0adfSAndreas Gohr        }
276579b0f7eSTNHarris    }
277b4ce25e9SAndreas Gohr
278b4ce25e9SAndreas Gohr    return $index;
279b4ce25e9SAndreas Gohr}
280b4ce25e9SAndreas Gohr
28144ca0adfSAndreas Gohr/**
28244ca0adfSAndreas Gohr * Adds/updates the search for the given page
28344ca0adfSAndreas Gohr *
28444ca0adfSAndreas Gohr * This is the core function of the indexer which does most
28544ca0adfSAndreas Gohr * of the work. This function needs to be called with proper
28644ca0adfSAndreas Gohr * locking!
28744ca0adfSAndreas Gohr *
28844ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
28944ca0adfSAndreas Gohr */
29044ca0adfSAndreas Gohrfunction idx_addPage($page){
29144ca0adfSAndreas Gohr    global $conf;
292b4ce25e9SAndreas Gohr
293488dd6ceSAndreas Gohr    // load known documents
294579b0f7eSTNHarris    $page_idx = idx_getIndex('page','');
29544ca0adfSAndreas Gohr
29644ca0adfSAndreas Gohr    // get page id (this is the linenumber in page.idx)
29744ca0adfSAndreas Gohr    $pid = array_search("$page\n",$page_idx);
29844ca0adfSAndreas Gohr    if(!is_int($pid)){
299c5418046SAndreas Gohr        $pid = count($page_idx);
30044ca0adfSAndreas Gohr        // page was new - write back
301dd35e9c9SAndreas Gohr        if (!idx_appendIndex('page','',"$page\n")){
302d5b23302STom N Harris            trigger_error("Failed to write page index", E_USER_ERROR);
303579b0f7eSTNHarris            return false;
30444ca0adfSAndreas Gohr        }
305d5b23302STom N Harris    }
306dd35e9c9SAndreas Gohr    unset($page_idx); // free memory
30744ca0adfSAndreas Gohr
308a0c5c349STom N Harris    $pagewords = array();
30944ca0adfSAndreas Gohr    // get word usage in page
31044ca0adfSAndreas Gohr    $words = idx_getPageWords($page);
31144ca0adfSAndreas Gohr    if($words === false) return false;
31244ca0adfSAndreas Gohr
313a0c5c349STom N Harris    if(!empty($words)) {
314579b0f7eSTNHarris        foreach(array_keys($words) as $wlen){
315d5b23302STom N Harris            $index = idx_getIndex('i',$wlen);
316d5b23302STom N Harris            foreach($words[$wlen] as $wid => $freq){
317d5b23302STom N Harris                if($wid<count($index)){
318d5b23302STom N Harris                    $index[$wid] = idx_updateIndexLine($index[$wid],$pid,$freq);
319d5b23302STom N Harris                }else{
320d5b23302STom N Harris                    // New words **should** have been added in increasing order
321d5b23302STom N Harris                    // starting with the first unassigned index.
322d5b23302STom N Harris                    // If someone can show how this isn't true, then I'll need to sort
323d5b23302STom N Harris                    // or do something special.
324d5b23302STom N Harris                    $index[$wid] = idx_updateIndexLine('',$pid,$freq);
325d5b23302STom N Harris                }
326a0c5c349STom N Harris                $pagewords[] = "$wlen*$wid";
327d5b23302STom N Harris            }
328d5b23302STom N Harris            // save back word index
329d5b23302STom N Harris            if(!idx_saveIndex('i',$wlen,$index)){
330d5b23302STom N Harris                trigger_error("Failed to write index", E_USER_ERROR);
33144ca0adfSAndreas Gohr                return false;
33244ca0adfSAndreas Gohr            }
333579b0f7eSTNHarris        }
334a0c5c349STom N Harris    }
335a0c5c349STom N Harris
336a0c5c349STom N Harris    // Remove obsolete index entries
337b6344591STom N Harris    $pageword_idx = trim(idx_getIndexLine('pageword','',$pid));
338b6344591STom N Harris    if ($pageword_idx !== '') {
339b6344591STom N Harris        $oldwords = explode(':',$pageword_idx);
340a0c5c349STom N Harris        $delwords = array_diff($oldwords, $pagewords);
341b6344591STom N Harris        $upwords = array();
342a0c5c349STom N Harris        foreach ($delwords as $word) {
343a0c5c349STom N Harris            if($word=='') continue;
344a0c5c349STom N Harris            list($wlen,$wid) = explode('*',$word);
345a0c5c349STom N Harris            $wid = (int)$wid;
346b6344591STom N Harris            $upwords[$wlen][] = $wid;
347b6344591STom N Harris        }
348b6344591STom N Harris        foreach ($upwords as $wlen => $widx) {
349a0c5c349STom N Harris            $index = idx_getIndex('i',$wlen);
350b6344591STom N Harris            foreach ($widx as $wid) {
351a0c5c349STom N Harris                $index[$wid] = idx_updateIndexLine($index[$wid],$pid,0);
352b6344591STom N Harris            }
353a0c5c349STom N Harris            idx_saveIndex('i',$wlen,$index);
354a0c5c349STom N Harris        }
355b6344591STom N Harris    }
356a0c5c349STom N Harris    // Save the reverse index
357b6344591STom N Harris    $pageword_idx = join(':',$pagewords)."\n";
358b6344591STom N Harris    if(!idx_saveIndexLine('pageword','',$pid,$pageword_idx)){
359a0c5c349STom N Harris        trigger_error("Failed to write word index", E_USER_ERROR);
360a0c5c349STom N Harris        return false;
361a0c5c349STom N Harris    }
362579b0f7eSTNHarris
363579b0f7eSTNHarris    return true;
36444ca0adfSAndreas Gohr}
36544ca0adfSAndreas Gohr
36644ca0adfSAndreas Gohr/**
36744ca0adfSAndreas Gohr * Write a new index line to the filehandle
36844ca0adfSAndreas Gohr *
36944ca0adfSAndreas Gohr * This function writes an line for the index file to the
37044ca0adfSAndreas Gohr * given filehandle. It removes the given document from
37144ca0adfSAndreas Gohr * the given line and readds it when $count is >0.
37244ca0adfSAndreas Gohr *
373d5b23302STom N Harris * @deprecated - see idx_updateIndexLine
37444ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
37544ca0adfSAndreas Gohr */
37644ca0adfSAndreas Gohrfunction idx_writeIndexLine($fh,$line,$pid,$count){
377d5b23302STom N Harris    fwrite($fh,idx_updateIndexLine($line,$pid,$count));
378d5b23302STom N Harris}
37944ca0adfSAndreas Gohr
380d5b23302STom N Harris/**
381d5b23302STom N Harris * Modify an index line with new information
382d5b23302STom N Harris *
383d5b23302STom N Harris * This returns a line of the index. It removes the
384d5b23302STom N Harris * given document from the line and readds it if
385d5b23302STom N Harris * $count is >0.
386d5b23302STom N Harris *
387d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
388d5b23302STom N Harris * @author Andreas Gohr <andi@splitbrain.org>
389d5b23302STom N Harris */
390d5b23302STom N Harrisfunction idx_updateIndexLine($line,$pid,$count){
391d5b23302STom N Harris    $line = trim($line);
392d5b23302STom N Harris    $updated = array();
39344ca0adfSAndreas Gohr    if($line != ''){
39444ca0adfSAndreas Gohr        $parts = explode(':',$line);
39544ca0adfSAndreas Gohr        // remove doc from given line
39644ca0adfSAndreas Gohr        foreach($parts as $part){
39744ca0adfSAndreas Gohr            if($part == '') continue;
39844ca0adfSAndreas Gohr            list($doc,$cnt) = explode('*',$part);
39944ca0adfSAndreas Gohr            if($doc != $pid){
400d5b23302STom N Harris                $updated[] = $part;
40144ca0adfSAndreas Gohr            }
40244ca0adfSAndreas Gohr        }
40344ca0adfSAndreas Gohr    }
40444ca0adfSAndreas Gohr
40544ca0adfSAndreas Gohr    // add doc
40644ca0adfSAndreas Gohr    if ($count){
407d5b23302STom N Harris        $updated[] = "$pid*$count";
40844ca0adfSAndreas Gohr    }
40944ca0adfSAndreas Gohr
410d5b23302STom N Harris    return join(':',$updated)."\n";
41144ca0adfSAndreas Gohr}
412b4ce25e9SAndreas Gohr
413488dd6ceSAndreas Gohr/**
414*22952965SYoBoY * Get the list of lenghts indexed in the wiki
415*22952965SYoBoY *
416*22952965SYoBoY * Read the index directory or a cache file and returns
417*22952965SYoBoY * a sorted array of lengths of the words used in the wiki.
418*22952965SYoBoY *
419*22952965SYoBoY * @author YoBoY <yoboy.leguesh@gmail.com>
420*22952965SYoBoY */
421*22952965SYoBoYfunction idx_listIndexLengths() {
422*22952965SYoBoY    global $conf;
423*22952965SYoBoY    // testing what we have to do, create a cache file or not.
424*22952965SYoBoY    if ($conf['readdircache'] == 0) {
425*22952965SYoBoY        $docache = false;
426*22952965SYoBoY    } else {
427*22952965SYoBoY        clearstatcache();
428*22952965SYoBoY        if (@file_exists($conf['indexdir'].'/lengths.idx') and (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
429*22952965SYoBoY            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ) !== false) {
430*22952965SYoBoY                $idx = array();
431*22952965SYoBoY                foreach ( $lengths as $length) {
432*22952965SYoBoY                    $idx[] = (int)$length;
433*22952965SYoBoY                }
434*22952965SYoBoY                return $idx;
435*22952965SYoBoY            }
436*22952965SYoBoY        }
437*22952965SYoBoY        $docache = true;
438*22952965SYoBoY    }
439*22952965SYoBoY
440*22952965SYoBoY    if ($conf['readdircache'] == 0 or $docache ) {
441*22952965SYoBoY        $dir = @opendir($conf['indexdir']);
442*22952965SYoBoY        if($dir===false)
443*22952965SYoBoY            return array();
444*22952965SYoBoY        $idx[] = array();
445*22952965SYoBoY        while (($f = readdir($dir)) !== false) {
446*22952965SYoBoY            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
447*22952965SYoBoY                $i = substr($f,1,-4);
448*22952965SYoBoY                if (is_numeric($i))
449*22952965SYoBoY                    $idx[] = (int)$i;
450*22952965SYoBoY            }
451*22952965SYoBoY        }
452*22952965SYoBoY        closedir($dir);
453*22952965SYoBoY        sort($idx);
454*22952965SYoBoY        // we save this in a file.
455*22952965SYoBoY        if ($docache === true) {
456*22952965SYoBoY            $handle = @fopen($conf['indexdir'].'/lengths.idx','w');
457*22952965SYoBoY            @fwrite($handle, implode("\n",$idx));
458*22952965SYoBoY            @fclose($handle);
459*22952965SYoBoY        }
460*22952965SYoBoY        return $idx;
461*22952965SYoBoY    }
462*22952965SYoBoY
463*22952965SYoBoY    return array();
464*22952965SYoBoY}
465*22952965SYoBoY
466*22952965SYoBoY/**
467579b0f7eSTNHarris * Get the word lengths that have been indexed.
468579b0f7eSTNHarris *
469579b0f7eSTNHarris * Reads the index directory and returns an array of lengths
470579b0f7eSTNHarris * that there are indices for.
471579b0f7eSTNHarris *
472*22952965SYoBoY * @author YoBoY <yoboy.leguesh@gmail.com>
473579b0f7eSTNHarris */
474d5b23302STom N Harrisfunction idx_indexLengths(&$filter){
475579b0f7eSTNHarris    global $conf;
476579b0f7eSTNHarris    $idx = array();
477d5b23302STom N Harris    if (is_array($filter)){
478*22952965SYoBoY        // testing if index files exists only
479*22952965SYoBoY        foreach ($filter as $key => $value) {
480*22952965SYoBoY            if (@file_exists($conf['indexdir']."/i$key.idx")) {
481*22952965SYoBoY                $idx[] = $key;
482d5b23302STom N Harris            }
483d5b23302STom N Harris        }
484d5b23302STom N Harris    } else {
485*22952965SYoBoY        $lengths = idx_listIndexLengths();
486*22952965SYoBoY        foreach ( $lengths as $key => $length) {
487*22952965SYoBoY            // we keep all the values equal or superior
488*22952965SYoBoY            if ((int)$length >= (int)$filter) {
489*22952965SYoBoY                $idx[] = $length;
490d5b23302STom N Harris            }
491579b0f7eSTNHarris        }
492579b0f7eSTNHarris    }
493579b0f7eSTNHarris    return $idx;
494579b0f7eSTNHarris}
495579b0f7eSTNHarris
496579b0f7eSTNHarris/**
497d5b23302STom N Harris * Find the the index number of each search term.
498d5b23302STom N Harris *
499adb16d4fSAndreas Gohr * This will group together words that appear in the same index.
500d5b23302STom N Harris * So it should perform better, because it only opens each index once.
501d5b23302STom N Harris * Actually, it's not that great. (in my experience) Probably because of the disk cache.
502d5b23302STom N Harris * And the sorted function does more work, making it slightly slower in some cases.
503d5b23302STom N Harris *
504d5b23302STom N Harris * @param array    $words   The query terms. Words should only contain valid characters,
505d5b23302STom N Harris *                          with a '*' at either the beginning or end of the word (or both)
506d5b23302STom N Harris * @param arrayref $result  Set to word => array("length*id" ...), use this to merge the
507d5b23302STom N Harris *                          index locations with the appropriate query term.
508d5b23302STom N Harris * @return array            Set to length => array(id ...)
509d5b23302STom N Harris *
510d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
511d5b23302STom N Harris */
512d5b23302STom N Harrisfunction idx_getIndexWordsSorted($words,&$result){
513d5b23302STom N Harris    // parse and sort tokens
514d5b23302STom N Harris    $tokens = array();
515d5b23302STom N Harris    $tokenlength = array();
516d5b23302STom N Harris    $tokenwild = array();
517d5b23302STom N Harris    foreach($words as $word){
518d5b23302STom N Harris        $result[$word] = array();
519d5b23302STom N Harris        $wild = 0;
520d5b23302STom N Harris        $xword = $word;
521d5b23302STom N Harris        $wlen = wordlen($word);
522d5b23302STom N Harris
523d5b23302STom N Harris        // check for wildcards
524d5b23302STom N Harris        if(substr($xword,0,1) == '*'){
525d5b23302STom N Harris            $xword = substr($xword,1);
526d5b23302STom N Harris            $wild |= 1;
527d5b23302STom N Harris            $wlen -= 1;
528d5b23302STom N Harris        }
529d5b23302STom N Harris        if(substr($xword,-1,1) == '*'){
530d5b23302STom N Harris            $xword = substr($xword,0,-1);
531d5b23302STom N Harris            $wild |= 2;
532d5b23302STom N Harris            $wlen -= 1;
533d5b23302STom N Harris        }
53433815ce2SChris Smith        if ($wlen < IDX_MINWORDLENGTH && $wild == 0 && !is_numeric($xword)) continue;
535d5b23302STom N Harris        if(!isset($tokens[$xword])){
536d5b23302STom N Harris            $tokenlength[$wlen][] = $xword;
537d5b23302STom N Harris        }
538d5b23302STom N Harris        if($wild){
539d5b23302STom N Harris            $ptn = preg_quote($xword,'/');
540d5b23302STom N Harris            if(($wild&1) == 0) $ptn = '^'.$ptn;
541d5b23302STom N Harris            if(($wild&2) == 0) $ptn = $ptn.'$';
542d5b23302STom N Harris            $tokens[$xword][] = array($word, '/'.$ptn.'/');
543d5b23302STom N Harris            if(!isset($tokenwild[$xword])) $tokenwild[$xword] = $wlen;
544d5b23302STom N Harris        }else
545d5b23302STom N Harris            $tokens[$xword][] = array($word, null);
546d5b23302STom N Harris    }
547d5b23302STom N Harris    asort($tokenwild);
548d5b23302STom N Harris    // $tokens = array( base word => array( [ query word , grep pattern ] ... ) ... )
549d5b23302STom N Harris    // $tokenlength = array( base word length => base word ... )
550d5b23302STom N Harris    // $tokenwild = array( base word => base word length ... )
551d5b23302STom N Harris
552d5b23302STom N Harris    $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
553d5b23302STom N Harris    $indexes_known = idx_indexLengths($length_filter);
554d5b23302STom N Harris    if(!empty($tokenwild)) sort($indexes_known);
555d5b23302STom N Harris    // get word IDs
556d5b23302STom N Harris    $wids = array();
557d5b23302STom N Harris    foreach($indexes_known as $ixlen){
558d5b23302STom N Harris        $word_idx = idx_getIndex('w',$ixlen);
559d5b23302STom N Harris        // handle exact search
560d5b23302STom N Harris        if(isset($tokenlength[$ixlen])){
561d5b23302STom N Harris            foreach($tokenlength[$ixlen] as $xword){
562d5b23302STom N Harris                $wid = array_search("$xword\n",$word_idx);
563d5b23302STom N Harris                if(is_int($wid)){
564d5b23302STom N Harris                    $wids[$ixlen][] = $wid;
565d5b23302STom N Harris                    foreach($tokens[$xword] as $w)
566d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
567d5b23302STom N Harris                }
568d5b23302STom N Harris            }
569d5b23302STom N Harris        }
570d5b23302STom N Harris        // handle wildcard search
571d5b23302STom N Harris        foreach($tokenwild as $xword => $wlen){
572d5b23302STom N Harris            if($wlen >= $ixlen) break;
573d5b23302STom N Harris            foreach($tokens[$xword] as $w){
574d5b23302STom N Harris                if(is_null($w[1])) continue;
575d5b23302STom N Harris                foreach(array_keys(preg_grep($w[1],$word_idx)) as $wid){
576d5b23302STom N Harris                    $wids[$ixlen][] = $wid;
577d5b23302STom N Harris                    $result[$w[0]][] = "$ixlen*$wid";
578d5b23302STom N Harris                }
579d5b23302STom N Harris            }
580d5b23302STom N Harris        }
581d5b23302STom N Harris    }
582d5b23302STom N Harris    return $wids;
583d5b23302STom N Harris}
584d5b23302STom N Harris
585d5b23302STom N Harris/**
586488dd6ceSAndreas Gohr * Lookup words in index
587488dd6ceSAndreas Gohr *
588488dd6ceSAndreas Gohr * Takes an array of word and will return a list of matching
589488dd6ceSAndreas Gohr * documents for each one.
590488dd6ceSAndreas Gohr *
59163773904SAndreas Gohr * Important: No ACL checking is done here! All results are
59263773904SAndreas Gohr *            returned, regardless of permissions
59363773904SAndreas Gohr *
594488dd6ceSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
595488dd6ceSAndreas Gohr */
596488dd6ceSAndreas Gohrfunction idx_lookup($words){
597488dd6ceSAndreas Gohr    global $conf;
598488dd6ceSAndreas Gohr
599488dd6ceSAndreas Gohr    $result = array();
600488dd6ceSAndreas Gohr
601d5b23302STom N Harris    $wids = idx_getIndexWordsSorted($words, $result);
602d5b23302STom N Harris    if(empty($wids)) return array();
603d5b23302STom N Harris
604488dd6ceSAndreas Gohr    // load known words and documents
605579b0f7eSTNHarris    $page_idx = idx_getIndex('page','');
606488dd6ceSAndreas Gohr
607579b0f7eSTNHarris    $docs = array();                          // hold docs found
608579b0f7eSTNHarris    foreach(array_keys($wids) as $wlen){
609579b0f7eSTNHarris        $wids[$wlen] = array_unique($wids[$wlen]);
610d5b23302STom N Harris        $index = idx_getIndex('i',$wlen);
611d5b23302STom N Harris        foreach($wids[$wlen] as $ixid){
612d5b23302STom N Harris            if($ixid < count($index))
613d5b23302STom N Harris                $docs["$wlen*$ixid"] = idx_parseIndexLine($page_idx,$index[$ixid]);
614488dd6ceSAndreas Gohr        }
615488dd6ceSAndreas Gohr    }
616488dd6ceSAndreas Gohr
617ad81d431SAndreas Gohr    // merge found pages into final result array
618ad81d431SAndreas Gohr    $final = array();
619c66972f2SAdrian Lang    foreach($result as $word => $res){
620ad81d431SAndreas Gohr        $final[$word] = array();
621c66972f2SAdrian Lang        foreach($res as $wid){
622ad81d431SAndreas Gohr            $hits = &$docs[$wid];
623ad81d431SAndreas Gohr            foreach ($hits as $hitkey => $hitcnt) {
624c66972f2SAdrian Lang                if (!isset($final[$word][$hitkey])) {
625c66972f2SAdrian Lang                    $final[$word][$hitkey] = $hitcnt;
626c66972f2SAdrian Lang                } else {
627c66972f2SAdrian Lang                    $final[$word][$hitkey] += $hitcnt;
628c66972f2SAdrian Lang                }
629ad81d431SAndreas Gohr            }
630ad81d431SAndreas Gohr        }
631ad81d431SAndreas Gohr    }
632ad81d431SAndreas Gohr    return $final;
633488dd6ceSAndreas Gohr}
634488dd6ceSAndreas Gohr
635488dd6ceSAndreas Gohr/**
636488dd6ceSAndreas Gohr * Returns a list of documents and counts from a index line
637488dd6ceSAndreas Gohr *
638488dd6ceSAndreas Gohr * It omits docs with a count of 0 and pages that no longer
639488dd6ceSAndreas Gohr * exist.
640488dd6ceSAndreas Gohr *
641488dd6ceSAndreas Gohr * @param  array  $page_idx The list of known pages
642488dd6ceSAndreas Gohr * @param  string $line     A line from the main index
643488dd6ceSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
644488dd6ceSAndreas Gohr */
645488dd6ceSAndreas Gohrfunction idx_parseIndexLine(&$page_idx,$line){
646488dd6ceSAndreas Gohr    $result = array();
647488dd6ceSAndreas Gohr
648488dd6ceSAndreas Gohr    $line = trim($line);
649f5eb7cf0SAndreas Gohr    if($line == '') return $result;
650488dd6ceSAndreas Gohr
651488dd6ceSAndreas Gohr    $parts = explode(':',$line);
652488dd6ceSAndreas Gohr    foreach($parts as $part){
653488dd6ceSAndreas Gohr        if($part == '') continue;
654488dd6ceSAndreas Gohr        list($doc,$cnt) = explode('*',$part);
655488dd6ceSAndreas Gohr        if(!$cnt) continue;
656488dd6ceSAndreas Gohr        $doc = trim($page_idx[$doc]);
657488dd6ceSAndreas Gohr        if(!$doc) continue;
658488dd6ceSAndreas Gohr        // make sure the document still exists
659103c256aSChris Smith        if(!page_exists($doc,'',false)) continue;
660488dd6ceSAndreas Gohr
661488dd6ceSAndreas Gohr        $result[$doc] = $cnt;
662488dd6ceSAndreas Gohr    }
663488dd6ceSAndreas Gohr    return $result;
664488dd6ceSAndreas Gohr}
665488dd6ceSAndreas Gohr
666f5eb7cf0SAndreas Gohr/**
667f5eb7cf0SAndreas Gohr * Tokenizes a string into an array of search words
668f5eb7cf0SAndreas Gohr *
669f5eb7cf0SAndreas Gohr * Uses the same algorithm as idx_getPageWords()
670f5eb7cf0SAndreas Gohr *
671ad81d431SAndreas Gohr * @param string   $string     the query as given by the user
672ad81d431SAndreas Gohr * @param arrayref $stopwords  array of stopwords
673ad81d431SAndreas Gohr * @param boolean  $wc         are wildcards allowed?
674f5eb7cf0SAndreas Gohr */
675ad81d431SAndreas Gohrfunction idx_tokenizer($string,&$stopwords,$wc=false){
676f5eb7cf0SAndreas Gohr    $words = array();
6774efb9a42SAndreas Gohr    $wc = ($wc) ? '' : $wc = '\*';
678f5eb7cf0SAndreas Gohr
679f5eb7cf0SAndreas Gohr    if(preg_match('/[^0-9A-Za-z]/u', $string)){
68091bb5faaSAndreas Gohr        // handle asian chars as single words (may fail on older PHP version)
68160c15d7dSAndreas Gohr        $asia = @preg_replace('/('.IDX_ASIAN.')/u',' \1 ',$string);
68291bb5faaSAndreas Gohr        if(!is_null($asia)) $string = $asia; //recover from regexp failure
68393a60ad2SAndreas Gohr
6844efb9a42SAndreas Gohr        $arr = explode(' ', utf8_stripspecials($string,' ','\._\-:'.$wc));
685f5eb7cf0SAndreas Gohr        foreach ($arr as $w) {
68633815ce2SChris Smith            if (!is_numeric($w) && strlen($w) < IDX_MINWORDLENGTH) continue;
687f5eb7cf0SAndreas Gohr            $w = utf8_strtolower($w);
6883cbaa9a4SAndreas Gohr            if($stopwords && is_int(array_search("$w\n",$stopwords))) continue;
689f5eb7cf0SAndreas Gohr            $words[] = $w;
690f5eb7cf0SAndreas Gohr        }
691f5eb7cf0SAndreas Gohr    }else{
692f5eb7cf0SAndreas Gohr        $w = $string;
69333815ce2SChris Smith        if (!is_numeric($w) && strlen($w) < IDX_MINWORDLENGTH) return $words;
694f5eb7cf0SAndreas Gohr        $w = strtolower($w);
695f5eb7cf0SAndreas Gohr        if(is_int(array_search("$w\n",$stopwords))) return $words;
696f5eb7cf0SAndreas Gohr        $words[] = $w;
697f5eb7cf0SAndreas Gohr    }
698f5eb7cf0SAndreas Gohr
699f5eb7cf0SAndreas Gohr    return $words;
700f5eb7cf0SAndreas Gohr}
701f5eb7cf0SAndreas Gohr
702a0c5c349STom N Harris/**
703a0c5c349STom N Harris * Create a pagewords index from the existing index.
704a0c5c349STom N Harris *
705a0c5c349STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
706a0c5c349STom N Harris */
707a0c5c349STom N Harrisfunction idx_upgradePageWords(){
708a0c5c349STom N Harris    global $conf;
709a0c5c349STom N Harris    $page_idx = idx_getIndex('page','');
710a0c5c349STom N Harris    if (empty($page_idx)) return;
711a0c5c349STom N Harris    $pagewords = array();
712dd35e9c9SAndreas Gohr    $len = count($page_idx);
713db959ae3SAndreas Gohr    for ($n=0;$n<$len;$n++){
714db959ae3SAndreas Gohr        $pagewords[] = array();
715db959ae3SAndreas Gohr    }
716a0c5c349STom N Harris    unset($page_idx);
717a0c5c349STom N Harris
718a0c5c349STom N Harris    $n=0;
719a0c5c349STom N Harris    foreach (idx_indexLengths($n) as $wlen) {
720a0c5c349STom N Harris        $lines = idx_getIndex('i',$wlen);
721dd35e9c9SAndreas Gohr        $len = count($lines);
722dd35e9c9SAndreas Gohr        for ($wid=0;$wid<$len;$wid++) {
723a0c5c349STom N Harris            $wkey = "$wlen*$wid";
724a0c5c349STom N Harris            foreach (explode(':',trim($lines[$wid])) as $part) {
725a0c5c349STom N Harris                if($part == '') continue;
726a0c5c349STom N Harris                list($doc,$cnt) = explode('*',$part);
727a0c5c349STom N Harris                $pagewords[(int)$doc][] = $wkey;
728a0c5c349STom N Harris            }
729a0c5c349STom N Harris        }
730a0c5c349STom N Harris    }
731a0c5c349STom N Harris
732b6344591STom N Harris    $fn = $conf['indexdir'].'/pageword';
733b6344591STom N Harris    $fh = @fopen($fn.'.tmp','w');
734b6344591STom N Harris    if (!$fh){
735a0c5c349STom N Harris        trigger_error("Failed to write word index", E_USER_ERROR);
736a0c5c349STom N Harris        return false;
737a0c5c349STom N Harris    }
738b6344591STom N Harris    foreach ($pagewords as $line){
739b6344591STom N Harris        fwrite($fh, join(':',$line)."\n");
740b6344591STom N Harris    }
741b6344591STom N Harris    fclose($fh);
742b6344591STom N Harris    if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
743b6344591STom N Harris    io_rename($fn.'.tmp', $fn.'.idx');
744a0c5c349STom N Harris    return true;
745a0c5c349STom N Harris}
746a0c5c349STom N Harris
747b4ce25e9SAndreas Gohr//Setup VIM: ex: et ts=4 enc=utf-8 :
748