xref: /dokuwiki/inc/indexer.php (revision 4f0030dd466f56b3dc0c864656fb1bf0e76d2932)
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
26ae6c4ec0SDanny Lin                   "\xF0\xA0\x80\x80-\xF0\xAA\x9B\x9F". // CJK Extension B
27ae6c4ec0SDanny Lin                   "\xF0\xAA\x9C\x80-\xF0\xAB\x9C\xBF". // CJK Extension C
28ae6c4ec0SDanny Lin                   "\xF0\xAB\x9D\x80-\xF0\xAB\xA0\x9F". // CJK Extension D
29ae6c4ec0SDanny Lin                   "\xF0\xAF\xA0\x80-\xF0\xAF\xAB\xBF". // CJK Compatibility Supplement
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);
78c66972f2SAdrian Lang    if(isset($conf['fperm'])) chmod($fn.'.tmp', $conf['fperm']);
79579b0f7eSTNHarris    io_rename($fn.'.tmp', $fn.'.idx');
80579b0f7eSTNHarris    return true;
81579b0f7eSTNHarris}
82579b0f7eSTNHarris
83579b0f7eSTNHarris/**
84dd35e9c9SAndreas Gohr * Append a given line to an index file.
85dd35e9c9SAndreas Gohr *
86dd35e9c9SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
87dd35e9c9SAndreas Gohr */
88dd35e9c9SAndreas Gohrfunction idx_appendIndex($pre, $wlen, $line){
89dd35e9c9SAndreas Gohr    global $conf;
90dd35e9c9SAndreas Gohr    $fn = $conf['indexdir'].'/'.$pre.$wlen;
91dd35e9c9SAndreas Gohr    $fh = @fopen($fn.'.idx','a');
92dd35e9c9SAndreas Gohr    if(!$fh) return false;
93dd35e9c9SAndreas Gohr    fwrite($fh,$line);
94dd35e9c9SAndreas Gohr    fclose($fh);
95dd35e9c9SAndreas Gohr    return true;
96dd35e9c9SAndreas Gohr}
97dd35e9c9SAndreas Gohr
98dd35e9c9SAndreas Gohr/**
99579b0f7eSTNHarris * Read the list of words in an index (if it exists).
100579b0f7eSTNHarris *
101579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
102579b0f7eSTNHarris */
103579b0f7eSTNHarrisfunction idx_getIndex($pre, $wlen){
104579b0f7eSTNHarris    global $conf;
105579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
106579b0f7eSTNHarris    if(!@file_exists($fn)) return array();
107579b0f7eSTNHarris    return file($fn);
108579b0f7eSTNHarris}
109579b0f7eSTNHarris
110579b0f7eSTNHarris/**
111579b0f7eSTNHarris * Create an empty index file if it doesn't exist yet.
112579b0f7eSTNHarris *
113b6344591STom N Harris * FIXME: This function isn't currently used. It will probably be removed soon.
114b6344591STom N Harris *
115579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
116579b0f7eSTNHarris */
117579b0f7eSTNHarrisfunction idx_touchIndex($pre, $wlen){
118579b0f7eSTNHarris    global $conf;
119579b0f7eSTNHarris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
120579b0f7eSTNHarris    if(!@file_exists($fn)){
121579b0f7eSTNHarris        touch($fn);
122579b0f7eSTNHarris        if($conf['fperm']) chmod($fn, $conf['fperm']);
123579b0f7eSTNHarris    }
124579b0f7eSTNHarris}
125579b0f7eSTNHarris
126579b0f7eSTNHarris/**
127b6344591STom N Harris * Read a line ending with \n.
128b6344591STom N Harris * Returns false on EOF.
129b6344591STom N Harris *
130b6344591STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
131b6344591STom N Harris */
132b6344591STom N Harrisfunction _freadline($fh) {
133b6344591STom N Harris    if (feof($fh)) return false;
134b6344591STom N Harris    $ln = '';
135b6344591STom N Harris    while (($buf = fgets($fh,4096)) !== false) {
136b6344591STom N Harris        $ln .= $buf;
137b6344591STom N Harris        if (substr($buf,-1) == "\n") break;
138b6344591STom N Harris    }
139b6344591STom N Harris    if ($ln === '') return false;
140b6344591STom N Harris    if (substr($ln,-1) != "\n") $ln .= "\n";
141b6344591STom N Harris    return $ln;
142b6344591STom N Harris}
143b6344591STom N Harris
144b6344591STom N Harris/**
145b6344591STom N Harris * Write a line to an index file.
146b6344591STom N Harris *
147b6344591STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
148b6344591STom N Harris */
149b6344591STom N Harrisfunction idx_saveIndexLine($pre, $wlen, $idx, $line){
150b6344591STom N Harris    global $conf;
151b6344591STom N Harris    if(substr($line,-1) != "\n") $line .= "\n";
152b6344591STom N Harris    $fn = $conf['indexdir'].'/'.$pre.$wlen;
153b6344591STom N Harris    $fh = @fopen($fn.'.tmp','w');
154b6344591STom N Harris    if(!$fh) return false;
155b6344591STom N Harris    $ih = @fopen($fn.'.idx','r');
156b6344591STom N Harris    if ($ih) {
157b6344591STom N Harris        $ln = -1;
158b6344591STom N Harris        while (($curline = _freadline($ih)) !== false) {
159b6344591STom N Harris            if (++$ln == $idx) {
160b6344591STom N Harris                fwrite($fh, $line);
161b6344591STom N Harris            } else {
162b6344591STom N Harris                fwrite($fh, $curline);
163b6344591STom N Harris            }
164b6344591STom N Harris        }
165b6344591STom N Harris        if ($idx > $ln) {
166b6344591STom N Harris            fwrite($fh,$line);
167b6344591STom N Harris        }
168b6344591STom N Harris        fclose($ih);
169b6344591STom N Harris    } else {
170b6344591STom N Harris        fwrite($fh,$line);
171b6344591STom N Harris    }
172b6344591STom N Harris    fclose($fh);
173b6344591STom N Harris    if($conf['fperm']) chmod($fn.'.tmp', $conf['fperm']);
174b6344591STom N Harris    io_rename($fn.'.tmp', $fn.'.idx');
175b6344591STom N Harris    return true;
176b6344591STom N Harris}
177b6344591STom N Harris
178b6344591STom N Harris/**
179b6344591STom N Harris * Read a single line from an index (if it exists).
180b6344591STom N Harris *
181b6344591STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
182b6344591STom N Harris */
183b6344591STom N Harrisfunction idx_getIndexLine($pre, $wlen, $idx){
184b6344591STom N Harris    global $conf;
185b6344591STom N Harris    $fn = $conf['indexdir'].'/'.$pre.$wlen.'.idx';
186b6344591STom N Harris    if(!@file_exists($fn)) return '';
187b6344591STom N Harris    $fh = @fopen($fn,'r');
188b6344591STom N Harris    if(!$fh) return '';
189b6344591STom N Harris    $ln = -1;
190b6344591STom N Harris    while (($line = _freadline($fh)) !== false) {
191b6344591STom N Harris        if (++$ln == $idx) break;
192b6344591STom N Harris    }
193b6344591STom N Harris    fclose($fh);
194b6344591STom N Harris    return "$line";
195b6344591STom N Harris}
196b6344591STom N Harris
197b6344591STom N Harris/**
19844ca0adfSAndreas Gohr * Split a page into words
19944ca0adfSAndreas Gohr *
200c9db30f9SAndreas Gohr * Returns an array of word counts, false if an error occurred.
201579b0f7eSTNHarris * Array is keyed on the word length, then the word index.
20244ca0adfSAndreas Gohr *
20344ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
20417f42b01SChris Smith * @author Christopher Smith <chris@jalakai.co.uk>
205b4ce25e9SAndreas Gohr */
20644ca0adfSAndreas Gohrfunction idx_getPageWords($page){
20744ca0adfSAndreas Gohr    global $conf;
2087367b368SAndreas Gohr    $swfile   = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
2097367b368SAndreas Gohr    if(@file_exists($swfile)){
2107367b368SAndreas Gohr        $stopwords = file($swfile);
2117367b368SAndreas Gohr    }else{
2127367b368SAndreas Gohr        $stopwords = array();
2137367b368SAndreas Gohr    }
21444ca0adfSAndreas Gohr
215a6a30c1aSEsther Brunner    $body = '';
21615018435SAndreas Gohr    $data = array($page, $body);
21715018435SAndreas Gohr    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
21815018435SAndreas Gohr    if ($evt->advise_before()) $data[1] .= rawWiki($page);
219a6a30c1aSEsther Brunner    $evt->advise_after();
220a6a30c1aSEsther Brunner    unset($evt);
221a6a30c1aSEsther Brunner
22215018435SAndreas Gohr    list($page,$body) = $data;
22315018435SAndreas Gohr
224*4f0030ddSAndreas Gohr    $body   = strtr($body,
225*4f0030ddSAndreas Gohr                    array(
226*4f0030ddSAndreas Gohr                        "\r" => ' ',
227*4f0030ddSAndreas Gohr                        "\n" => ' ',
228*4f0030ddSAndreas Gohr                        "\t" => ' ',
229*4f0030ddSAndreas Gohr                        "\xC2\xAD" => '', //soft-hyphen
230*4f0030ddSAndreas Gohr                    )
231*4f0030ddSAndreas Gohr                   );
23217f42b01SChris Smith    $tokens = explode(' ', $body);
23317f42b01SChris Smith    $tokens = array_count_values($tokens);   // count the frequency of each token
23417f42b01SChris Smith
2356b06b652Schris    // ensure the deaccented or romanised page names of internal links are added to the token array
2366b06b652Schris    // (this is necessary for the backlink function -- there maybe a better way!)
2376b06b652Schris    if ($conf['deaccent']) {
2386b06b652Schris        $links = p_get_metadata($page,'relation references');
2396b06b652Schris
2403fc667cfSchris        if (!empty($links)) {
2416b06b652Schris            $tmp = join(' ',array_keys($links));                // make a single string
2426b06b652Schris            $tmp = strtr($tmp, ':', ' ');                       // replace namespace separator with a space
2436b06b652Schris            $link_tokens = array_unique(explode(' ', $tmp));    // break into tokens
2446b06b652Schris
2456b06b652Schris            foreach ($link_tokens as $link_token) {
2466b06b652Schris                if (isset($tokens[$link_token])) continue;
2476b06b652Schris                $tokens[$link_token] = 1;
2486b06b652Schris            }
2496b06b652Schris        }
2503fc667cfSchris    }
2516b06b652Schris
25217f42b01SChris Smith    $words = array();
25317f42b01SChris Smith    foreach ($tokens as $word => $count) {
254579b0f7eSTNHarris        $arr = idx_tokenizer($word,$stopwords);
25517f42b01SChris Smith        $arr = array_count_values($arr);
25617f42b01SChris Smith        foreach ($arr as $w => $c) {
257d5b23302STom N Harris            $l = wordlen($w);
258579b0f7eSTNHarris            if(isset($words[$l])){
259b2bc63f0SAndreas Gohr                $words[$l][$w] = $c * $count + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
26017f42b01SChris Smith            }else{
261579b0f7eSTNHarris                $words[$l] = array($w => $c * $count);
262579b0f7eSTNHarris            }
26317f42b01SChris Smith        }
26417f42b01SChris Smith    }
26517f42b01SChris Smith
266579b0f7eSTNHarris    // arrive here with $words = array(wordlen => array(word => frequency))
267b4ce25e9SAndreas Gohr
268b4ce25e9SAndreas Gohr    $index = array(); //resulting index
269579b0f7eSTNHarris    foreach (array_keys($words) as $wlen){
270579b0f7eSTNHarris        $word_idx = idx_getIndex('w',$wlen);
271579b0f7eSTNHarris        foreach ($words[$wlen] as $word => $freq) {
27244ca0adfSAndreas Gohr            $wid = array_search("$word\n",$word_idx);
27344ca0adfSAndreas Gohr            if(!is_int($wid)){
274d5b23302STom N Harris                $wid = count($word_idx);
27544ca0adfSAndreas Gohr                $word_idx[] = "$word\n";
276b4ce25e9SAndreas Gohr            }
277579b0f7eSTNHarris            if(!isset($index[$wlen]))
278579b0f7eSTNHarris                $index[$wlen] = array();
279579b0f7eSTNHarris            $index[$wlen][$wid] = $freq;
28044ca0adfSAndreas Gohr        }
28144ca0adfSAndreas Gohr
28244ca0adfSAndreas Gohr        // save back word index
283579b0f7eSTNHarris        if(!idx_saveIndex('w',$wlen,$word_idx)){
284579b0f7eSTNHarris            trigger_error("Failed to write word index", E_USER_ERROR);
28544ca0adfSAndreas Gohr            return false;
28644ca0adfSAndreas Gohr        }
287579b0f7eSTNHarris    }
288b4ce25e9SAndreas Gohr
289b4ce25e9SAndreas Gohr    return $index;
290b4ce25e9SAndreas Gohr}
291b4ce25e9SAndreas Gohr
29244ca0adfSAndreas Gohr/**
29344ca0adfSAndreas Gohr * Adds/updates the search for the given page
29444ca0adfSAndreas Gohr *
29544ca0adfSAndreas Gohr * This is the core function of the indexer which does most
29644ca0adfSAndreas Gohr * of the work. This function needs to be called with proper
29744ca0adfSAndreas Gohr * locking!
29844ca0adfSAndreas Gohr *
29944ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
30044ca0adfSAndreas Gohr */
30144ca0adfSAndreas Gohrfunction idx_addPage($page){
30244ca0adfSAndreas Gohr    global $conf;
303b4ce25e9SAndreas Gohr
304488dd6ceSAndreas Gohr    // load known documents
305579b0f7eSTNHarris    $page_idx = idx_getIndex('page','');
30644ca0adfSAndreas Gohr
30744ca0adfSAndreas Gohr    // get page id (this is the linenumber in page.idx)
30844ca0adfSAndreas Gohr    $pid = array_search("$page\n",$page_idx);
30944ca0adfSAndreas Gohr    if(!is_int($pid)){
310c5418046SAndreas Gohr        $pid = count($page_idx);
31144ca0adfSAndreas Gohr        // page was new - write back
312dd35e9c9SAndreas Gohr        if (!idx_appendIndex('page','',"$page\n")){
313d5b23302STom N Harris            trigger_error("Failed to write page index", E_USER_ERROR);
314579b0f7eSTNHarris            return false;
31544ca0adfSAndreas Gohr        }
316d5b23302STom N Harris    }
317dd35e9c9SAndreas Gohr    unset($page_idx); // free memory
31844ca0adfSAndreas Gohr
3194a819402SMichael Hamann    idx_saveIndexLine('title', '', $pid, p_get_first_heading($page, true));
32080423ab6SAdrian Lang
321a0c5c349STom N Harris    $pagewords = array();
32244ca0adfSAndreas Gohr    // get word usage in page
32344ca0adfSAndreas Gohr    $words = idx_getPageWords($page);
32444ca0adfSAndreas Gohr    if($words === false) return false;
32544ca0adfSAndreas Gohr
326a0c5c349STom N Harris    if(!empty($words)) {
327579b0f7eSTNHarris        foreach(array_keys($words) as $wlen){
328d5b23302STom N Harris            $index = idx_getIndex('i',$wlen);
329d5b23302STom N Harris            foreach($words[$wlen] as $wid => $freq){
330d5b23302STom N Harris                if($wid<count($index)){
331d5b23302STom N Harris                    $index[$wid] = idx_updateIndexLine($index[$wid],$pid,$freq);
332d5b23302STom N Harris                }else{
333d5b23302STom N Harris                    // New words **should** have been added in increasing order
334d5b23302STom N Harris                    // starting with the first unassigned index.
335d5b23302STom N Harris                    // If someone can show how this isn't true, then I'll need to sort
336d5b23302STom N Harris                    // or do something special.
337d5b23302STom N Harris                    $index[$wid] = idx_updateIndexLine('',$pid,$freq);
338d5b23302STom N Harris                }
339a0c5c349STom N Harris                $pagewords[] = "$wlen*$wid";
340d5b23302STom N Harris            }
341d5b23302STom N Harris            // save back word index
342d5b23302STom N Harris            if(!idx_saveIndex('i',$wlen,$index)){
343d5b23302STom N Harris                trigger_error("Failed to write index", E_USER_ERROR);
34444ca0adfSAndreas Gohr                return false;
34544ca0adfSAndreas Gohr            }
346579b0f7eSTNHarris        }
347a0c5c349STom N Harris    }
348a0c5c349STom N Harris
349a0c5c349STom N Harris    // Remove obsolete index entries
350b6344591STom N Harris    $pageword_idx = trim(idx_getIndexLine('pageword','',$pid));
351b6344591STom N Harris    if ($pageword_idx !== '') {
352b6344591STom N Harris        $oldwords = explode(':',$pageword_idx);
353a0c5c349STom N Harris        $delwords = array_diff($oldwords, $pagewords);
354b6344591STom N Harris        $upwords = array();
355a0c5c349STom N Harris        foreach ($delwords as $word) {
356a0c5c349STom N Harris            if($word=='') continue;
357a0c5c349STom N Harris            list($wlen,$wid) = explode('*',$word);
358a0c5c349STom N Harris            $wid = (int)$wid;
359b6344591STom N Harris            $upwords[$wlen][] = $wid;
360b6344591STom N Harris        }
361b6344591STom N Harris        foreach ($upwords as $wlen => $widx) {
362a0c5c349STom N Harris            $index = idx_getIndex('i',$wlen);
363b6344591STom N Harris            foreach ($widx as $wid) {
364a0c5c349STom N Harris                $index[$wid] = idx_updateIndexLine($index[$wid],$pid,0);
365b6344591STom N Harris            }
366a0c5c349STom N Harris            idx_saveIndex('i',$wlen,$index);
367a0c5c349STom N Harris        }
368b6344591STom N Harris    }
369a0c5c349STom N Harris    // Save the reverse index
370b6344591STom N Harris    $pageword_idx = join(':',$pagewords)."\n";
371b6344591STom N Harris    if(!idx_saveIndexLine('pageword','',$pid,$pageword_idx)){
372a0c5c349STom N Harris        trigger_error("Failed to write word index", E_USER_ERROR);
373a0c5c349STom N Harris        return false;
374a0c5c349STom N Harris    }
375579b0f7eSTNHarris
376579b0f7eSTNHarris    return true;
37744ca0adfSAndreas Gohr}
37844ca0adfSAndreas Gohr
37944ca0adfSAndreas Gohr/**
38044ca0adfSAndreas Gohr * Write a new index line to the filehandle
38144ca0adfSAndreas Gohr *
38244ca0adfSAndreas Gohr * This function writes an line for the index file to the
38344ca0adfSAndreas Gohr * given filehandle. It removes the given document from
38444ca0adfSAndreas Gohr * the given line and readds it when $count is >0.
38544ca0adfSAndreas Gohr *
386d5b23302STom N Harris * @deprecated - see idx_updateIndexLine
38744ca0adfSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
38844ca0adfSAndreas Gohr */
38944ca0adfSAndreas Gohrfunction idx_writeIndexLine($fh,$line,$pid,$count){
390d5b23302STom N Harris    fwrite($fh,idx_updateIndexLine($line,$pid,$count));
391d5b23302STom N Harris}
39244ca0adfSAndreas Gohr
393d5b23302STom N Harris/**
394d5b23302STom N Harris * Modify an index line with new information
395d5b23302STom N Harris *
396d5b23302STom N Harris * This returns a line of the index. It removes the
397d5b23302STom N Harris * given document from the line and readds it if
398d5b23302STom N Harris * $count is >0.
399d5b23302STom N Harris *
400d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
401d5b23302STom N Harris * @author Andreas Gohr <andi@splitbrain.org>
402d5b23302STom N Harris */
403d5b23302STom N Harrisfunction idx_updateIndexLine($line,$pid,$count){
404d5b23302STom N Harris    $line = trim($line);
405d5b23302STom N Harris    $updated = array();
40644ca0adfSAndreas Gohr    if($line != ''){
40744ca0adfSAndreas Gohr        $parts = explode(':',$line);
40844ca0adfSAndreas Gohr        // remove doc from given line
40944ca0adfSAndreas Gohr        foreach($parts as $part){
41044ca0adfSAndreas Gohr            if($part == '') continue;
41144ca0adfSAndreas Gohr            list($doc,$cnt) = explode('*',$part);
41244ca0adfSAndreas Gohr            if($doc != $pid){
413d5b23302STom N Harris                $updated[] = $part;
41444ca0adfSAndreas Gohr            }
41544ca0adfSAndreas Gohr        }
41644ca0adfSAndreas Gohr    }
41744ca0adfSAndreas Gohr
41844ca0adfSAndreas Gohr    // add doc
41944ca0adfSAndreas Gohr    if ($count){
420d5b23302STom N Harris        $updated[] = "$pid*$count";
42144ca0adfSAndreas Gohr    }
42244ca0adfSAndreas Gohr
423d5b23302STom N Harris    return join(':',$updated)."\n";
42444ca0adfSAndreas Gohr}
425b4ce25e9SAndreas Gohr
426488dd6ceSAndreas Gohr/**
42722952965SYoBoY * Get the list of lenghts indexed in the wiki
42822952965SYoBoY *
42922952965SYoBoY * Read the index directory or a cache file and returns
43022952965SYoBoY * a sorted array of lengths of the words used in the wiki.
43122952965SYoBoY *
43222952965SYoBoY * @author YoBoY <yoboy.leguesh@gmail.com>
43322952965SYoBoY */
43422952965SYoBoYfunction idx_listIndexLengths() {
43522952965SYoBoY    global $conf;
43622952965SYoBoY    // testing what we have to do, create a cache file or not.
43722952965SYoBoY    if ($conf['readdircache'] == 0) {
43822952965SYoBoY        $docache = false;
43922952965SYoBoY    } else {
44022952965SYoBoY        clearstatcache();
44122952965SYoBoY        if (@file_exists($conf['indexdir'].'/lengths.idx') and (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
44222952965SYoBoY            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ) !== false) {
44322952965SYoBoY                $idx = array();
44422952965SYoBoY                foreach ( $lengths as $length) {
44522952965SYoBoY                    $idx[] = (int)$length;
44622952965SYoBoY                }
44722952965SYoBoY                return $idx;
44822952965SYoBoY            }
44922952965SYoBoY        }
45022952965SYoBoY        $docache = true;
45122952965SYoBoY    }
45222952965SYoBoY
45322952965SYoBoY    if ($conf['readdircache'] == 0 or $docache ) {
45422952965SYoBoY        $dir = @opendir($conf['indexdir']);
45522952965SYoBoY        if($dir===false)
45622952965SYoBoY            return array();
45722952965SYoBoY        $idx[] = array();
45822952965SYoBoY        while (($f = readdir($dir)) !== false) {
45922952965SYoBoY            if (substr($f,0,1) == 'i' && substr($f,-4) == '.idx'){
46022952965SYoBoY                $i = substr($f,1,-4);
46122952965SYoBoY                if (is_numeric($i))
46222952965SYoBoY                    $idx[] = (int)$i;
46322952965SYoBoY            }
46422952965SYoBoY        }
46522952965SYoBoY        closedir($dir);
46622952965SYoBoY        sort($idx);
46722952965SYoBoY        // we save this in a file.
46822952965SYoBoY        if ($docache === true) {
46922952965SYoBoY            $handle = @fopen($conf['indexdir'].'/lengths.idx','w');
47022952965SYoBoY            @fwrite($handle, implode("\n",$idx));
47122952965SYoBoY            @fclose($handle);
47222952965SYoBoY        }
47322952965SYoBoY        return $idx;
47422952965SYoBoY    }
47522952965SYoBoY
47622952965SYoBoY    return array();
47722952965SYoBoY}
47822952965SYoBoY
47922952965SYoBoY/**
480579b0f7eSTNHarris * Get the word lengths that have been indexed.
481579b0f7eSTNHarris *
482579b0f7eSTNHarris * Reads the index directory and returns an array of lengths
483579b0f7eSTNHarris * that there are indices for.
484579b0f7eSTNHarris *
48522952965SYoBoY * @author YoBoY <yoboy.leguesh@gmail.com>
486579b0f7eSTNHarris */
487d5b23302STom N Harrisfunction idx_indexLengths(&$filter){
488579b0f7eSTNHarris    global $conf;
489579b0f7eSTNHarris    $idx = array();
490d5b23302STom N Harris    if (is_array($filter)){
49122952965SYoBoY        // testing if index files exists only
49222952965SYoBoY        foreach ($filter as $key => $value) {
49322952965SYoBoY            if (@file_exists($conf['indexdir']."/i$key.idx")) {
49422952965SYoBoY                $idx[] = $key;
495d5b23302STom N Harris            }
496d5b23302STom N Harris        }
497d5b23302STom N Harris    } else {
49822952965SYoBoY        $lengths = idx_listIndexLengths();
49922952965SYoBoY        foreach ( $lengths as $key => $length) {
50022952965SYoBoY            // we keep all the values equal or superior
50122952965SYoBoY            if ((int)$length >= (int)$filter) {
50222952965SYoBoY                $idx[] = $length;
503d5b23302STom N Harris            }
504579b0f7eSTNHarris        }
505579b0f7eSTNHarris    }
506579b0f7eSTNHarris    return $idx;
507579b0f7eSTNHarris}
508579b0f7eSTNHarris
509579b0f7eSTNHarris/**
510d5b23302STom N Harris * Find the the index number of each search term.
511d5b23302STom N Harris *
512adb16d4fSAndreas Gohr * This will group together words that appear in the same index.
513d5b23302STom N Harris * So it should perform better, because it only opens each index once.
514d5b23302STom N Harris * Actually, it's not that great. (in my experience) Probably because of the disk cache.
515d5b23302STom N Harris * And the sorted function does more work, making it slightly slower in some cases.
516d5b23302STom N Harris *
517d5b23302STom N Harris * @param array    $words   The query terms. Words should only contain valid characters,
518d5b23302STom N Harris *                          with a '*' at either the beginning or end of the word (or both)
519d5b23302STom N Harris * @param arrayref $result  Set to word => array("length*id" ...), use this to merge the
520d5b23302STom N Harris *                          index locations with the appropriate query term.
521d5b23302STom N Harris * @return array            Set to length => array(id ...)
522d5b23302STom N Harris *
523d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
524d5b23302STom N Harris */
525d5b23302STom N Harrisfunction idx_getIndexWordsSorted($words,&$result){
526d5b23302STom N Harris    // parse and sort tokens
527d5b23302STom N Harris    $tokens = array();
528d5b23302STom N Harris    $tokenlength = array();
529d5b23302STom N Harris    $tokenwild = array();
530d5b23302STom N Harris    foreach($words as $word){
531d5b23302STom N Harris        $result[$word] = array();
532d5b23302STom N Harris        $wild = 0;
533d5b23302STom N Harris        $xword = $word;
534d5b23302STom N Harris        $wlen = wordlen($word);
535d5b23302STom N Harris
536d5b23302STom N Harris        // check for wildcards
537d5b23302STom N Harris        if(substr($xword,0,1) == '*'){
538d5b23302STom N Harris            $xword = substr($xword,1);
539d5b23302STom N Harris            $wild |= 1;
540d5b23302STom N Harris            $wlen -= 1;
541d5b23302STom N Harris        }
542d5b23302STom N Harris        if(substr($xword,-1,1) == '*'){
543d5b23302STom N Harris            $xword = substr($xword,0,-1);
544d5b23302STom N Harris            $wild |= 2;
545d5b23302STom N Harris            $wlen -= 1;
546d5b23302STom N Harris        }
54733815ce2SChris Smith        if ($wlen < IDX_MINWORDLENGTH && $wild == 0 && !is_numeric($xword)) continue;
548d5b23302STom N Harris        if(!isset($tokens[$xword])){
549d5b23302STom N Harris            $tokenlength[$wlen][] = $xword;
550d5b23302STom N Harris        }
551d5b23302STom N Harris        if($wild){
552d5b23302STom N Harris            $ptn = preg_quote($xword,'/');
553d5b23302STom N Harris            if(($wild&1) == 0) $ptn = '^'.$ptn;
554d5b23302STom N Harris            if(($wild&2) == 0) $ptn = $ptn.'$';
555d5b23302STom N Harris            $tokens[$xword][] = array($word, '/'.$ptn.'/');
556d5b23302STom N Harris            if(!isset($tokenwild[$xword])) $tokenwild[$xword] = $wlen;
557d5b23302STom N Harris        }else
558d5b23302STom N Harris            $tokens[$xword][] = array($word, null);
559d5b23302STom N Harris    }
560d5b23302STom N Harris    asort($tokenwild);
561d5b23302STom N Harris    // $tokens = array( base word => array( [ query word , grep pattern ] ... ) ... )
562d5b23302STom N Harris    // $tokenlength = array( base word length => base word ... )
563d5b23302STom N Harris    // $tokenwild = array( base word => base word length ... )
564d5b23302STom N Harris
565d5b23302STom N Harris    $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
566d5b23302STom N Harris    $indexes_known = idx_indexLengths($length_filter);
567d5b23302STom N Harris    if(!empty($tokenwild)) sort($indexes_known);
568d5b23302STom N Harris    // get word IDs
569d5b23302STom N Harris    $wids = array();
570d5b23302STom N Harris    foreach($indexes_known as $ixlen){
571d5b23302STom N Harris        $word_idx = idx_getIndex('w',$ixlen);
572d5b23302STom N Harris        // handle exact search
573d5b23302STom N Harris        if(isset($tokenlength[$ixlen])){
574d5b23302STom N Harris            foreach($tokenlength[$ixlen] as $xword){
575d5b23302STom N Harris                $wid = array_search("$xword\n",$word_idx);
576d5b23302STom N Harris                if(is_int($wid)){
577d5b23302STom N Harris                    $wids[$ixlen][] = $wid;
578d5b23302STom N Harris                    foreach($tokens[$xword] as $w)
579d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
580d5b23302STom N Harris                }
581d5b23302STom N Harris            }
582d5b23302STom N Harris        }
583d5b23302STom N Harris        // handle wildcard search
584d5b23302STom N Harris        foreach($tokenwild as $xword => $wlen){
585d5b23302STom N Harris            if($wlen >= $ixlen) break;
586d5b23302STom N Harris            foreach($tokens[$xword] as $w){
587d5b23302STom N Harris                if(is_null($w[1])) continue;
588d5b23302STom N Harris                foreach(array_keys(preg_grep($w[1],$word_idx)) as $wid){
589d5b23302STom N Harris                    $wids[$ixlen][] = $wid;
590d5b23302STom N Harris                    $result[$w[0]][] = "$ixlen*$wid";
591d5b23302STom N Harris                }
592d5b23302STom N Harris            }
593d5b23302STom N Harris        }
594d5b23302STom N Harris    }
595d5b23302STom N Harris    return $wids;
596d5b23302STom N Harris}
597d5b23302STom N Harris
598d5b23302STom N Harris/**
599488dd6ceSAndreas Gohr * Lookup words in index
600488dd6ceSAndreas Gohr *
601488dd6ceSAndreas Gohr * Takes an array of word and will return a list of matching
602488dd6ceSAndreas Gohr * documents for each one.
603488dd6ceSAndreas Gohr *
60463773904SAndreas Gohr * Important: No ACL checking is done here! All results are
60563773904SAndreas Gohr *            returned, regardless of permissions
60663773904SAndreas Gohr *
607488dd6ceSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
608488dd6ceSAndreas Gohr */
609488dd6ceSAndreas Gohrfunction idx_lookup($words){
610488dd6ceSAndreas Gohr    global $conf;
611488dd6ceSAndreas Gohr
612488dd6ceSAndreas Gohr    $result = array();
613488dd6ceSAndreas Gohr
614d5b23302STom N Harris    $wids = idx_getIndexWordsSorted($words, $result);
615d5b23302STom N Harris    if(empty($wids)) return array();
616d5b23302STom N Harris
617488dd6ceSAndreas Gohr    // load known words and documents
618579b0f7eSTNHarris    $page_idx = idx_getIndex('page','');
619488dd6ceSAndreas Gohr
620579b0f7eSTNHarris    $docs = array();                          // hold docs found
621579b0f7eSTNHarris    foreach(array_keys($wids) as $wlen){
622579b0f7eSTNHarris        $wids[$wlen] = array_unique($wids[$wlen]);
623d5b23302STom N Harris        $index = idx_getIndex('i',$wlen);
624d5b23302STom N Harris        foreach($wids[$wlen] as $ixid){
625d5b23302STom N Harris            if($ixid < count($index))
626d5b23302STom N Harris                $docs["$wlen*$ixid"] = idx_parseIndexLine($page_idx,$index[$ixid]);
627488dd6ceSAndreas Gohr        }
628488dd6ceSAndreas Gohr    }
629488dd6ceSAndreas Gohr
630ad81d431SAndreas Gohr    // merge found pages into final result array
631ad81d431SAndreas Gohr    $final = array();
632c66972f2SAdrian Lang    foreach($result as $word => $res){
633ad81d431SAndreas Gohr        $final[$word] = array();
634c66972f2SAdrian Lang        foreach($res as $wid){
635ad81d431SAndreas Gohr            $hits = &$docs[$wid];
636ad81d431SAndreas Gohr            foreach ($hits as $hitkey => $hitcnt) {
637c66972f2SAdrian Lang                if (!isset($final[$word][$hitkey])) {
638c66972f2SAdrian Lang                    $final[$word][$hitkey] = $hitcnt;
639c66972f2SAdrian Lang                } else {
640c66972f2SAdrian Lang                    $final[$word][$hitkey] += $hitcnt;
641c66972f2SAdrian Lang                }
642ad81d431SAndreas Gohr            }
643ad81d431SAndreas Gohr        }
644ad81d431SAndreas Gohr    }
645ad81d431SAndreas Gohr    return $final;
646488dd6ceSAndreas Gohr}
647488dd6ceSAndreas Gohr
648488dd6ceSAndreas Gohr/**
649488dd6ceSAndreas Gohr * Returns a list of documents and counts from a index line
650488dd6ceSAndreas Gohr *
651488dd6ceSAndreas Gohr * It omits docs with a count of 0 and pages that no longer
652488dd6ceSAndreas Gohr * exist.
653488dd6ceSAndreas Gohr *
654488dd6ceSAndreas Gohr * @param  array  $page_idx The list of known pages
655488dd6ceSAndreas Gohr * @param  string $line     A line from the main index
656488dd6ceSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
657488dd6ceSAndreas Gohr */
658488dd6ceSAndreas Gohrfunction idx_parseIndexLine(&$page_idx,$line){
659488dd6ceSAndreas Gohr    $result = array();
660488dd6ceSAndreas Gohr
661488dd6ceSAndreas Gohr    $line = trim($line);
662f5eb7cf0SAndreas Gohr    if($line == '') return $result;
663488dd6ceSAndreas Gohr
664488dd6ceSAndreas Gohr    $parts = explode(':',$line);
665488dd6ceSAndreas Gohr    foreach($parts as $part){
666488dd6ceSAndreas Gohr        if($part == '') continue;
667488dd6ceSAndreas Gohr        list($doc,$cnt) = explode('*',$part);
668488dd6ceSAndreas Gohr        if(!$cnt) continue;
669488dd6ceSAndreas Gohr        $doc = trim($page_idx[$doc]);
670488dd6ceSAndreas Gohr        if(!$doc) continue;
671488dd6ceSAndreas Gohr        // make sure the document still exists
672103c256aSChris Smith        if(!page_exists($doc,'',false)) continue;
673488dd6ceSAndreas Gohr
674488dd6ceSAndreas Gohr        $result[$doc] = $cnt;
675488dd6ceSAndreas Gohr    }
676488dd6ceSAndreas Gohr    return $result;
677488dd6ceSAndreas Gohr}
678488dd6ceSAndreas Gohr
679f5eb7cf0SAndreas Gohr/**
680f5eb7cf0SAndreas Gohr * Tokenizes a string into an array of search words
681f5eb7cf0SAndreas Gohr *
682f5eb7cf0SAndreas Gohr * Uses the same algorithm as idx_getPageWords()
683f5eb7cf0SAndreas Gohr *
684ad81d431SAndreas Gohr * @param string   $string     the query as given by the user
685ad81d431SAndreas Gohr * @param arrayref $stopwords  array of stopwords
686ad81d431SAndreas Gohr * @param boolean  $wc         are wildcards allowed?
687f5eb7cf0SAndreas Gohr */
688ad81d431SAndreas Gohrfunction idx_tokenizer($string,&$stopwords,$wc=false){
689f5eb7cf0SAndreas Gohr    $words = array();
6904efb9a42SAndreas Gohr    $wc = ($wc) ? '' : $wc = '\*';
691f5eb7cf0SAndreas Gohr
692f5eb7cf0SAndreas Gohr    if(preg_match('/[^0-9A-Za-z]/u', $string)){
69391bb5faaSAndreas Gohr        // handle asian chars as single words (may fail on older PHP version)
69460c15d7dSAndreas Gohr        $asia = @preg_replace('/('.IDX_ASIAN.')/u',' \1 ',$string);
69591bb5faaSAndreas Gohr        if(!is_null($asia)) $string = $asia; //recover from regexp failure
69693a60ad2SAndreas Gohr
6974efb9a42SAndreas Gohr        $arr = explode(' ', utf8_stripspecials($string,' ','\._\-:'.$wc));
698f5eb7cf0SAndreas Gohr        foreach ($arr as $w) {
69933815ce2SChris Smith            if (!is_numeric($w) && strlen($w) < IDX_MINWORDLENGTH) continue;
700f5eb7cf0SAndreas Gohr            $w = utf8_strtolower($w);
7013cbaa9a4SAndreas Gohr            if($stopwords && is_int(array_search("$w\n",$stopwords))) continue;
702f5eb7cf0SAndreas Gohr            $words[] = $w;
703f5eb7cf0SAndreas Gohr        }
704f5eb7cf0SAndreas Gohr    }else{
705f5eb7cf0SAndreas Gohr        $w = $string;
70633815ce2SChris Smith        if (!is_numeric($w) && strlen($w) < IDX_MINWORDLENGTH) return $words;
707f5eb7cf0SAndreas Gohr        $w = strtolower($w);
708f5eb7cf0SAndreas Gohr        if(is_int(array_search("$w\n",$stopwords))) return $words;
709f5eb7cf0SAndreas Gohr        $words[] = $w;
710f5eb7cf0SAndreas Gohr    }
711f5eb7cf0SAndreas Gohr
712f5eb7cf0SAndreas Gohr    return $words;
713f5eb7cf0SAndreas Gohr}
714f5eb7cf0SAndreas Gohr
715e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 :
716