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