xref: /dokuwiki/inc/indexer.php (revision cd763a5b1584197f6e9adf3bbb4f982b6bbaca05)
1<?php
2/**
3 * Functions to create the fulltext search index
4 *
5 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author     Andreas Gohr <andi@splitbrain.org>
7 * @author     Tom N Harris <tnharris@whoopdedo.org>
8 */
9
10if(!defined('DOKU_INC')) die('meh.');
11
12// Version tag used to force rebuild on upgrade
13define('INDEXER_VERSION', 3);
14
15// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens)
16if (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2);
17
18// Asian characters are handled as words. The following regexp defines the
19// Unicode-Ranges for Asian characters
20// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block
21// I'm no language expert. If you think some ranges are wrongly chosen or
22// a range is missing, please contact me
23define('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai
24define('IDX_ASIAN2','['.
25                   '\x{2E80}-\x{3040}'.  // CJK -> Hangul
26                   '\x{309D}-\x{30A0}'.
27                   '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'.
28                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
29                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
30                   ']');
31define('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
32                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
33                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
34                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
35                   '\x{308F}-\x{3094}'.
36                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
37                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
38                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
39                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
40                   ']['.
41                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
42                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
43                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
44                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
45                   '\x{31F0}-\x{31FF}'.
46                   ']?');
47define('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
48
49/**
50 * Version of the indexer taking into consideration the external tokenizer.
51 * The indexer is only compatible with data written by the same version.
52 *
53 * @author Tom N Harris <tnharris@whoopdedo.org>
54 */
55function idx_get_version(){
56    global $conf;
57    if($conf['external_tokenizer'])
58        return INDEXER_VERSION . '+' . trim($conf['tokenizer_cmd']);
59    else
60        return INDEXER_VERSION;
61}
62
63/**
64 * Measure the length of a string.
65 * Differs from strlen in handling of asian characters.
66 *
67 * @author Tom N Harris <tnharris@whoopdedo.org>
68 */
69function wordlen($w){
70    $l = strlen($w);
71    // If left alone, all chinese "words" will get put into w3.idx
72    // So the "length" of a "word" is faked
73    if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) {
74        foreach($leadbytes[0] as $b)
75            $l += ord($b) - 0xE1;
76    }
77    return $l;
78}
79
80/**
81 * Class that encapsulates operations on the indexer database.
82 *
83 * @author Tom N Harris <tnharris@whoopdedo.org>
84 */
85class Doku_Indexer {
86
87    /**
88     * Adds the contents of a page to the fulltext index
89     *
90     * The added text replaces previous words for the same page.
91     * An empty value erases the page.
92     *
93     * @param string    $page   a page name
94     * @param string    $text   the body of the page
95     * @return boolean          the function completed successfully
96     * @author Tom N Harris <tnharris@whoopdedo.org>
97     * @author Andreas Gohr <andi@splitbrain.org>
98     */
99    public function addPageWords($page, $text) {
100        if (!$this->_lock())
101            return "locked";
102
103        // load known documents
104        $page_idx = $this->_addIndexKey('page', '', $page);
105        if ($page_idx === false) {
106            $this->_unlock();
107            return false;
108        }
109
110        $pagewords = array();
111        // get word usage in page
112        $words = $this->_getPageWords($text);
113        if ($words === false) {
114            $this->_unlock();
115            return false;
116        }
117
118        if (!empty($words)) {
119            foreach (array_keys($words) as $wlen) {
120                $index = $this->_getIndex('i', $wlen);
121                foreach ($words[$wlen] as $wid => $freq) {
122                    $idx = ($wid<count($index)) ? $index[$wid] : '';
123                    $index[$wid] = $this->_updateTuple($idx, $pid, $freq);
124                    $pagewords[] = "$wlen*$wid";
125                }
126                if (!$this->_saveIndex('i', $wlen, $index)) {
127                    $this->_unlock();
128                    return false;
129                }
130            }
131        }
132
133        // Remove obsolete index entries
134        $pageword_idx = $this->_getIndexKey('pageword', '', $pid);
135        if ($pageword_idx !== '') {
136            $oldwords = explode(':',$pageword_idx);
137            $delwords = array_diff($oldwords, $pagewords);
138            $upwords = array();
139            foreach ($delwords as $word) {
140                if ($word != '') {
141                    list($wlen,$wid) = explode('*', $word);
142                    $wid = (int)$wid;
143                    $upwords[$wlen][] = $wid;
144                }
145            }
146            foreach ($upwords as $wlen => $widx) {
147                $index = $this->_getIndex('i', $wlen);
148                foreach ($widx as $wid) {
149                    $index[$wid] = $this->_updateTuple($index[$wid], $pid, 0);
150                }
151                $this->_saveIndex('i', $wlen, $index);
152            }
153        }
154        // Save the reverse index
155        $pageword_idx = join(':', $pagewords);
156        if (!$this->_saveIndexKey('pageword', '', $pid, $pageword_idx)) {
157            $this->_unlock();
158            return false;
159        }
160
161        $this->_unlock();
162        return true;
163    }
164
165    /**
166     * Split the words in a page and add them to the index.
167     *
168     * @author Andreas Gohr <andi@splitbrain.org>
169     * @author Christopher Smith <chris@jalakai.co.uk>
170     * @author Tom N Harris <tnharris@whoopdedo.org>
171     */
172    private function _getPageWords($text) {
173        global $conf;
174
175        $tokens = $this->tokenizer($text);
176        $tokens = array_count_values($tokens);  // count the frequency of each token
177
178        $words = array();
179        foreach ($tokens as $w=>$c) {
180            $l = wordlen($w);
181            if (isset($words[$l])){
182                $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
183            }else{
184                $words[$l] = array($w => $c);
185            }
186        }
187
188        // arrive here with $words = array(wordlen => array(word => frequency))
189        $word_idx_modified = false;
190        $index = array();   //resulting index
191        foreach (array_keys($words) as $wlen) {
192            $word_idx = $this->_getIndex('w', $wlen);
193            foreach ($words[$wlen] as $word => $freq) {
194                $wid = array_search($word, $word_idx);
195                if ($wid === false) {
196                    $wid = count($word_idx);
197                    $word_idx[] = $word;
198                    $word_idx_modified = true;
199                }
200                if (!isset($index[$wlen]))
201                    $index[$wlen] = array();
202                $index[$wlen][$wid] = $freq;
203            }
204            // save back the word index
205            if ($word_idx_modified && !$this->_saveIndex('w', $wlen, $word_idx))
206                return false;
207        }
208
209        return $index;
210    }
211
212    /**
213     * Add keys to the metadata index.
214     *
215     * Adding new keys does not remove other keys for the page.
216     * An empty value will erase the key.
217     * The $key parameter can be an array to add multiple keys. $value will
218     * not be used if $key is an array.
219     *
220     * @param string    $page   a page name
221     * @param mixed     $key    a key string or array of key=>value pairs
222     * @param mixed     $value  the value or list of values
223     * @return boolean          the function completed successfully
224     * @author Tom N Harris <tnharris@whoopdedo.org>
225     */
226    public function addMetaKeys($page, $key, $value=null) {
227        if (!is_array($key)) {
228            $key = array($key => $value);
229        } elseif (!is_null($value)) {
230            // $key is array, but $value is not null
231            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
232        }
233
234        $this->_lock();
235
236        // load known documents
237        $pid = $this->_addIndexKey('page', '', $page);
238        if ($pid === false) {
239            $this->_unlock();
240            return false;
241        }
242
243        foreach ($key as $name => $values) {
244            $metaname = idx_cleanName($name);
245            $metaidx = $this->_getIndex($metaname, '_i');
246            $metawords = $this->_getIndex($metaname, '_w');
247            $addwords = false;
248            $update = array();
249            if (!is_array($val)) $values = array($values);
250            foreach ($values as $val) {
251                $val = (string)$val;
252                if ($val !== "") {
253                    $id = array_search($val, $metawords);
254                    if ($id === false) {
255                        $id = count($metawords);
256                        $metawords[$id] = $val;
257                        $addwords = true;
258                    }
259                    $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 1);
260                    $update[$id] = 1;
261                } else {
262                    $id = array_search($val, $metawords);
263                    if ($id !== false) {
264                        $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 0);
265                        $update[$id] = 0;
266                    }
267                }
268            }
269            if (!empty($update)) {
270                if ($addwords)
271                    $this->_saveIndex($metaname.'_w', '', $metawords);
272                $this->_saveIndex($metaname.'_i', '', $metaidx);
273                $val_idx = $this->_getIndexKey($metaname, '_p', $pid);
274                $val_idx = array_flip(explode(':', $val_idx));
275                foreach ($update as $id => $add) {
276                    if ($add) $val_idx[$id] = 1;
277                    else unset($val_idx[$id]);
278                }
279                $val_idx = array_keys($val_idx);
280                $this->_saveIndexKey($metaname.'_p', '', $pid, implode(':', $val_idx));
281            }
282            unset($metaidx);
283            unset($metawords);
284        }
285        return true;
286    }
287
288    /**
289     * Remove a page from the index
290     *
291     * Erases entries in all known indexes.
292     *
293     * @param string    $page   a page name
294     * @return boolean          the function completed successfully
295     * @author Tom N Harris <tnharris@whoopdedo.org>
296     */
297    public function deletePage($page) {
298    }
299
300    /**
301     * Split the text into words for fulltext search
302     *
303     * TODO: does this also need &$stopwords ?
304     *
305     * @param string    $text   plain text
306     * @param boolean   $wc     are wildcards allowed?
307     * @return array            list of words in the text
308     * @author Tom N Harris <tnharris@whoopdedo.org>
309     * @author Andreas Gohr <andi@splitbrain.org>
310     */
311    public function tokenizer($text, $wc=false) {
312        global $conf;
313        $words = array();
314        $wc = ($wc) ? '' : '\*';
315        $stopwords =& idx_get_stopwords();
316
317        if ($conf['external_tokenizer'] && $conf['tokenizer_cmd'] != '') {
318            if (0 == io_exec($conf['tokenizer_cmd'], $text, $output))
319                $text = $output;
320        } else {
321            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
322                // handle asian chars as single words (may fail on older PHP version)
323                $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text);
324                if (!is_null($asia)) $text = $asia; // recover from regexp falure
325            }
326        }
327        $text = strtr($text, "\r\n\t", '   ');
328        if (preg_match('/[^0-9A-Za-z ]/u', $text))
329            $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
330
331        $wordlist = explode(' ', $text);
332        foreach ($wordlist as $word) {
333            $word = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
334                utf8_strtolower($word) : strtolower($word);
335            if (!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) continue;
336            if (array_search($word, $stopwords) !== false) continue;
337            $words[] = $word;
338        }
339        return $words;
340    }
341
342    /**
343     * Find pages in the fulltext index containing the words,
344     *
345     * The search words must be pre-tokenized, meaning only letters and
346     * numbers with an optional wildcard
347     *
348     * The returned array will have the original tokens as key. The values
349     * in the returned list is an array with the page names as keys and the
350     * number of times that token appeas on the page as value.
351     *
352     * @param arrayref  $tokens list of words to search for
353     * @return array            list of page names with usage counts
354     * @author Tom N Harris <tnharris@whoopdedo.org>
355     * @author Andreas Gohr <andi@splitbrain.org>
356     */
357    public function lookup(&$tokens) {
358        $result = array();
359        $wids = $this->_getIndexWords($tokens, $result);
360        if (empty($wids)) return array();
361        // load known words and documents
362        $page_idx = $this->_getIndex('page', '');
363        $docs = array();
364        foreach (array_keys($wids) as $wlen) {
365            $wids[$wlen] = array_unique($wids[$wlen]);
366            $index = $this->_getIndex('i', $wlen);
367            foreach($wids[$wlen] as $ixid) {
368                if ($ixid < count($index))
369                    $docs["$wlen*$ixid"] = $this->_parseTuples($page_idx, $index[$ixid]);
370            }
371        }
372        // merge found pages into final result array
373        $final = array();
374        foreach ($result as $word => $res) {
375            $final[$word] = array();
376            foreach ($res as $wid) {
377                $hits = &$docs[$wid];
378                foreach ($hits as $hitkey => $hitcnt) {
379                    // make sure the document still exists
380                    if (!page_exists($hitkey, '', false)) continue;
381                    if (!isset($final[$word][$hitkey]))
382                        $final[$word][$hitkey] = $hitcnt;
383                    else
384                        $final[$word][$hitkey] += $hitcnt;
385                }
386            }
387        }
388        return $final;
389    }
390
391    /**
392     * Find pages containing a metadata key.
393     *
394     * The metadata values are compared as case-sensitive strings. Pass a
395     * callback function that returns true or false to use a different
396     * comparison function
397     *
398     * @param string    $key    name of the metadata key to look for
399     * @param string    $value  search term to look for
400     * @param callback  $func   comparison function
401     * @return array            list with page names, keys are query values if more than one given
402     * @author Tom N Harris <tnharris@whoopdedo.org>
403     * @author Michael Hamann <michael@content-space.de>
404     */
405    public function lookupKey($key, $value, $func=null) {
406        $metaname = idx_cleanName($key);
407
408        // get all words in order to search the matching ids
409        $words = $this->_getIndex($metaname, '_w');
410
411        // the matching ids for the provided value(s)
412        $value_ids = array();
413
414        if (!is_array($value)) $value = array($value);
415
416        foreach ($value as $val) {
417            if (is_null($func)) {
418                if (($i = array_search($val, $words)) !== false)
419                    $value_ids[$i] = $val;
420            } else {
421                foreach ($words as $i => $word) {
422                    if (call_user_func_array($func, array($word, $value)))
423                        $value_ids[$i] = $val;
424                }
425            }
426        }
427
428        unset($words); // free the used memory
429
430        // load all lines and pages so the used lines can be taken and matched with the pages
431        $lines = $this->_getIndex($metaname, '_i');
432        $page_idx = $this->_getIndex('page', '');
433
434        $result = array();
435        foreach ($value_ids as $value_id => $val) {
436            // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
437            // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
438            $result[$val] = array_keys($this->_parseTuples($page_idx, $lines[$value_id]));
439        }
440        return $result;
441    }
442
443    /**
444     * Find the index ID of each search term.
445     *
446     * The query terms should only contain valid characters, with a '*' at
447     * either the beginning or end of the word (or both).
448     * The $result parameter can be used to merge the index locations with
449     * the appropriate query term.
450     *
451     * @param arrayref  $words  The query terms.
452     * @param arrayref  $result Set to word => array("length*id" ...)
453     * @return array            Set to length => array(id ...)
454     * @author Tom N Harris <tnharris@whoopdedo.org>
455     */
456    private function _getIndexWords(&$words, &$result) {
457        $tokens = array();
458        $tokenlength = array();
459        $tokenwild = array();
460        foreach ($words as $word) {
461            $result[$word] = array();
462            $caret = false;
463            $dollar = false;
464            $xword = $word;
465            $wlen = wordlen($word);
466
467            // check for wildcards
468            if (substr($xword, 0, 1) == '*') {
469                $xword = substr($xword, 1);
470                $caret = true;
471                $wlen -= 1;
472            }
473            if (substr($xword, -1, 1) == '*') {
474                $xword = substr($xword, 0, -1);
475                $dollar = true;
476                $wlen -= 1;
477            }
478            if ($wlen < IDX_MINWORDLENGTH && !$caret && !$dollar && !is_numeric($xword))
479                continue;
480            if (!isset($tokens[$xword]))
481                $tokenlength[$wlen][] = $xword;
482            if ($caret || $dollar) {
483                $re = preg_quote($xword, '/');
484                if ($caret) $re = '^'.$re;
485                if ($dollar) $re = $re.'$';
486                $tokens[$xword][] = array($word, '/'.$re.'/');
487                if (!isset($tokenwild[$xword]))
488                    $tokenwild[$xword] = $wlen;
489            } else {
490                $tokens[$xword][] = array($word, null);
491            }
492        }
493        asort($tokenwild);
494        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
495        // $tokenlength = array( base word length => base word ... )
496        // $tokenwild = array( base word => base word length ... )
497        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
498        $indexes_known = $this->_indexLengths($length_filter);
499        if (!empty($tokenwild)) sort($indexes_known);
500        // get word IDs
501        $wids = array();
502        foreach ($indexes_known as $ixlen) {
503            $word_idx = $this->_getIndex('w', $ixlen);
504            // handle exact search
505            if (isset($tokenlength[$ixlen])) {
506                foreach ($tokenlength[$ixlen] as $xword) {
507                    $wid = array_search($xword, $word_idx);
508                    if ($wid !== false) {
509                        $wids[$ixlen][] = $wid;
510                        foreach ($tokens[$xword] as $w)
511                            $result[$w[0]][] = "$ixlen*$wid";
512                    }
513                }
514            }
515            // handle wildcard search
516            foreach ($tokenwild as $xword => $wlen) {
517                if ($wlen >= $ixlen) break;
518                foreach ($tokens[$xword] as $w) {
519                    if (is_null($w[1])) continue;
520                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
521                        $wids[$ixlen][] = $wid;
522                        $result[$w[0]][] = "$ixlen*$wid";
523                    }
524                }
525            }
526        }
527        return $wids;
528    }
529
530    /**
531     * Return a list of all pages
532     *
533     * @param string    $key    list only pages containing the metadata key (optional)
534     * @return array            list of page names
535     * @author Tom N Harris <tnharris@whoopdedo.org>
536     */
537    public function getPages($key=null) {
538        $page_idx = $this->_getIndex('page', '');
539        if (is_null($key)) return $page_idx;
540    }
541
542    /**
543     * Return a list of words sorted by number of times used
544     *
545     * @param int       $min    bottom frequency threshold
546     * @param int       $max    upper frequency limit. No limit if $max<$min
547     * @param string    $key    metadata key to list. Uses the fulltext index if not given
548     * @return array            list of words as the keys and frequency as values
549     * @author Tom N Harris <tnharris@whoopdedo.org>
550     */
551    public function histogram($min=1, $max=0, $key=null) {
552    }
553
554    /**
555     * Lock the indexer.
556     *
557     * @author Tom N Harris <tnharris@whoopdedo.org>
558     */
559    private function _lock() {
560        global $conf;
561        $status = true;
562        $lock = $conf['lockdir'].'/_indexer.lock';
563        while (!@mkdir($lock, $conf['dmode'])) {
564            usleep(50);
565            if (time() - @filemtime($lock) > 60*5) {
566                // looks like a stale lock, remove it
567                @rmdir($lock);
568                $status = "stale lock removed";
569            } else {
570                return false;
571            }
572        }
573        if ($conf['dperm'])
574            chmod($lock, $conf['dperm']);
575        return $status;
576    }
577
578    /**
579     * Release the indexer lock.
580     *
581     * @author Tom N Harris <tnharris@whoopdedo.org>
582     */
583    private function _unlock() {
584        global $conf;
585        @rmdir($conf['lockdir'].'/_indexer.lock');
586        return true;
587    }
588
589    /**
590     * Retrieve the entire index.
591     *
592     * @author Tom N Harris <tnharris@whoopdedo.org>
593     */
594    private function _getIndex($idx, $suffix) {
595        global $conf;
596        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
597        if (!@file_exists($fn)) return array();
598        return file($fn, FILE_IGNORE_NEW_LINES);
599    }
600
601    /**
602     * Replace the contents of the index with an array.
603     *
604     * @author Tom N Harris <tnharris@whoopdedo.org>
605     */
606    private function _saveIndex($idx, $suffix, &$lines) {
607        global $conf;
608        $fn = $conf['indexdir'].'/'.$idx.$suffix;
609        $fh = @fopen($fn.'.tmp', 'w');
610        if (!$fh) return false;
611        fwrite($fh, join("\n", $lines));
612        fclose($fh);
613        if (isset($conf['fperm']))
614            chmod($fn.'.tmp', $conf['fperm']);
615        io_rename($fn.'.tmp', $fn.'.idx');
616        if ($suffix !== '')
617            $this->_cacheIndexDir($idx, $suffix, empty($lines));
618        return true;
619    }
620
621    /**
622     * Retrieve a line from the index.
623     *
624     * @author Tom N Harris <tnharris@whoopdedo.org>
625     */
626    private function _getIndexKey($idx, $suffix, $id) {
627        global $conf;
628        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
629        if (!@file_exists($fn)) return '';
630        $fh = @fopen($fn, 'r');
631        if (!$fh) return '';
632        $ln = -1;
633        while (($line = fgets($fh)) !== false) {
634            if (++$ln == $id) break;
635        }
636        fclose($fh);
637        return rtrim((string)$line);
638    }
639
640    /**
641     * Write a line into the index.
642     *
643     * @author Tom N Harris <tnharris@whoopdedo.org>
644     */
645    private function _saveIndexKey($idx, $suffix, $id, $line) {
646        global $conf;
647        if (substr($line, -1) != "\n")
648            $line .= "\n";
649        $fn = $conf['indexdir'].'/'.$idx.$suffix;
650        $fh = @fopen($fn.'.tmp', 'w');
651        if (!fh) return false;
652        $ih = @fopen($fn.'.idx', 'r');
653        if ($ih) {
654            $ln = -1;
655            while (($curline = fgets($ih)) !== false) {
656                fwrite($fh, (++$ln == $id) ? $line : $curline);
657            }
658            if ($id > $ln) {
659                while ($id > ++$ln)
660                    fwrite($fh, "\n");
661                fwrite($fh, $line);
662            }
663            fclose($ih);
664        } else {
665            $ln = -1;
666            while ($id > ++$ln)
667                fwrite($fh, "\n");
668            fwrite($fh, $line);
669        }
670        fclose($fh);
671        if (isset($conf['fperm']))
672            chmod($fn.'.tmp', $conf['fperm']);
673        io_rename($fn.'.tmp', $fn.'.idx');
674        if ($suffix !== '')
675            $this->_cacheIndexDir($idx, $suffix);
676        return true;
677    }
678
679    /**
680     * Retrieve or insert a value in the index.
681     *
682     * @author Tom N Harris <tnharris@whoopdedo.org>
683     */
684    private function _addIndexKey($idx, $suffix, $value) {
685        $index = $this->_getIndex($idx, $suffix);
686        $id = array_search($value, $index);
687        if ($id === false) {
688            $id = count($index);
689            $index[$id] = $value;
690            if (!$this->_saveIndex($idx, $suffix, $index)) {
691                trigger_error("Failed to write $idx index", E_USER_ERROR);
692                return false;
693            }
694        }
695        return $id;
696    }
697
698    private function _cacheIndexDir($idx, $suffix, $delete=false) {
699        global $conf;
700        if ($idx == 'i')
701            $cachename = $conf['indexdir'].'/lengths';
702        else
703            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
704        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
705        if ($lengths === false) $lengths = array();
706        $old = array_search((string)$suffix, $lengths);
707        if (empty($lines)) {
708            if ($old === false) return;
709            unset($lengths[$old]);
710        } else {
711            if ($old !== false) return;
712            $lengths[] = $suffix;
713            sort($lengths);
714        }
715        $fh = @fopen($cachename.'.tmp', 'w');
716        if (!$fh) {
717            trigger_error("Failed to write index cache", E_USER_ERROR);
718            return;
719        }
720        @fwrite($fh, implode("\n", $lengths));
721        @fclose($fh);
722        if (isset($conf['fperm']))
723            chmod($cachename.'.tmp', $conf['fperm']);
724        io_rename($cachename.'.tmp', $cachename.'.idx');
725    }
726
727    /**
728     * Get the list of lengths indexed in the wiki.
729     *
730     * Read the index directory or a cache file and returns
731     * a sorted array of lengths of the words used in the wiki.
732     *
733     * @author YoBoY <yoboy.leguesh@gmail.com>
734     */
735    private function _listIndexLengths() {
736        global $conf;
737        $cachename = $conf['indexdir'].'/lengths';
738        clearstatcache();
739        if (@file_exists($cachename.'.idx')) {
740            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
741            if ($lengths !== false) {
742                $idx = array();
743                foreach ($lengths as $length)
744                    $idx[] = (int)$length;
745                return $idx;
746            }
747        }
748
749        $dir = @opendir($conf['indexdir']);
750        if ($dir === false)
751            return array();
752        $lengths[] = array();
753        while (($f = readdir($dir)) !== false) {
754            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
755                $i = substr($f, 1, -4);
756                if (is_numeric($i))
757                    $lengths[] = (int)$i;
758            }
759        }
760        closedir($dir);
761        sort($lengths);
762        // save this in a file
763        $fh = @fopen($cachename.'.tmp', 'w');
764        if (!$fh) {
765            trigger_error("Failed to write index cache", E_USER_ERROR);
766            return;
767        }
768        @fwrite($fh, implode("\n", $lengths));
769        @fclose($fh);
770        if (isset($conf['fperm']))
771            chmod($cachename.'.tmp', $conf['fperm']);
772        io_rename($cachename.'.tmp', $cachename.'.idx');
773
774        return $lengths;
775    }
776
777    /**
778     * Get the word lengths that have been indexed.
779     *
780     * Reads the index directory and returns an array of lengths
781     * that there are indices for.
782     *
783     * @author YoBoY <yoboy.leguesh@gmail.com>
784     */
785    private function _indexLengths($filter) {
786        global $conf;
787        $idx = array();
788        if (is_array($filter)) {
789            // testing if index files exist only
790            $path = $conf['indexdir']."/i";
791            foreach ($filter as $key => $value) {
792                if (@file_exists($path.$key.'.idx'))
793                    $idx[] = $key;
794            }
795        } else {
796            $lengths = idx_listIndexLengths();
797            foreach ($lengths as $key => $length) {
798                // keep all the values equal or superior
799                if ((int)$length >= (int)$filter)
800                    $idx[] = $length;
801            }
802        }
803        return $idx;
804    }
805
806    /**
807     * Insert or replace a tuple in a line.
808     *
809     * @author Tom N Harris <tnharris@whoopdedo.org>
810     */
811    private function _updateTuple($line, $id, $count) {
812        $newLine = $line;
813        if ($newLine !== '')
814            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
815        $newLine = trim($newLine, ':');
816        if ($count) {
817            if (strlen($newLine) > 0)
818                return "$id*$count:".$newLine;
819            else
820                return "$id*$count".$newLine;
821        }
822        return $newLine;
823    }
824
825    /**
826     * Split a line into an array of tuples.
827     *
828     * @author Tom N Harris <tnharris@whoopdedo.org>
829     * @author Andreas Gohr <andi@splitbrain.org>
830     */
831    private function _parseTuples(&$keys, $line) {
832        $result = array();
833        if ($line == '') return $result;
834        $parts = explode(':', $line);
835        foreach ($parts as $tuple) {
836            if ($tuple == '') continue;
837            list($key, $cnt) = explode('*', $tuple);
838            if (!$cnt) continue;
839            $key = $keys[$key];
840            if (!$key) continue;
841            $result[$key] = $cnt;
842        }
843        return $result;
844    }
845}
846
847/**
848 * Create an instance of the indexer.
849 *
850 * @return object               a Doku_Indexer
851 * @author Tom N Harris <tnharris@whoopdedo.org>
852 */
853function idx_get_indexer() {
854    static $Indexer = null;
855    if (is_null($Indexer)) {
856        $Indexer = new Doku_Indexer();
857    }
858    return $Indexer;
859}
860
861/**
862 * Returns words that will be ignored.
863 *
864 * @return array                list of stop words
865 * @author Tom N Harris <tnharris@whoopdedo.org>
866 */
867function & idx_get_stopwords() {
868    static $stopwords = null;
869    if (is_null($stopwords)) {
870        global $conf;
871        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
872        if(@file_exists($swfile)){
873            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
874        }else{
875            $stopwords = array();
876        }
877    }
878    return $stopwords;
879}
880
881/**
882 * Adds/updates the search index for the given page
883 *
884 * Locking is handled internally.
885 *
886 * @param string        $page   name of the page to index
887 * @param boolean       $verbose    print status messages
888 * @return boolean              the function completed successfully
889 * @author Tom N Harris <tnharris@whoopdedo.org>
890 */
891function idx_addPage($page, $verbose=false) {
892    // check if indexing needed
893    $idxtag = metaFN($page,'.indexed');
894    if(@file_exists($idxtag)){
895        if(trim(io_readFile($idxtag)) == idx_get_version()){
896            $last = @filemtime($idxtag);
897            if($last > @filemtime(wikiFN($ID))){
898                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
899                return false;
900            }
901        }
902    }
903
904    $body = '';
905    $data = array($page, $body);
906    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
907    if ($evt->advise_before()) $data[1] = $data[1] . " " . rawWiki($page);
908    $evt->advise_after();
909    unset($evt);
910    list($page,$body) = $data;
911
912    $Indexer = idx_get_indexer();
913    $result = $Indexer->addPageWords($page, $body);
914    if ($result == "locked") {
915        if ($verbose) print("Indexer: locked".DOKU_LF);
916        return false;
917    }
918    if ($result)
919        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
920    if ($verbose) {
921        print("Indexer: finished".DOKU_LF);
922        return true;
923    }
924    return $result;
925}
926
927/**
928 * Find tokens in the fulltext index
929 *
930 * Takes an array of words and will return a list of matching
931 * pages for each one.
932 *
933 * Important: No ACL checking is done here! All results are
934 *            returned, regardless of permissions
935 *
936 * @param arrayref      $words  list of words to search for
937 * @return array                list of pages found, associated with the search terms
938 */
939function idx_lookup(&$words) {
940    $Indexer = idx_get_indexer();
941    return $Indexer->lookup($words);
942}
943
944/**
945 * Split a string into tokens
946 *
947 */
948function idx_tokenizer($string, $wc=false) {
949    $Indexer = idx_get_indexer();
950    return $Indexer->tokenizer($string, $wc);
951}
952
953/* For compatibility */
954
955/**
956 * Read the list of words in an index (if it exists).
957 *
958 * @author Tom N Harris <tnharris@whoopdedo.org>
959 */
960function idx_getIndex($idx, $suffix) {
961    global $conf;
962    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
963    if (!@file_exists($fn)) return array();
964    return file($fn);
965}
966
967/**
968 * Get the list of lengths indexed in the wiki.
969 *
970 * Read the index directory or a cache file and returns
971 * a sorted array of lengths of the words used in the wiki.
972 *
973 * @author YoBoY <yoboy.leguesh@gmail.com>
974 */
975function idx_listIndexLengths() {
976    global $conf;
977    // testing what we have to do, create a cache file or not.
978    if ($conf['readdircache'] == 0) {
979        $docache = false;
980    } else {
981        clearstatcache();
982        if (@file_exists($conf['indexdir'].'/lengths.idx')
983        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
984            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
985                $idx = array();
986                foreach ($lengths as $length) {
987                    $idx[] = (int)$length;
988                }
989                return $idx;
990            }
991        }
992        $docache = true;
993    }
994
995    if ($conf['readdircache'] == 0 || $docache) {
996        $dir = @opendir($conf['indexdir']);
997        if ($dir === false)
998            return array();
999        $idx[] = array();
1000        while (($f = readdir($dir)) !== false) {
1001            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
1002                $i = substr($f, 1, -4);
1003                if (is_numeric($i))
1004                    $idx[] = (int)$i;
1005            }
1006        }
1007        closedir($dir);
1008        sort($idx);
1009        // save this in a file
1010        if ($docache) {
1011            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
1012            @fwrite($handle, implode("\n", $idx));
1013            @fclose($handle);
1014        }
1015        return $idx;
1016    }
1017
1018    return array();
1019}
1020
1021/**
1022 * Get the word lengths that have been indexed.
1023 *
1024 * Reads the index directory and returns an array of lengths
1025 * that there are indices for.
1026 *
1027 * @author YoBoY <yoboy.leguesh@gmail.com>
1028 */
1029function idx_indexLengths($filter) {
1030    global $conf;
1031    $idx = array();
1032    if (is_array($filter)) {
1033        // testing if index files exist only
1034        $path = $conf['indexdir']."/i";
1035        foreach ($filter as $key => $value) {
1036            if (@file_exists($path.$key.'.idx'))
1037                $idx[] = $key;
1038        }
1039    } else {
1040        $lengths = idx_listIndexLengths();
1041        foreach ($lengths as $key => $length) {
1042            // keep all the values equal or superior
1043            if ((int)$length >= (int)$filter)
1044                $idx[] = $length;
1045        }
1046    }
1047    return $idx;
1048}
1049
1050/**
1051 * Clean a name of a key for use as a file name.
1052 *
1053 * Romanizes non-latin characters, then strips away anything that's
1054 * not a letter, number, or underscore.
1055 *
1056 * @author Tom N Harris <tnharris@whoopdedo.org>
1057 */
1058function idx_cleanName($name) {
1059    $name = utf8_romanize(trim((string)$name));
1060    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
1061    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
1062    return strtolower($name);
1063}
1064
1065//Setup VIM: ex: et ts=4 :
1066