xref: /dokuwiki/inc/indexer.php (revision bbc85ee4bc98fadf89707309f923f8ae2c16f727)
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/update keys to/of 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     * @author Michael Hamann <michael@content-space.de>
226     */
227    public function addMetaKeys($page, $key, $value=null) {
228        if (!is_array($key)) {
229            $key = array($key => $value);
230        } elseif (!is_null($value)) {
231            // $key is array, but $value is not null
232            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
233        }
234
235        if (!$this->_lock())
236            return "locked";
237
238        // load known documents
239        $pid = $this->_addIndexKey('page', '', $page);
240        if ($pid === false) {
241            $this->_unlock();
242            return false;
243        }
244
245        foreach ($key as $name => $values) {
246            $metaname = idx_cleanName($name);
247            $metaidx = $this->_getIndex($metaname, '_i');
248            $metawords = $this->_getIndex($metaname, '_w');
249            $addwords = false;
250
251            if (!is_array($values)) $values = array($values);
252
253            $val_idx = $this->_getIndexKey($metaname, '_p', $pid);
254            if ($val_idx != '') {
255                $val_idx = explode(':', $val_idx);
256                // -1 means remove, 0 keep, 1 add
257                $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
258            } else {
259                $val_idx = array();
260            }
261
262
263            foreach ($values as $val) {
264                $val = (string)$val;
265                if ($val !== "") {
266                    $id = array_search($val, $metawords);
267                    if ($id === false) {
268                        $id = count($metawords);
269                        $metawords[$id] = $val;
270                        $addwords = true;
271                    }
272                    // test if value is already in the index
273                    if (isset($val_idx[$id]) && $val_idx[$id] <= 0)
274                        $val_idx[$id] = 0;
275                    else // else add it
276                        $val_idx[$id] = 1;
277                }
278            }
279
280            if ($addwords)
281                $this->_saveIndex($metaname.'_w', '', $metawords);
282            $vals_changed = false;
283            foreach ($val_idx as $id => $action) {
284                if ($action == -1) {
285                    $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 0);
286                    $vals_changed = true;
287                    unset($val_idx[$id]);
288                } elseif ($action == 1) {
289                    $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 1);
290                    $vals_changed = true;
291                }
292            }
293
294            if ($vals_changed) {
295                $this->_saveIndex($metaname.'_i', '', $metaidx);
296                $val_idx = implode(':', array_keys($val_idx));
297                $this->_saveIndexKey($metaname.'_p', '', $pid, $val_idx);
298            }
299
300            unset($metaidx);
301            unset($metawords);
302        }
303
304        $this->_unlock();
305        return true;
306    }
307
308    /**
309     * Remove a page from the index
310     *
311     * Erases entries in all known indexes.
312     *
313     * @param string    $page   a page name
314     * @return boolean          the function completed successfully
315     * @author Tom N Harris <tnharris@whoopdedo.org>
316     */
317    public function deletePage($page) {
318        if (!$this->_lock())
319            return "locked";
320
321        // load known documents
322        $page_idx = $this->_getIndexKey('page', '', $page);
323        if ($page_idx === false) {
324            $this->_unlock();
325            return false;
326        }
327
328        // Remove obsolete index entries
329        $pageword_idx = $this->_getIndexKey('pageword', '', $pid);
330        if ($pageword_idx !== '') {
331            $delwords = explode(':',$pageword_idx);
332            $upwords = array();
333            foreach ($delwords as $word) {
334                if ($word != '') {
335                    list($wlen,$wid) = explode('*', $word);
336                    $wid = (int)$wid;
337                    $upwords[$wlen][] = $wid;
338                }
339            }
340            foreach ($upwords as $wlen => $widx) {
341                $index = $this->_getIndex('i', $wlen);
342                foreach ($widx as $wid) {
343                    $index[$wid] = $this->_updateTuple($index[$wid], $pid, 0);
344                }
345                $this->_saveIndex('i', $wlen, $index);
346            }
347        }
348        // Save the reverse index
349        if (!$this->_saveIndexKey('pageword', '', $pid, "")) {
350            $this->_unlock();
351            return false;
352        }
353
354        // XXX TODO: delete meta keys
355
356        $this->_unlock();
357        return true;
358    }
359
360    /**
361     * Split the text into words for fulltext search
362     *
363     * TODO: does this also need &$stopwords ?
364     *
365     * @param string    $text   plain text
366     * @param boolean   $wc     are wildcards allowed?
367     * @return array            list of words in the text
368     * @author Tom N Harris <tnharris@whoopdedo.org>
369     * @author Andreas Gohr <andi@splitbrain.org>
370     */
371    public function tokenizer($text, $wc=false) {
372        global $conf;
373        $words = array();
374        $wc = ($wc) ? '' : '\*';
375        $stopwords =& idx_get_stopwords();
376
377        if ($conf['external_tokenizer'] && $conf['tokenizer_cmd'] != '') {
378            if (0 == io_exec($conf['tokenizer_cmd'], $text, $output))
379                $text = $output;
380        } else {
381            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
382                // handle asian chars as single words (may fail on older PHP version)
383                $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text);
384                if (!is_null($asia)) $text = $asia; // recover from regexp falure
385            }
386        }
387        $text = strtr($text, "\r\n\t", '   ');
388        if (preg_match('/[^0-9A-Za-z ]/u', $text))
389            $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
390
391        $wordlist = explode(' ', $text);
392        foreach ($wordlist as $word) {
393            $word = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
394                utf8_strtolower($word) : strtolower($word);
395            if (!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) continue;
396            if (array_search($word, $stopwords) !== false) continue;
397            $words[] = $word;
398        }
399        return $words;
400    }
401
402    /**
403     * Find pages in the fulltext index containing the words,
404     *
405     * The search words must be pre-tokenized, meaning only letters and
406     * numbers with an optional wildcard
407     *
408     * The returned array will have the original tokens as key. The values
409     * in the returned list is an array with the page names as keys and the
410     * number of times that token appeas on the page as value.
411     *
412     * @param arrayref  $tokens list of words to search for
413     * @return array            list of page names with usage counts
414     * @author Tom N Harris <tnharris@whoopdedo.org>
415     * @author Andreas Gohr <andi@splitbrain.org>
416     */
417    public function lookup(&$tokens) {
418        $result = array();
419        $wids = $this->_getIndexWords($tokens, $result);
420        if (empty($wids)) return array();
421        // load known words and documents
422        $page_idx = $this->_getIndex('page', '');
423        $docs = array();
424        foreach (array_keys($wids) as $wlen) {
425            $wids[$wlen] = array_unique($wids[$wlen]);
426            $index = $this->_getIndex('i', $wlen);
427            foreach($wids[$wlen] as $ixid) {
428                if ($ixid < count($index))
429                    $docs["$wlen*$ixid"] = $this->_parseTuples($page_idx, $index[$ixid]);
430            }
431        }
432        // merge found pages into final result array
433        $final = array();
434        foreach ($result as $word => $res) {
435            $final[$word] = array();
436            foreach ($res as $wid) {
437                $hits = &$docs[$wid];
438                foreach ($hits as $hitkey => $hitcnt) {
439                    // make sure the document still exists
440                    if (!page_exists($hitkey, '', false)) continue;
441                    if (!isset($final[$word][$hitkey]))
442                        $final[$word][$hitkey] = $hitcnt;
443                    else
444                        $final[$word][$hitkey] += $hitcnt;
445                }
446            }
447        }
448        return $final;
449    }
450
451    /**
452     * Find pages containing a metadata key.
453     *
454     * The metadata values are compared as case-sensitive strings. Pass a
455     * callback function that returns true or false to use a different
456     * comparison function
457     *
458     * @param string    $key    name of the metadata key to look for
459     * @param string    $value  search term to look for
460     * @param callback  $func   comparison function
461     * @return array            lists with page names, keys are query values
462     * @author Tom N Harris <tnharris@whoopdedo.org>
463     * @author Michael Hamann <michael@content-space.de>
464     */
465    public function lookupKey($key, $value, $func=null) {
466        $metaname = idx_cleanName($key);
467
468        // get all words in order to search the matching ids
469        $words = $this->_getIndex($metaname, '_w');
470
471        // the matching ids for the provided value(s)
472        $value_ids = array();
473
474        if (!is_array($value)) $value = array($value);
475
476        foreach ($value as $val) {
477            if (is_null($func)) {
478                if (($i = array_search($val, $words)) !== false)
479                    $value_ids[$i] = $val;
480            } else {
481                foreach ($words as $i => $word) {
482                    if (call_user_func_array($func, array($word, $value)))
483                        $value_ids[$i] = $val;
484                }
485            }
486        }
487
488        unset($words); // free the used memory
489
490        // load all lines and pages so the used lines can be taken and matched with the pages
491        $lines = $this->_getIndex($metaname, '_i');
492        $page_idx = $this->_getIndex('page', '');
493
494        $result = array();
495        foreach ($value_ids as $value_id => $val) {
496            // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
497            // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
498            $result[$val] = array_keys($this->_parseTuples($page_idx, $lines[$value_id]));
499        }
500        return $result;
501    }
502
503    /**
504     * Find the index ID of each search term.
505     *
506     * The query terms should only contain valid characters, with a '*' at
507     * either the beginning or end of the word (or both).
508     * The $result parameter can be used to merge the index locations with
509     * the appropriate query term.
510     *
511     * @param arrayref  $words  The query terms.
512     * @param arrayref  $result Set to word => array("length*id" ...)
513     * @return array            Set to length => array(id ...)
514     * @author Tom N Harris <tnharris@whoopdedo.org>
515     */
516    private function _getIndexWords(&$words, &$result) {
517        $tokens = array();
518        $tokenlength = array();
519        $tokenwild = array();
520        foreach ($words as $word) {
521            $result[$word] = array();
522            $caret = false;
523            $dollar = false;
524            $xword = $word;
525            $wlen = wordlen($word);
526
527            // check for wildcards
528            if (substr($xword, 0, 1) == '*') {
529                $xword = substr($xword, 1);
530                $caret = true;
531                $wlen -= 1;
532            }
533            if (substr($xword, -1, 1) == '*') {
534                $xword = substr($xword, 0, -1);
535                $dollar = true;
536                $wlen -= 1;
537            }
538            if ($wlen < IDX_MINWORDLENGTH && !$caret && !$dollar && !is_numeric($xword))
539                continue;
540            if (!isset($tokens[$xword]))
541                $tokenlength[$wlen][] = $xword;
542            if ($caret || $dollar) {
543                $re = preg_quote($xword, '/');
544                if ($caret) $re = '^'.$re;
545                if ($dollar) $re = $re.'$';
546                $tokens[$xword][] = array($word, '/'.$re.'/');
547                if (!isset($tokenwild[$xword]))
548                    $tokenwild[$xword] = $wlen;
549            } else {
550                $tokens[$xword][] = array($word, null);
551            }
552        }
553        asort($tokenwild);
554        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
555        // $tokenlength = array( base word length => base word ... )
556        // $tokenwild = array( base word => base word length ... )
557        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
558        $indexes_known = $this->_indexLengths($length_filter);
559        if (!empty($tokenwild)) sort($indexes_known);
560        // get word IDs
561        $wids = array();
562        foreach ($indexes_known as $ixlen) {
563            $word_idx = $this->_getIndex('w', $ixlen);
564            // handle exact search
565            if (isset($tokenlength[$ixlen])) {
566                foreach ($tokenlength[$ixlen] as $xword) {
567                    $wid = array_search($xword, $word_idx);
568                    if ($wid !== false) {
569                        $wids[$ixlen][] = $wid;
570                        foreach ($tokens[$xword] as $w)
571                            $result[$w[0]][] = "$ixlen*$wid";
572                    }
573                }
574            }
575            // handle wildcard search
576            foreach ($tokenwild as $xword => $wlen) {
577                if ($wlen >= $ixlen) break;
578                foreach ($tokens[$xword] as $w) {
579                    if (is_null($w[1])) continue;
580                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
581                        $wids[$ixlen][] = $wid;
582                        $result[$w[0]][] = "$ixlen*$wid";
583                    }
584                }
585            }
586        }
587        return $wids;
588    }
589
590    /**
591     * Return a list of all pages
592     *
593     * @param string    $key    list only pages containing the metadata key (optional)
594     * @return array            list of page names
595     * @author Tom N Harris <tnharris@whoopdedo.org>
596     */
597    public function getPages($key=null) {
598        $page_idx = $this->_getIndex('page', '');
599        if (is_null($key)) return $page_idx;
600    }
601
602    /**
603     * Return a list of words sorted by number of times used
604     *
605     * @param int       $min    bottom frequency threshold
606     * @param int       $max    upper frequency limit. No limit if $max<$min
607     * @param string    $key    metadata key to list. Uses the fulltext index if not given
608     * @return array            list of words as the keys and frequency as values
609     * @author Tom N Harris <tnharris@whoopdedo.org>
610     */
611    public function histogram($min=1, $max=0, $key=null) {
612    }
613
614    /**
615     * Lock the indexer.
616     *
617     * @author Tom N Harris <tnharris@whoopdedo.org>
618     */
619    private function _lock() {
620        global $conf;
621        $status = true;
622        $lock = $conf['lockdir'].'/_indexer.lock';
623        while (!@mkdir($lock, $conf['dmode'])) {
624            usleep(50);
625            if (time() - @filemtime($lock) > 60*5) {
626                // looks like a stale lock, remove it
627                @rmdir($lock);
628                $status = "stale lock removed";
629            } else {
630                return false;
631            }
632        }
633        if ($conf['dperm'])
634            chmod($lock, $conf['dperm']);
635        return $status;
636    }
637
638    /**
639     * Release the indexer lock.
640     *
641     * @author Tom N Harris <tnharris@whoopdedo.org>
642     */
643    private function _unlock() {
644        global $conf;
645        @rmdir($conf['lockdir'].'/_indexer.lock');
646        return true;
647    }
648
649    /**
650     * Retrieve the entire index.
651     *
652     * @author Tom N Harris <tnharris@whoopdedo.org>
653     */
654    private function _getIndex($idx, $suffix) {
655        global $conf;
656        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
657        if (!@file_exists($fn)) return array();
658        return file($fn, FILE_IGNORE_NEW_LINES);
659    }
660
661    /**
662     * Replace the contents of the index with an array.
663     *
664     * @author Tom N Harris <tnharris@whoopdedo.org>
665     */
666    private function _saveIndex($idx, $suffix, &$lines) {
667        global $conf;
668        $fn = $conf['indexdir'].'/'.$idx.$suffix;
669        $fh = @fopen($fn.'.tmp', 'w');
670        if (!$fh) return false;
671        fwrite($fh, join("\n", $lines));
672        fclose($fh);
673        if (isset($conf['fperm']))
674            chmod($fn.'.tmp', $conf['fperm']);
675        io_rename($fn.'.tmp', $fn.'.idx');
676        if ($suffix !== '')
677            $this->_cacheIndexDir($idx, $suffix, empty($lines));
678        return true;
679    }
680
681    /**
682     * Retrieve a line from the index.
683     *
684     * @author Tom N Harris <tnharris@whoopdedo.org>
685     */
686    private function _getIndexKey($idx, $suffix, $id) {
687        global $conf;
688        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
689        if (!@file_exists($fn)) return '';
690        $fh = @fopen($fn, 'r');
691        if (!$fh) return '';
692        $ln = -1;
693        while (($line = fgets($fh)) !== false) {
694            if (++$ln == $id) break;
695        }
696        fclose($fh);
697        return rtrim((string)$line);
698    }
699
700    /**
701     * Write a line into the index.
702     *
703     * @author Tom N Harris <tnharris@whoopdedo.org>
704     */
705    private function _saveIndexKey($idx, $suffix, $id, $line) {
706        global $conf;
707        if (substr($line, -1) != "\n")
708            $line .= "\n";
709        $fn = $conf['indexdir'].'/'.$idx.$suffix;
710        $fh = @fopen($fn.'.tmp', 'w');
711        if (!fh) return false;
712        $ih = @fopen($fn.'.idx', 'r');
713        if ($ih) {
714            $ln = -1;
715            while (($curline = fgets($ih)) !== false) {
716                fwrite($fh, (++$ln == $id) ? $line : $curline);
717            }
718            if ($id > $ln) {
719                while ($id > ++$ln)
720                    fwrite($fh, "\n");
721                fwrite($fh, $line);
722            }
723            fclose($ih);
724        } else {
725            $ln = -1;
726            while ($id > ++$ln)
727                fwrite($fh, "\n");
728            fwrite($fh, $line);
729        }
730        fclose($fh);
731        if (isset($conf['fperm']))
732            chmod($fn.'.tmp', $conf['fperm']);
733        io_rename($fn.'.tmp', $fn.'.idx');
734        if ($suffix !== '')
735            $this->_cacheIndexDir($idx, $suffix);
736        return true;
737    }
738
739    /**
740     * Retrieve or insert a value in the index.
741     *
742     * @author Tom N Harris <tnharris@whoopdedo.org>
743     */
744    private function _addIndexKey($idx, $suffix, $value) {
745        $index = $this->_getIndex($idx, $suffix);
746        $id = array_search($value, $index);
747        if ($id === false) {
748            $id = count($index);
749            $index[$id] = $value;
750            if (!$this->_saveIndex($idx, $suffix, $index)) {
751                trigger_error("Failed to write $idx index", E_USER_ERROR);
752                return false;
753            }
754        }
755        return $id;
756    }
757
758    private function _cacheIndexDir($idx, $suffix, $delete=false) {
759        global $conf;
760        if ($idx == 'i')
761            $cachename = $conf['indexdir'].'/lengths';
762        else
763            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
764        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
765        if ($lengths === false) $lengths = array();
766        $old = array_search((string)$suffix, $lengths);
767        if (empty($lines)) {
768            if ($old === false) return;
769            unset($lengths[$old]);
770        } else {
771            if ($old !== false) return;
772            $lengths[] = $suffix;
773            sort($lengths);
774        }
775        $fh = @fopen($cachename.'.tmp', 'w');
776        if (!$fh) {
777            trigger_error("Failed to write index cache", E_USER_ERROR);
778            return;
779        }
780        @fwrite($fh, implode("\n", $lengths));
781        @fclose($fh);
782        if (isset($conf['fperm']))
783            chmod($cachename.'.tmp', $conf['fperm']);
784        io_rename($cachename.'.tmp', $cachename.'.idx');
785    }
786
787    /**
788     * Get the list of lengths indexed in the wiki.
789     *
790     * Read the index directory or a cache file and returns
791     * a sorted array of lengths of the words used in the wiki.
792     *
793     * @author YoBoY <yoboy.leguesh@gmail.com>
794     */
795    private function _listIndexLengths() {
796        global $conf;
797        $cachename = $conf['indexdir'].'/lengths';
798        clearstatcache();
799        if (@file_exists($cachename.'.idx')) {
800            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
801            if ($lengths !== false) {
802                $idx = array();
803                foreach ($lengths as $length)
804                    $idx[] = (int)$length;
805                return $idx;
806            }
807        }
808
809        $dir = @opendir($conf['indexdir']);
810        if ($dir === false)
811            return array();
812        $lengths[] = array();
813        while (($f = readdir($dir)) !== false) {
814            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
815                $i = substr($f, 1, -4);
816                if (is_numeric($i))
817                    $lengths[] = (int)$i;
818            }
819        }
820        closedir($dir);
821        sort($lengths);
822        // save this in a file
823        $fh = @fopen($cachename.'.tmp', 'w');
824        if (!$fh) {
825            trigger_error("Failed to write index cache", E_USER_ERROR);
826            return;
827        }
828        @fwrite($fh, implode("\n", $lengths));
829        @fclose($fh);
830        if (isset($conf['fperm']))
831            chmod($cachename.'.tmp', $conf['fperm']);
832        io_rename($cachename.'.tmp', $cachename.'.idx');
833
834        return $lengths;
835    }
836
837    /**
838     * Get the word lengths that have been indexed.
839     *
840     * Reads the index directory and returns an array of lengths
841     * that there are indices for.
842     *
843     * @author YoBoY <yoboy.leguesh@gmail.com>
844     */
845    private function _indexLengths($filter) {
846        global $conf;
847        $idx = array();
848        if (is_array($filter)) {
849            // testing if index files exist only
850            $path = $conf['indexdir']."/i";
851            foreach ($filter as $key => $value) {
852                if (@file_exists($path.$key.'.idx'))
853                    $idx[] = $key;
854            }
855        } else {
856            $lengths = idx_listIndexLengths();
857            foreach ($lengths as $key => $length) {
858                // keep all the values equal or superior
859                if ((int)$length >= (int)$filter)
860                    $idx[] = $length;
861            }
862        }
863        return $idx;
864    }
865
866    /**
867     * Insert or replace a tuple in a line.
868     *
869     * @author Tom N Harris <tnharris@whoopdedo.org>
870     */
871    private function _updateTuple($line, $id, $count) {
872        $newLine = $line;
873        if ($newLine !== '')
874            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
875        $newLine = trim($newLine, ':');
876        if ($count) {
877            if (strlen($newLine) > 0)
878                return "$id*$count:".$newLine;
879            else
880                return "$id*$count".$newLine;
881        }
882        return $newLine;
883    }
884
885    /**
886     * Split a line into an array of tuples.
887     *
888     * @author Tom N Harris <tnharris@whoopdedo.org>
889     * @author Andreas Gohr <andi@splitbrain.org>
890     */
891    private function _parseTuples(&$keys, $line) {
892        $result = array();
893        if ($line == '') return $result;
894        $parts = explode(':', $line);
895        foreach ($parts as $tuple) {
896            if ($tuple == '') continue;
897            list($key, $cnt) = explode('*', $tuple);
898            if (!$cnt) continue;
899            $key = $keys[$key];
900            if (!$key) continue;
901            $result[$key] = $cnt;
902        }
903        return $result;
904    }
905}
906
907/**
908 * Create an instance of the indexer.
909 *
910 * @return object               a Doku_Indexer
911 * @author Tom N Harris <tnharris@whoopdedo.org>
912 */
913function idx_get_indexer() {
914    static $Indexer = null;
915    if (is_null($Indexer)) {
916        $Indexer = new Doku_Indexer();
917    }
918    return $Indexer;
919}
920
921/**
922 * Returns words that will be ignored.
923 *
924 * @return array                list of stop words
925 * @author Tom N Harris <tnharris@whoopdedo.org>
926 */
927function & idx_get_stopwords() {
928    static $stopwords = null;
929    if (is_null($stopwords)) {
930        global $conf;
931        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
932        if(@file_exists($swfile)){
933            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
934        }else{
935            $stopwords = array();
936        }
937    }
938    return $stopwords;
939}
940
941/**
942 * Adds/updates the search index for the given page
943 *
944 * Locking is handled internally.
945 *
946 * @param string        $page   name of the page to index
947 * @param boolean       $verbose    print status messages
948 * @return boolean              the function completed successfully
949 * @author Tom N Harris <tnharris@whoopdedo.org>
950 */
951function idx_addPage($page, $verbose=false) {
952    // check if indexing needed
953    $idxtag = metaFN($page,'.indexed');
954    if(@file_exists($idxtag)){
955        if(trim(io_readFile($idxtag)) == idx_get_version()){
956            $last = @filemtime($idxtag);
957            if($last > @filemtime(wikiFN($ID))){
958                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
959                return false;
960            }
961        }
962    }
963
964    if (!page_exists($page)) {
965        if (!@file_exists($idxtag)) {
966            if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
967            return false;
968        }
969        $Indexer = idx_get_indexer();
970        $result = $Indexer->deletePage($page);
971        if ($result === "locked") {
972            if ($verbose) print("Indexer: locked".DOKU_LF);
973            return false;
974        }
975        @unlink($idxtag);
976        return $result;
977    }
978    $indexenabled = p_get_metadata($page, 'internal index', false);
979    if ($indexenabled === false) {
980        $result = false;
981        if (@file_exists($idxtag)) {
982            $Indexer = idx_get_indexer();
983            $result = $Indexer->deletePage($page);
984            if ($result === "locked") {
985                if ($verbose) print("Indexer: locked".DOKU_LF);
986                return false;
987            }
988            @unlink($idxtag);
989        }
990        if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
991        return $result;
992    }
993
994    $body = '';
995    $data = array($page, $body);
996    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
997    if ($evt->advise_before()) $data[1] = $data[1] . " " . rawWiki($page);
998    $evt->advise_after();
999    unset($evt);
1000    list($page,$body) = $data;
1001
1002    $Indexer = idx_get_indexer();
1003    $result = $Indexer->addPageWords($page, $body);
1004    if ($result === "locked") {
1005        if ($verbose) print("Indexer: locked".DOKU_LF);
1006        return false;
1007    }
1008
1009    if ($result) {
1010        $data = array('page' => $page, 'metadata' => array());
1011
1012        $data['metadata']['title'] = p_get_metadata($page, 'title', false);
1013        if (($references = p_get_metadata($page, 'relation references', false)) !== null)
1014            $data['metadata']['relation_references'] = array_keys($references);
1015
1016        $evt = new Doku_Event('INDEXER_METADATA_INDEX', $data);
1017        if ($evt->advise_before()) {
1018            $result = $Indexer->addMetaKeys($page, $data['metadata']);
1019            if ($result === "locked") {
1020                if ($verbose) print("Indexer: locked".DOKU_LF);
1021                return false;
1022            }
1023        }
1024        $evt->advise_after();
1025        unset($evt);
1026    }
1027
1028    if ($result)
1029        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
1030    if ($verbose) {
1031        print("Indexer: finished".DOKU_LF);
1032        return true;
1033    }
1034    return $result;
1035}
1036
1037/**
1038 * Find tokens in the fulltext index
1039 *
1040 * Takes an array of words and will return a list of matching
1041 * pages for each one.
1042 *
1043 * Important: No ACL checking is done here! All results are
1044 *            returned, regardless of permissions
1045 *
1046 * @param arrayref      $words  list of words to search for
1047 * @return array                list of pages found, associated with the search terms
1048 */
1049function idx_lookup(&$words) {
1050    $Indexer = idx_get_indexer();
1051    return $Indexer->lookup($words);
1052}
1053
1054/**
1055 * Split a string into tokens
1056 *
1057 */
1058function idx_tokenizer($string, $wc=false) {
1059    $Indexer = idx_get_indexer();
1060    return $Indexer->tokenizer($string, $wc);
1061}
1062
1063/* For compatibility */
1064
1065/**
1066 * Read the list of words in an index (if it exists).
1067 *
1068 * @author Tom N Harris <tnharris@whoopdedo.org>
1069 */
1070function idx_getIndex($idx, $suffix) {
1071    global $conf;
1072    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
1073    if (!@file_exists($fn)) return array();
1074    return file($fn);
1075}
1076
1077/**
1078 * Get the list of lengths indexed in the wiki.
1079 *
1080 * Read the index directory or a cache file and returns
1081 * a sorted array of lengths of the words used in the wiki.
1082 *
1083 * @author YoBoY <yoboy.leguesh@gmail.com>
1084 */
1085function idx_listIndexLengths() {
1086    global $conf;
1087    // testing what we have to do, create a cache file or not.
1088    if ($conf['readdircache'] == 0) {
1089        $docache = false;
1090    } else {
1091        clearstatcache();
1092        if (@file_exists($conf['indexdir'].'/lengths.idx')
1093        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
1094            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
1095                $idx = array();
1096                foreach ($lengths as $length) {
1097                    $idx[] = (int)$length;
1098                }
1099                return $idx;
1100            }
1101        }
1102        $docache = true;
1103    }
1104
1105    if ($conf['readdircache'] == 0 || $docache) {
1106        $dir = @opendir($conf['indexdir']);
1107        if ($dir === false)
1108            return array();
1109        $idx[] = array();
1110        while (($f = readdir($dir)) !== false) {
1111            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
1112                $i = substr($f, 1, -4);
1113                if (is_numeric($i))
1114                    $idx[] = (int)$i;
1115            }
1116        }
1117        closedir($dir);
1118        sort($idx);
1119        // save this in a file
1120        if ($docache) {
1121            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
1122            @fwrite($handle, implode("\n", $idx));
1123            @fclose($handle);
1124        }
1125        return $idx;
1126    }
1127
1128    return array();
1129}
1130
1131/**
1132 * Get the word lengths that have been indexed.
1133 *
1134 * Reads the index directory and returns an array of lengths
1135 * that there are indices for.
1136 *
1137 * @author YoBoY <yoboy.leguesh@gmail.com>
1138 */
1139function idx_indexLengths($filter) {
1140    global $conf;
1141    $idx = array();
1142    if (is_array($filter)) {
1143        // testing if index files exist only
1144        $path = $conf['indexdir']."/i";
1145        foreach ($filter as $key => $value) {
1146            if (@file_exists($path.$key.'.idx'))
1147                $idx[] = $key;
1148        }
1149    } else {
1150        $lengths = idx_listIndexLengths();
1151        foreach ($lengths as $key => $length) {
1152            // keep all the values equal or superior
1153            if ((int)$length >= (int)$filter)
1154                $idx[] = $length;
1155        }
1156    }
1157    return $idx;
1158}
1159
1160/**
1161 * Clean a name of a key for use as a file name.
1162 *
1163 * Romanizes non-latin characters, then strips away anything that's
1164 * not a letter, number, or underscore.
1165 *
1166 * @author Tom N Harris <tnharris@whoopdedo.org>
1167 */
1168function idx_cleanName($name) {
1169    $name = utf8_romanize(trim((string)$name));
1170    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
1171    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
1172    return strtolower($name);
1173}
1174
1175//Setup VIM: ex: et ts=4 :
1176