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