xref: /dokuwiki/inc/indexer.php (revision f078bb0088870b4b68b348d546afa30a80a07e87)
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 if $key is array
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))
475            $value_array = array($value);
476        else
477            $value_array =& $value;
478
479        if (!is_null($func)) {
480            foreach ($value_array as $val) {
481                foreach ($words as $i => $word) {
482                    if (call_user_func_array($func, array($word, $val)))
483                        $value_ids[$i] = $val;
484                }
485            }
486        } else {
487            foreach ($value_array as $val) {
488                $xval = $val;
489                $caret = false;
490                $dollar = false;
491                // check for wildcards
492                if (substr($xval, 0, 1) == '*') {
493                    $xval = substr($xval, 1);
494                    $caret = '^';
495                }
496                if (substr($xval, -1, 1) == '*') {
497                    $xval = substr($xval, 0, -1);
498                    $dollar = '$';
499                }
500                if ($caret || $dollar) {
501                    $re = $caret.preg_quote($xval, '/').$dollar;
502                    foreach(array_keys(preg_grep('/'.$re.'/', $words)) as $i)
503                        $value_ids[$i] = $val;
504                } else {
505                    if (($i = array_search($val, $words)) !== false)
506                        $value_ids[$i] = $val;
507                }
508            }
509        }
510
511        unset($words); // free the used memory
512
513        // load all lines and pages so the used lines can be taken and matched with the pages
514        $lines = $this->_getIndex($metaname, '_i');
515        $page_idx = $this->_getIndex('page', '');
516
517        $result = array();
518        foreach ($value_ids as $value_id => $val) {
519            // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
520            // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
521            $result[$val] = array_keys($this->_parseTuples($page_idx, $lines[$value_id]));
522        }
523        if (!is_array($value)) $result = $result[$value];
524        return $result;
525    }
526
527    /**
528     * Find the index ID of each search term.
529     *
530     * The query terms should only contain valid characters, with a '*' at
531     * either the beginning or end of the word (or both).
532     * The $result parameter can be used to merge the index locations with
533     * the appropriate query term.
534     *
535     * @param arrayref  $words  The query terms.
536     * @param arrayref  $result Set to word => array("length*id" ...)
537     * @return array            Set to length => array(id ...)
538     * @author Tom N Harris <tnharris@whoopdedo.org>
539     */
540    private function _getIndexWords(&$words, &$result) {
541        $tokens = array();
542        $tokenlength = array();
543        $tokenwild = array();
544        foreach ($words as $word) {
545            $result[$word] = array();
546            $caret = false;
547            $dollar = false;
548            $xword = $word;
549            $wlen = wordlen($word);
550
551            // check for wildcards
552            if (substr($xword, 0, 1) == '*') {
553                $xword = substr($xword, 1);
554                $caret = '^';
555                $wlen -= 1;
556            }
557            if (substr($xword, -1, 1) == '*') {
558                $xword = substr($xword, 0, -1);
559                $dollar = '$';
560                $wlen -= 1;
561            }
562            if ($wlen < IDX_MINWORDLENGTH && !$caret && !$dollar && !is_numeric($xword))
563                continue;
564            if (!isset($tokens[$xword]))
565                $tokenlength[$wlen][] = $xword;
566            if ($caret || $dollar) {
567                $re = $caret.preg_quote($xword, '/').$dollar;
568                $tokens[$xword][] = array($word, '/'.$re.'/');
569                if (!isset($tokenwild[$xword]))
570                    $tokenwild[$xword] = $wlen;
571            } else {
572                $tokens[$xword][] = array($word, null);
573            }
574        }
575        asort($tokenwild);
576        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
577        // $tokenlength = array( base word length => base word ... )
578        // $tokenwild = array( base word => base word length ... )
579        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
580        $indexes_known = $this->_indexLengths($length_filter);
581        if (!empty($tokenwild)) sort($indexes_known);
582        // get word IDs
583        $wids = array();
584        foreach ($indexes_known as $ixlen) {
585            $word_idx = $this->_getIndex('w', $ixlen);
586            // handle exact search
587            if (isset($tokenlength[$ixlen])) {
588                foreach ($tokenlength[$ixlen] as $xword) {
589                    $wid = array_search($xword, $word_idx);
590                    if ($wid !== false) {
591                        $wids[$ixlen][] = $wid;
592                        foreach ($tokens[$xword] as $w)
593                            $result[$w[0]][] = "$ixlen*$wid";
594                    }
595                }
596            }
597            // handle wildcard search
598            foreach ($tokenwild as $xword => $wlen) {
599                if ($wlen >= $ixlen) break;
600                foreach ($tokens[$xword] as $w) {
601                    if (is_null($w[1])) continue;
602                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
603                        $wids[$ixlen][] = $wid;
604                        $result[$w[0]][] = "$ixlen*$wid";
605                    }
606                }
607            }
608        }
609        return $wids;
610    }
611
612    /**
613     * Return a list of all pages
614     *
615     * @param string    $key    list only pages containing the metadata key (optional)
616     * @return array            list of page names
617     * @author Tom N Harris <tnharris@whoopdedo.org>
618     */
619    public function getPages($key=null) {
620        $page_idx = $this->_getIndex('page', '');
621        if (is_null($key)) return $page_idx;
622    }
623
624    /**
625     * Return a list of words sorted by number of times used
626     *
627     * @param int       $min    bottom frequency threshold
628     * @param int       $max    upper frequency limit. No limit if $max<$min
629     * @param string    $key    metadata key to list. Uses the fulltext index if not given
630     * @return array            list of words as the keys and frequency as values
631     * @author Tom N Harris <tnharris@whoopdedo.org>
632     */
633    public function histogram($min=1, $max=0, $key=null) {
634    }
635
636    /**
637     * Lock the indexer.
638     *
639     * @author Tom N Harris <tnharris@whoopdedo.org>
640     */
641    private function _lock() {
642        global $conf;
643        $status = true;
644        $lock = $conf['lockdir'].'/_indexer.lock';
645        while (!@mkdir($lock, $conf['dmode'])) {
646            usleep(50);
647            if (time() - @filemtime($lock) > 60*5) {
648                // looks like a stale lock, remove it
649                @rmdir($lock);
650                $status = "stale lock removed";
651            } else {
652                return false;
653            }
654        }
655        if ($conf['dperm'])
656            chmod($lock, $conf['dperm']);
657        return $status;
658    }
659
660    /**
661     * Release the indexer lock.
662     *
663     * @author Tom N Harris <tnharris@whoopdedo.org>
664     */
665    private function _unlock() {
666        global $conf;
667        @rmdir($conf['lockdir'].'/_indexer.lock');
668        return true;
669    }
670
671    /**
672     * Retrieve the entire index.
673     *
674     * @author Tom N Harris <tnharris@whoopdedo.org>
675     */
676    private function _getIndex($idx, $suffix) {
677        global $conf;
678        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
679        if (!@file_exists($fn)) return array();
680        return file($fn, FILE_IGNORE_NEW_LINES);
681    }
682
683    /**
684     * Replace the contents of the index with an array.
685     *
686     * @author Tom N Harris <tnharris@whoopdedo.org>
687     */
688    private function _saveIndex($idx, $suffix, &$lines) {
689        global $conf;
690        $fn = $conf['indexdir'].'/'.$idx.$suffix;
691        $fh = @fopen($fn.'.tmp', 'w');
692        if (!$fh) return false;
693        fwrite($fh, join("\n", $lines));
694        fclose($fh);
695        if (isset($conf['fperm']))
696            chmod($fn.'.tmp', $conf['fperm']);
697        io_rename($fn.'.tmp', $fn.'.idx');
698        if ($suffix !== '')
699            $this->_cacheIndexDir($idx, $suffix, empty($lines));
700        return true;
701    }
702
703    /**
704     * Retrieve a line from the index.
705     *
706     * @author Tom N Harris <tnharris@whoopdedo.org>
707     */
708    private function _getIndexKey($idx, $suffix, $id) {
709        global $conf;
710        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
711        if (!@file_exists($fn)) return '';
712        $fh = @fopen($fn, 'r');
713        if (!$fh) return '';
714        $ln = -1;
715        while (($line = fgets($fh)) !== false) {
716            if (++$ln == $id) break;
717        }
718        fclose($fh);
719        return rtrim((string)$line);
720    }
721
722    /**
723     * Write a line into the index.
724     *
725     * @author Tom N Harris <tnharris@whoopdedo.org>
726     */
727    private function _saveIndexKey($idx, $suffix, $id, $line) {
728        global $conf;
729        if (substr($line, -1) != "\n")
730            $line .= "\n";
731        $fn = $conf['indexdir'].'/'.$idx.$suffix;
732        $fh = @fopen($fn.'.tmp', 'w');
733        if (!fh) return false;
734        $ih = @fopen($fn.'.idx', 'r');
735        if ($ih) {
736            $ln = -1;
737            while (($curline = fgets($ih)) !== false) {
738                fwrite($fh, (++$ln == $id) ? $line : $curline);
739            }
740            if ($id > $ln) {
741                while ($id > ++$ln)
742                    fwrite($fh, "\n");
743                fwrite($fh, $line);
744            }
745            fclose($ih);
746        } else {
747            $ln = -1;
748            while ($id > ++$ln)
749                fwrite($fh, "\n");
750            fwrite($fh, $line);
751        }
752        fclose($fh);
753        if (isset($conf['fperm']))
754            chmod($fn.'.tmp', $conf['fperm']);
755        io_rename($fn.'.tmp', $fn.'.idx');
756        if ($suffix !== '')
757            $this->_cacheIndexDir($idx, $suffix);
758        return true;
759    }
760
761    /**
762     * Retrieve or insert a value in the index.
763     *
764     * @author Tom N Harris <tnharris@whoopdedo.org>
765     */
766    private function _addIndexKey($idx, $suffix, $value) {
767        $index = $this->_getIndex($idx, $suffix);
768        $id = array_search($value, $index);
769        if ($id === false) {
770            $id = count($index);
771            $index[$id] = $value;
772            if (!$this->_saveIndex($idx, $suffix, $index)) {
773                trigger_error("Failed to write $idx index", E_USER_ERROR);
774                return false;
775            }
776        }
777        return $id;
778    }
779
780    private function _cacheIndexDir($idx, $suffix, $delete=false) {
781        global $conf;
782        if ($idx == 'i')
783            $cachename = $conf['indexdir'].'/lengths';
784        else
785            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
786        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
787        if ($lengths === false) $lengths = array();
788        $old = array_search((string)$suffix, $lengths);
789        if (empty($lines)) {
790            if ($old === false) return;
791            unset($lengths[$old]);
792        } else {
793            if ($old !== false) return;
794            $lengths[] = $suffix;
795            sort($lengths);
796        }
797        $fh = @fopen($cachename.'.tmp', 'w');
798        if (!$fh) {
799            trigger_error("Failed to write index cache", E_USER_ERROR);
800            return;
801        }
802        @fwrite($fh, implode("\n", $lengths));
803        @fclose($fh);
804        if (isset($conf['fperm']))
805            chmod($cachename.'.tmp', $conf['fperm']);
806        io_rename($cachename.'.tmp', $cachename.'.idx');
807    }
808
809    /**
810     * Get the list of lengths indexed in the wiki.
811     *
812     * Read the index directory or a cache file and returns
813     * a sorted array of lengths of the words used in the wiki.
814     *
815     * @author YoBoY <yoboy.leguesh@gmail.com>
816     */
817    private function _listIndexLengths() {
818        global $conf;
819        $cachename = $conf['indexdir'].'/lengths';
820        clearstatcache();
821        if (@file_exists($cachename.'.idx')) {
822            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
823            if ($lengths !== false) {
824                $idx = array();
825                foreach ($lengths as $length)
826                    $idx[] = (int)$length;
827                return $idx;
828            }
829        }
830
831        $dir = @opendir($conf['indexdir']);
832        if ($dir === false)
833            return array();
834        $lengths[] = array();
835        while (($f = readdir($dir)) !== false) {
836            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
837                $i = substr($f, 1, -4);
838                if (is_numeric($i))
839                    $lengths[] = (int)$i;
840            }
841        }
842        closedir($dir);
843        sort($lengths);
844        // save this in a file
845        $fh = @fopen($cachename.'.tmp', 'w');
846        if (!$fh) {
847            trigger_error("Failed to write index cache", E_USER_ERROR);
848            return;
849        }
850        @fwrite($fh, implode("\n", $lengths));
851        @fclose($fh);
852        if (isset($conf['fperm']))
853            chmod($cachename.'.tmp', $conf['fperm']);
854        io_rename($cachename.'.tmp', $cachename.'.idx');
855
856        return $lengths;
857    }
858
859    /**
860     * Get the word lengths that have been indexed.
861     *
862     * Reads the index directory and returns an array of lengths
863     * that there are indices for.
864     *
865     * @author YoBoY <yoboy.leguesh@gmail.com>
866     */
867    private function _indexLengths($filter) {
868        global $conf;
869        $idx = array();
870        if (is_array($filter)) {
871            // testing if index files exist only
872            $path = $conf['indexdir']."/i";
873            foreach ($filter as $key => $value) {
874                if (@file_exists($path.$key.'.idx'))
875                    $idx[] = $key;
876            }
877        } else {
878            $lengths = idx_listIndexLengths();
879            foreach ($lengths as $key => $length) {
880                // keep all the values equal or superior
881                if ((int)$length >= (int)$filter)
882                    $idx[] = $length;
883            }
884        }
885        return $idx;
886    }
887
888    /**
889     * Insert or replace a tuple in a line.
890     *
891     * @author Tom N Harris <tnharris@whoopdedo.org>
892     */
893    private function _updateTuple($line, $id, $count) {
894        $newLine = $line;
895        if ($newLine !== '')
896            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
897        $newLine = trim($newLine, ':');
898        if ($count) {
899            if (strlen($newLine) > 0)
900                return "$id*$count:".$newLine;
901            else
902                return "$id*$count".$newLine;
903        }
904        return $newLine;
905    }
906
907    /**
908     * Split a line into an array of tuples.
909     *
910     * @author Tom N Harris <tnharris@whoopdedo.org>
911     * @author Andreas Gohr <andi@splitbrain.org>
912     */
913    private function _parseTuples(&$keys, $line) {
914        $result = array();
915        if ($line == '') return $result;
916        $parts = explode(':', $line);
917        foreach ($parts as $tuple) {
918            if ($tuple == '') continue;
919            list($key, $cnt) = explode('*', $tuple);
920            if (!$cnt) continue;
921            $key = $keys[$key];
922            if (!$key) continue;
923            $result[$key] = $cnt;
924        }
925        return $result;
926    }
927}
928
929/**
930 * Create an instance of the indexer.
931 *
932 * @return object               a Doku_Indexer
933 * @author Tom N Harris <tnharris@whoopdedo.org>
934 */
935function idx_get_indexer() {
936    static $Indexer = null;
937    if (is_null($Indexer)) {
938        $Indexer = new Doku_Indexer();
939    }
940    return $Indexer;
941}
942
943/**
944 * Returns words that will be ignored.
945 *
946 * @return array                list of stop words
947 * @author Tom N Harris <tnharris@whoopdedo.org>
948 */
949function & idx_get_stopwords() {
950    static $stopwords = null;
951    if (is_null($stopwords)) {
952        global $conf;
953        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
954        if(@file_exists($swfile)){
955            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
956        }else{
957            $stopwords = array();
958        }
959    }
960    return $stopwords;
961}
962
963/**
964 * Adds/updates the search index for the given page
965 *
966 * Locking is handled internally.
967 *
968 * @param string        $page   name of the page to index
969 * @param boolean       $verbose    print status messages
970 * @return boolean              the function completed successfully
971 * @author Tom N Harris <tnharris@whoopdedo.org>
972 */
973function idx_addPage($page, $verbose=false) {
974    // check if indexing needed
975    $idxtag = metaFN($page,'.indexed');
976    if(@file_exists($idxtag)){
977        if(trim(io_readFile($idxtag)) == idx_get_version()){
978            $last = @filemtime($idxtag);
979            if($last > @filemtime(wikiFN($ID))){
980                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
981                return false;
982            }
983        }
984    }
985
986    if (!page_exists($page)) {
987        if (!@file_exists($idxtag)) {
988            if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
989            return false;
990        }
991        $Indexer = idx_get_indexer();
992        $result = $Indexer->deletePage($page);
993        if ($result === "locked") {
994            if ($verbose) print("Indexer: locked".DOKU_LF);
995            return false;
996        }
997        @unlink($idxtag);
998        return $result;
999    }
1000    $indexenabled = p_get_metadata($page, 'internal index', false);
1001    if ($indexenabled === false) {
1002        $result = false;
1003        if (@file_exists($idxtag)) {
1004            $Indexer = idx_get_indexer();
1005            $result = $Indexer->deletePage($page);
1006            if ($result === "locked") {
1007                if ($verbose) print("Indexer: locked".DOKU_LF);
1008                return false;
1009            }
1010            @unlink($idxtag);
1011        }
1012        if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
1013        return $result;
1014    }
1015
1016    $body = '';
1017    $data = array($page, $body);
1018    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
1019    if ($evt->advise_before()) $data[1] = $data[1] . " " . rawWiki($page);
1020    $evt->advise_after();
1021    unset($evt);
1022    list($page,$body) = $data;
1023
1024    $Indexer = idx_get_indexer();
1025    $result = $Indexer->addPageWords($page, $body);
1026    if ($result === "locked") {
1027        if ($verbose) print("Indexer: locked".DOKU_LF);
1028        return false;
1029    }
1030
1031    if ($result) {
1032        $data = array('page' => $page, 'metadata' => array());
1033
1034        $data['metadata']['title'] = p_get_metadata($page, 'title', false);
1035        if (($references = p_get_metadata($page, 'relation references', false)) !== null)
1036            $data['metadata']['relation_references'] = array_keys($references);
1037
1038        $evt = new Doku_Event('INDEXER_METADATA_INDEX', $data);
1039        if ($evt->advise_before()) {
1040            $result = $Indexer->addMetaKeys($page, $data['metadata']);
1041            if ($result === "locked") {
1042                if ($verbose) print("Indexer: locked".DOKU_LF);
1043                return false;
1044            }
1045        }
1046        $evt->advise_after();
1047        unset($evt);
1048    }
1049
1050    if ($result)
1051        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
1052    if ($verbose) {
1053        print("Indexer: finished".DOKU_LF);
1054        return true;
1055    }
1056    return $result;
1057}
1058
1059/**
1060 * Find tokens in the fulltext index
1061 *
1062 * Takes an array of words and will return a list of matching
1063 * pages for each one.
1064 *
1065 * Important: No ACL checking is done here! All results are
1066 *            returned, regardless of permissions
1067 *
1068 * @param arrayref      $words  list of words to search for
1069 * @return array                list of pages found, associated with the search terms
1070 */
1071function idx_lookup(&$words) {
1072    $Indexer = idx_get_indexer();
1073    return $Indexer->lookup($words);
1074}
1075
1076/**
1077 * Split a string into tokens
1078 *
1079 */
1080function idx_tokenizer($string, $wc=false) {
1081    $Indexer = idx_get_indexer();
1082    return $Indexer->tokenizer($string, $wc);
1083}
1084
1085/* For compatibility */
1086
1087/**
1088 * Read the list of words in an index (if it exists).
1089 *
1090 * @author Tom N Harris <tnharris@whoopdedo.org>
1091 */
1092function idx_getIndex($idx, $suffix) {
1093    global $conf;
1094    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
1095    if (!@file_exists($fn)) return array();
1096    return file($fn);
1097}
1098
1099/**
1100 * Get the list of lengths indexed in the wiki.
1101 *
1102 * Read the index directory or a cache file and returns
1103 * a sorted array of lengths of the words used in the wiki.
1104 *
1105 * @author YoBoY <yoboy.leguesh@gmail.com>
1106 */
1107function idx_listIndexLengths() {
1108    global $conf;
1109    // testing what we have to do, create a cache file or not.
1110    if ($conf['readdircache'] == 0) {
1111        $docache = false;
1112    } else {
1113        clearstatcache();
1114        if (@file_exists($conf['indexdir'].'/lengths.idx')
1115        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
1116            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
1117                $idx = array();
1118                foreach ($lengths as $length) {
1119                    $idx[] = (int)$length;
1120                }
1121                return $idx;
1122            }
1123        }
1124        $docache = true;
1125    }
1126
1127    if ($conf['readdircache'] == 0 || $docache) {
1128        $dir = @opendir($conf['indexdir']);
1129        if ($dir === false)
1130            return array();
1131        $idx[] = array();
1132        while (($f = readdir($dir)) !== false) {
1133            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
1134                $i = substr($f, 1, -4);
1135                if (is_numeric($i))
1136                    $idx[] = (int)$i;
1137            }
1138        }
1139        closedir($dir);
1140        sort($idx);
1141        // save this in a file
1142        if ($docache) {
1143            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
1144            @fwrite($handle, implode("\n", $idx));
1145            @fclose($handle);
1146        }
1147        return $idx;
1148    }
1149
1150    return array();
1151}
1152
1153/**
1154 * Get the word lengths that have been indexed.
1155 *
1156 * Reads the index directory and returns an array of lengths
1157 * that there are indices for.
1158 *
1159 * @author YoBoY <yoboy.leguesh@gmail.com>
1160 */
1161function idx_indexLengths($filter) {
1162    global $conf;
1163    $idx = array();
1164    if (is_array($filter)) {
1165        // testing if index files exist only
1166        $path = $conf['indexdir']."/i";
1167        foreach ($filter as $key => $value) {
1168            if (@file_exists($path.$key.'.idx'))
1169                $idx[] = $key;
1170        }
1171    } else {
1172        $lengths = idx_listIndexLengths();
1173        foreach ($lengths as $key => $length) {
1174            // keep all the values equal or superior
1175            if ((int)$length >= (int)$filter)
1176                $idx[] = $length;
1177        }
1178    }
1179    return $idx;
1180}
1181
1182/**
1183 * Clean a name of a key for use as a file name.
1184 *
1185 * Romanizes non-latin characters, then strips away anything that's
1186 * not a letter, number, or underscore.
1187 *
1188 * @author Tom N Harris <tnharris@whoopdedo.org>
1189 */
1190function idx_cleanName($name) {
1191    $name = utf8_romanize(trim((string)$name));
1192    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
1193    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
1194    return strtolower($name);
1195}
1196
1197//Setup VIM: ex: et ts=4 :
1198