xref: /dokuwiki/inc/indexer.php (revision d64516f5d992bb47a765949743506d8433a07d55)
1b4ce25e9SAndreas Gohr<?php
2b4ce25e9SAndreas Gohr/**
3fcd3bb7cSAndreas Gohr * Functions to create the fulltext search index
4b4ce25e9SAndreas Gohr *
5b4ce25e9SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6b4ce25e9SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
700803e56STom N Harris * @author     Tom N Harris <tnharris@whoopdedo.org>
8b4ce25e9SAndreas Gohr */
9b4ce25e9SAndreas Gohr
10fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
11b4ce25e9SAndreas Gohr
127c2ef4e8STom N Harris// Version tag used to force rebuild on upgrade
1300803e56STom N Harrisdefine('INDEXER_VERSION', 3);
147c2ef4e8STom N Harris
1533815ce2SChris Smith// set the minimum token length to use in the index (note, this doesn't apply to numeric tokens)
16d3fb3219SAndreas Gohrif (!defined('IDX_MINWORDLENGTH')) define('IDX_MINWORDLENGTH',2);
1733815ce2SChris Smith
1893a60ad2SAndreas Gohr// Asian characters are handled as words. The following regexp defines the
1993a60ad2SAndreas Gohr// Unicode-Ranges for Asian characters
2093a60ad2SAndreas Gohr// Ranges taken from http://en.wikipedia.org/wiki/Unicode_block
2193a60ad2SAndreas Gohr// I'm no language expert. If you think some ranges are wrongly chosen or
2293a60ad2SAndreas Gohr// a range is missing, please contact me
23d5b23302STom N Harrisdefine('IDX_ASIAN1','[\x{0E00}-\x{0E7F}]'); // Thai
24d5b23302STom N Harrisdefine('IDX_ASIAN2','['.
25d5b23302STom N Harris                   '\x{2E80}-\x{3040}'.  // CJK -> Hangul
26d5b23302STom N Harris                   '\x{309D}-\x{30A0}'.
27a0c5c349STom N Harris                   '\x{30FD}-\x{31EF}\x{3200}-\x{D7AF}'.
2893a60ad2SAndreas Gohr                   '\x{F900}-\x{FAFF}'.  // CJK Compatibility Ideographs
2993a60ad2SAndreas Gohr                   '\x{FE30}-\x{FE4F}'.  // CJK Compatibility Forms
3093a60ad2SAndreas Gohr                   ']');
31d5b23302STom N Harrisdefine('IDX_ASIAN3','['.                // Hiragana/Katakana (can be two characters)
32d5b23302STom N Harris                   '\x{3042}\x{3044}\x{3046}\x{3048}'.
33d5b23302STom N Harris                   '\x{304A}-\x{3062}\x{3064}-\x{3082}'.
34d5b23302STom N Harris                   '\x{3084}\x{3086}\x{3088}-\x{308D}'.
35d5b23302STom N Harris                   '\x{308F}-\x{3094}'.
36d5b23302STom N Harris                   '\x{30A2}\x{30A4}\x{30A6}\x{30A8}'.
37d5b23302STom N Harris                   '\x{30AA}-\x{30C2}\x{30C4}-\x{30E2}'.
38d5b23302STom N Harris                   '\x{30E4}\x{30E6}\x{30E8}-\x{30ED}'.
39d5b23302STom N Harris                   '\x{30EF}-\x{30F4}\x{30F7}-\x{30FA}'.
40d5b23302STom N Harris                   ']['.
41d5b23302STom N Harris                   '\x{3041}\x{3043}\x{3045}\x{3047}\x{3049}'.
42d5b23302STom N Harris                   '\x{3063}\x{3083}\x{3085}\x{3087}\x{308E}\x{3095}-\x{309C}'.
43d5b23302STom N Harris                   '\x{30A1}\x{30A3}\x{30A5}\x{30A7}\x{30A9}'.
44d5b23302STom N Harris                   '\x{30C3}\x{30E3}\x{30E5}\x{30E7}\x{30EE}\x{30F5}\x{30F6}\x{30FB}\x{30FC}'.
45d5b23302STom N Harris                   '\x{31F0}-\x{31FF}'.
46d5b23302STom N Harris                   ']?');
47699b8a0bSAndreas Gohrdefine('IDX_ASIAN', '(?:'.IDX_ASIAN1.'|'.IDX_ASIAN2.'|'.IDX_ASIAN3.')');
4893a60ad2SAndreas Gohr
49b4ce25e9SAndreas Gohr/**
507c2ef4e8STom N Harris * Version of the indexer taking into consideration the external tokenizer.
517c2ef4e8STom N Harris * The indexer is only compatible with data written by the same version.
527c2ef4e8STom N Harris *
537c2ef4e8STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
547c2ef4e8STom N Harris */
557c2ef4e8STom N Harrisfunction idx_get_version(){
567c2ef4e8STom N Harris    global $conf;
577c2ef4e8STom N Harris    if($conf['external_tokenizer'])
587c2ef4e8STom N Harris        return INDEXER_VERSION . '+' . trim($conf['tokenizer_cmd']);
597c2ef4e8STom N Harris    else
607c2ef4e8STom N Harris        return INDEXER_VERSION;
617c2ef4e8STom N Harris}
627c2ef4e8STom N Harris
637c2ef4e8STom N Harris/**
64d5b23302STom N Harris * Measure the length of a string.
65d5b23302STom N Harris * Differs from strlen in handling of asian characters.
66d5b23302STom N Harris *
67d5b23302STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
68d5b23302STom N Harris */
69d5b23302STom N Harrisfunction wordlen($w){
70d5b23302STom N Harris    $l = strlen($w);
71d5b23302STom N Harris    // If left alone, all chinese "words" will get put into w3.idx
72d5b23302STom N Harris    // So the "length" of a "word" is faked
734b9792c6STom N Harris    if(preg_match_all('/[\xE2-\xEF]/',$w,$leadbytes)) {
744b9792c6STom N Harris        foreach($leadbytes[0] as $b)
754b9792c6STom N Harris            $l += ord($b) - 0xE1;
764b9792c6STom N Harris    }
77d5b23302STom N Harris    return $l;
78d5b23302STom N Harris}
79d5b23302STom N Harris
80d5b23302STom N Harris/**
8100803e56STom N Harris * Class that encapsulates operations on the indexer database.
82579b0f7eSTNHarris *
83579b0f7eSTNHarris * @author Tom N Harris <tnharris@whoopdedo.org>
84579b0f7eSTNHarris */
8500803e56STom N Harrisclass Doku_Indexer {
86579b0f7eSTNHarris
87579b0f7eSTNHarris    /**
8800803e56STom N Harris     * Adds the contents of a page to the fulltext index
89dd35e9c9SAndreas Gohr     *
9000803e56STom N Harris     * The added text replaces previous words for the same page.
9100803e56STom N Harris     * An empty value erases the page.
9200803e56STom N Harris     *
9300803e56STom N Harris     * @param string    $page   a page name
9400803e56STom N Harris     * @param string    $text   the body of the page
9500803e56STom N Harris     * @return boolean          the function completed successfully
9600803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
97dd35e9c9SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
98dd35e9c9SAndreas Gohr     */
9900803e56STom N Harris    public function addPageWords($page, $text) {
1009b41be24STom N Harris        if (!$this->_lock())
1019b41be24STom N Harris            return "locked";
10200803e56STom N Harris
10300803e56STom N Harris        // load known documents
10400803e56STom N Harris        $page_idx = $this->_addIndexKey('page', '', $page);
10500803e56STom N Harris        if ($page_idx === false) {
10600803e56STom N Harris            $this->_unlock();
10700803e56STom N Harris            return false;
10800803e56STom N Harris        }
10900803e56STom N Harris
11000803e56STom N Harris        $pagewords = array();
11100803e56STom N Harris        // get word usage in page
11200803e56STom N Harris        $words = $this->_getPageWords($text);
11300803e56STom N Harris        if ($words === false) {
11400803e56STom N Harris            $this->_unlock();
11500803e56STom N Harris            return false;
11600803e56STom N Harris        }
11700803e56STom N Harris
11800803e56STom N Harris        if (!empty($words)) {
11900803e56STom N Harris            foreach (array_keys($words) as $wlen) {
12000803e56STom N Harris                $index = $this->_getIndex('i', $wlen);
12100803e56STom N Harris                foreach ($words[$wlen] as $wid => $freq) {
12200803e56STom N Harris                    $idx = ($wid<count($index)) ? $index[$wid] : '';
12300803e56STom N Harris                    $index[$wid] = $this->_updateTuple($idx, $pid, $freq);
12400803e56STom N Harris                    $pagewords[] = "$wlen*$wid";
12500803e56STom N Harris                }
12600803e56STom N Harris                if (!$this->_saveIndex('i', $wlen, $index)) {
12700803e56STom N Harris                    $this->_unlock();
12800803e56STom N Harris                    return false;
12900803e56STom N Harris                }
13000803e56STom N Harris            }
13100803e56STom N Harris        }
13200803e56STom N Harris
13300803e56STom N Harris        // Remove obsolete index entries
13400803e56STom N Harris        $pageword_idx = $this->_getIndexKey('pageword', '', $pid);
13500803e56STom N Harris        if ($pageword_idx !== '') {
13600803e56STom N Harris            $oldwords = explode(':',$pageword_idx);
13700803e56STom N Harris            $delwords = array_diff($oldwords, $pagewords);
13800803e56STom N Harris            $upwords = array();
13900803e56STom N Harris            foreach ($delwords as $word) {
14000803e56STom N Harris                if ($word != '') {
14100803e56STom N Harris                    list($wlen,$wid) = explode('*', $word);
14200803e56STom N Harris                    $wid = (int)$wid;
14300803e56STom N Harris                    $upwords[$wlen][] = $wid;
14400803e56STom N Harris                }
14500803e56STom N Harris            }
14600803e56STom N Harris            foreach ($upwords as $wlen => $widx) {
14700803e56STom N Harris                $index = $this->_getIndex('i', $wlen);
14800803e56STom N Harris                foreach ($widx as $wid) {
14900803e56STom N Harris                    $index[$wid] = $this->_updateTuple($index[$wid], $pid, 0);
15000803e56STom N Harris                }
15100803e56STom N Harris                $this->_saveIndex('i', $wlen, $index);
15200803e56STom N Harris            }
15300803e56STom N Harris        }
15400803e56STom N Harris        // Save the reverse index
15500803e56STom N Harris        $pageword_idx = join(':', $pagewords);
15600803e56STom N Harris        if (!$this->_saveIndexKey('pageword', '', $pid, $pageword_idx)) {
15700803e56STom N Harris            $this->_unlock();
15800803e56STom N Harris            return false;
15900803e56STom N Harris        }
16000803e56STom N Harris
16100803e56STom N Harris        $this->_unlock();
162dd35e9c9SAndreas Gohr        return true;
163dd35e9c9SAndreas Gohr    }
164dd35e9c9SAndreas Gohr
165dd35e9c9SAndreas Gohr    /**
16600803e56STom N Harris     * Split the words in a page and add them to the index.
16744ca0adfSAndreas Gohr     *
16844ca0adfSAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
16917f42b01SChris Smith     * @author Christopher Smith <chris@jalakai.co.uk>
17000803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
171b4ce25e9SAndreas Gohr     */
17200803e56STom N Harris    private function _getPageWords($text) {
17344ca0adfSAndreas Gohr        global $conf;
17444ca0adfSAndreas Gohr
17500803e56STom N Harris        $tokens = $this->tokenizer($text);
17617f42b01SChris Smith        $tokens = array_count_values($tokens);  // count the frequency of each token
17717f42b01SChris Smith
17817f42b01SChris Smith        $words = array();
1794e1bf408STom N Harris        foreach ($tokens as $w=>$c) {
180d5b23302STom N Harris            $l = wordlen($w);
181579b0f7eSTNHarris            if (isset($words[$l])){
1824e1bf408STom N Harris                $words[$l][$w] = $c + (isset($words[$l][$w]) ? $words[$l][$w] : 0);
18317f42b01SChris Smith            }else{
1844e1bf408STom N Harris                $words[$l] = array($w => $c);
18517f42b01SChris Smith            }
18617f42b01SChris Smith        }
18717f42b01SChris Smith
188579b0f7eSTNHarris        // arrive here with $words = array(wordlen => array(word => frequency))
189e5e50383SMichael Hamann        $word_idx_modified = false;
190b4ce25e9SAndreas Gohr        $index = array();   //resulting index
191579b0f7eSTNHarris        foreach (array_keys($words) as $wlen) {
19200803e56STom N Harris            $word_idx = $this->_getIndex('w', $wlen);
193579b0f7eSTNHarris            foreach ($words[$wlen] as $word => $freq) {
19400803e56STom N Harris                $wid = array_search($word, $word_idx);
19500803e56STom N Harris                if ($wid === false) {
196d5b23302STom N Harris                    $wid = count($word_idx);
19700803e56STom N Harris                    $word_idx[] = $word;
198e5e50383SMichael Hamann                    $word_idx_modified = true;
199b4ce25e9SAndreas Gohr                }
200579b0f7eSTNHarris                if (!isset($index[$wlen]))
201579b0f7eSTNHarris                    $index[$wlen] = array();
202579b0f7eSTNHarris                $index[$wlen][$wid] = $freq;
20344ca0adfSAndreas Gohr            }
20400803e56STom N Harris            // save back the word index
20500803e56STom N Harris            if ($word_idx_modified && !$this->_saveIndex('w', $wlen, $word_idx))
20644ca0adfSAndreas Gohr                return false;
20744ca0adfSAndreas Gohr        }
208b4ce25e9SAndreas Gohr
209b4ce25e9SAndreas Gohr        return $index;
210b4ce25e9SAndreas Gohr    }
211b4ce25e9SAndreas Gohr
21244ca0adfSAndreas Gohr    /**
21300803e56STom N Harris     * Add keys to the metadata index.
21444ca0adfSAndreas Gohr     *
21500803e56STom N Harris     * Adding new keys does not remove other keys for the page.
21600803e56STom N Harris     * An empty value will erase the key.
21700803e56STom N Harris     * The $key parameter can be an array to add multiple keys. $value will
21800803e56STom N Harris     * not be used if $key is an array.
21944ca0adfSAndreas Gohr     *
22000803e56STom N Harris     * @param string    $page   a page name
22100803e56STom N Harris     * @param mixed     $key    a key string or array of key=>value pairs
22200803e56STom N Harris     * @param mixed     $value  the value or list of values
22300803e56STom N Harris     * @return boolean          the function completed successfully
22400803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
22544ca0adfSAndreas Gohr     */
22600803e56STom N Harris    public function addMetaKeys($page, $key, $value=null) {
22700803e56STom N Harris        if (!is_array($key)) {
22800803e56STom N Harris            $key = array($key => $value);
22900803e56STom N Harris        } elseif (!is_null($value)) {
23000803e56STom N Harris            // $key is array, but $value is not null
23100803e56STom N Harris            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
23200803e56STom N Harris        }
23300803e56STom N Harris
23400803e56STom N Harris        $this->_lock();
235b4ce25e9SAndreas Gohr
236488dd6ceSAndreas Gohr        // load known documents
23700803e56STom N Harris        $pid = $this->_addIndexKey('page', '', $page);
23800803e56STom N Harris        if ($pid === false) {
23900803e56STom N Harris            $this->_unlock();
240579b0f7eSTNHarris            return false;
24144ca0adfSAndreas Gohr        }
24200803e56STom N Harris
24300803e56STom N Harris        foreach ($key as $name => $values) {
24400803e56STom N Harris            $metaname = idx_cleanName($name);
24500803e56STom N Harris            $metaidx = $this->_getIndex($metaname, '_i');
24600803e56STom N Harris            $metawords = $this->_getIndex($metaname, '_w');
24700803e56STom N Harris            $addwords = false;
24800803e56STom N Harris            $update = array();
24900803e56STom N Harris            if (!is_array($val)) $values = array($values);
25000803e56STom N Harris            foreach ($values as $val) {
25100803e56STom N Harris                $val = (string)$val;
25200803e56STom N Harris                if ($val !== "") {
25300803e56STom N Harris                    $id = array_search($val, $metawords);
25400803e56STom N Harris                    if ($id === false) {
25500803e56STom N Harris                        $id = count($metawords);
25600803e56STom N Harris                        $metawords[$id] = $val;
25700803e56STom N Harris                        $addwords = true;
258d5b23302STom N Harris                    }
25900803e56STom N Harris                    $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 1);
26000803e56STom N Harris                    $update[$id] = 1;
261d5b23302STom N Harris                } else {
26200803e56STom N Harris                    $id = array_search($val, $metawords);
26300803e56STom N Harris                    if ($id !== false) {
26400803e56STom N Harris                        $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 0);
26500803e56STom N Harris                        $update[$id] = 0;
26644ca0adfSAndreas Gohr                    }
267579b0f7eSTNHarris                }
268a0c5c349STom N Harris            }
26900803e56STom N Harris            if (!empty($update)) {
27000803e56STom N Harris                if ($addwords)
27100803e56STom N Harris                    $this->_saveIndex($metaname.'_w', '', $metawords);
27200803e56STom N Harris                $this->_saveIndex($metaname.'_i', '', $metaidx);
27300803e56STom N Harris                $val_idx = $this->_getIndexKey($metaname, '_p', $pid);
27400803e56STom N Harris                $val_idx = array_flip(explode(':', $val_idx));
27500803e56STom N Harris                foreach ($update as $id => $add) {
27600803e56STom N Harris                    if ($add) $val_idx[$id] = 1;
27700803e56STom N Harris                    else unset($val_idx[$id]);
278b6344591STom N Harris                }
27900803e56STom N Harris                $val_idx = array_keys($val_idx);
280*d64516f5SMichael Hamann                $this->_saveIndexKey($metaname.'_p', '', $pid, implode(':', $val_idx));
281b6344591STom N Harris            }
28200803e56STom N Harris            unset($metaidx);
28300803e56STom N Harris            unset($metawords);
284a0c5c349STom N Harris        }
285579b0f7eSTNHarris        return true;
28644ca0adfSAndreas Gohr    }
28744ca0adfSAndreas Gohr
28844ca0adfSAndreas Gohr    /**
28900803e56STom N Harris     * Remove a page from the index
29044ca0adfSAndreas Gohr     *
29100803e56STom N Harris     * Erases entries in all known indexes.
29244ca0adfSAndreas Gohr     *
29300803e56STom N Harris     * @param string    $page   a page name
29400803e56STom N Harris     * @return boolean          the function completed successfully
29500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
29644ca0adfSAndreas Gohr     */
29700803e56STom N Harris    public function deletePage($page) {
298d5b23302STom N Harris    }
29944ca0adfSAndreas Gohr
300d5b23302STom N Harris    /**
30100803e56STom N Harris     * Split the text into words for fulltext search
302d5b23302STom N Harris     *
30300803e56STom N Harris     * TODO: does this also need &$stopwords ?
304d5b23302STom N Harris     *
30500803e56STom N Harris     * @param string    $text   plain text
30600803e56STom N Harris     * @param boolean   $wc     are wildcards allowed?
30700803e56STom N Harris     * @return array            list of words in the text
308d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
309d5b23302STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
310d5b23302STom N Harris     */
31100803e56STom N Harris    public function tokenizer($text, $wc=false) {
31222952965SYoBoY        global $conf;
31300803e56STom N Harris        $words = array();
31400803e56STom N Harris        $wc = ($wc) ? '' : '\*';
31500803e56STom N Harris        $stopwords =& idx_get_stopwords();
31600803e56STom N Harris
31700803e56STom N Harris        if ($conf['external_tokenizer'] && $conf['tokenizer_cmd'] != '') {
31800803e56STom N Harris            if (0 == io_exec($conf['tokenizer_cmd'], $text, $output))
31900803e56STom N Harris                $text = $output;
32022952965SYoBoY        } else {
32100803e56STom N Harris            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
32200803e56STom N Harris                // handle asian chars as single words (may fail on older PHP version)
32300803e56STom N Harris                $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text);
32400803e56STom N Harris                if (!is_null($asia)) $text = $asia; // recover from regexp falure
32522952965SYoBoY            }
32622952965SYoBoY        }
32700803e56STom N Harris        $text = strtr($text, "\r\n\t", '   ');
32800803e56STom N Harris        if (preg_match('/[^0-9A-Za-z ]/u', $text))
32900803e56STom N Harris            $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
33022952965SYoBoY
33100803e56STom N Harris        $wordlist = explode(' ', $text);
33200803e56STom N Harris        foreach ($wordlist as $word) {
33300803e56STom N Harris            $word = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
33400803e56STom N Harris                utf8_strtolower($word) : strtolower($word);
33500803e56STom N Harris            if (!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) continue;
33600803e56STom N Harris            if (array_search($word, $stopwords) !== false) continue;
33700803e56STom N Harris            $words[] = $word;
33822952965SYoBoY        }
33900803e56STom N Harris        return $words;
34022952965SYoBoY    }
34122952965SYoBoY
34222952965SYoBoY    /**
34300803e56STom N Harris     * Find pages in the fulltext index containing the words,
344579b0f7eSTNHarris     *
34500803e56STom N Harris     * The search words must be pre-tokenized, meaning only letters and
34600803e56STom N Harris     * numbers with an optional wildcard
347579b0f7eSTNHarris     *
34800803e56STom N Harris     * The returned array will have the original tokens as key. The values
34900803e56STom N Harris     * in the returned list is an array with the page names as keys and the
35000803e56STom N Harris     * number of times that token appeas on the page as value.
35100803e56STom N Harris     *
3529b41be24STom N Harris     * @param arrayref  $tokens list of words to search for
35300803e56STom N Harris     * @return array            list of page names with usage counts
35400803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
35500803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
356579b0f7eSTNHarris     */
3579b41be24STom N Harris    public function lookup(&$tokens) {
35800803e56STom N Harris        $result = array();
35900803e56STom N Harris        $wids = $this->_getIndexWords($tokens, $result);
36000803e56STom N Harris        if (empty($wids)) return array();
36100803e56STom N Harris        // load known words and documents
36200803e56STom N Harris        $page_idx = $this->_getIndex('page', '');
36300803e56STom N Harris        $docs = array();
36400803e56STom N Harris        foreach (array_keys($wids) as $wlen) {
36500803e56STom N Harris            $wids[$wlen] = array_unique($wids[$wlen]);
36600803e56STom N Harris            $index = $this->_getIndex('i', $wlen);
36700803e56STom N Harris            foreach($wids[$wlen] as $ixid) {
36800803e56STom N Harris                if ($ixid < count($index))
36900803e56STom N Harris                    $docs["$wlen*$ixid"] = $this->_parseTuples($page_idx, $index[$ixid]);
370d5b23302STom N Harris            }
371d5b23302STom N Harris        }
37200803e56STom N Harris        // merge found pages into final result array
37300803e56STom N Harris        $final = array();
37400803e56STom N Harris        foreach ($result as $word => $res) {
37500803e56STom N Harris            $final[$word] = array();
37600803e56STom N Harris            foreach ($res as $wid) {
37700803e56STom N Harris                $hits = &$docs[$wid];
37800803e56STom N Harris                foreach ($hits as $hitkey => $hitcnt) {
37900803e56STom N Harris                    // make sure the document still exists
38000803e56STom N Harris                    if (!page_exists($hitkey, '', false)) continue;
38100803e56STom N Harris                    if (!isset($final[$word][$hitkey]))
38200803e56STom N Harris                        $final[$word][$hitkey] = $hitcnt;
38300803e56STom N Harris                    else
38400803e56STom N Harris                        $final[$word][$hitkey] += $hitcnt;
385d5b23302STom N Harris                }
386579b0f7eSTNHarris            }
387579b0f7eSTNHarris        }
38800803e56STom N Harris        return $final;
389579b0f7eSTNHarris    }
390579b0f7eSTNHarris
391579b0f7eSTNHarris    /**
39200803e56STom N Harris     * Find pages containing a metadata key.
393d5b23302STom N Harris     *
39400803e56STom N Harris     * The metadata values are compared as case-sensitive strings. Pass a
39500803e56STom N Harris     * callback function that returns true or false to use a different
39600803e56STom N Harris     * comparison function
397d5b23302STom N Harris     *
39800803e56STom N Harris     * @param string    $key    name of the metadata key to look for
39900803e56STom N Harris     * @param string    $value  search term to look for
40000803e56STom N Harris     * @param callback  $func   comparison function
4019b41be24STom N Harris     * @return array            list with page names, keys are query values if more than one given
40200803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
40300803e56STom N Harris     */
40400803e56STom N Harris    public function lookupKey($key, $value, $func=null) {
4059b41be24STom N Harris        return array();
40600803e56STom N Harris    }
40700803e56STom N Harris
40800803e56STom N Harris    /**
40900803e56STom N Harris     * Find the index ID of each search term.
41000803e56STom N Harris     *
41100803e56STom N Harris     * The query terms should only contain valid characters, with a '*' at
41200803e56STom N Harris     * either the beginning or end of the word (or both).
41300803e56STom N Harris     * The $result parameter can be used to merge the index locations with
41400803e56STom N Harris     * the appropriate query term.
41500803e56STom N Harris     *
4169b41be24STom N Harris     * @param arrayref  $words  The query terms.
41700803e56STom N Harris     * @param arrayref  $result Set to word => array("length*id" ...)
418d5b23302STom N Harris     * @return array            Set to length => array(id ...)
419d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
420d5b23302STom N Harris     */
4219b41be24STom N Harris    private function _getIndexWords(&$words, &$result) {
422d5b23302STom N Harris        $tokens = array();
423d5b23302STom N Harris        $tokenlength = array();
424d5b23302STom N Harris        $tokenwild = array();
425d5b23302STom N Harris        foreach ($words as $word) {
426d5b23302STom N Harris            $result[$word] = array();
42700803e56STom N Harris            $caret = false;
42800803e56STom N Harris            $dollar = false;
429d5b23302STom N Harris            $xword = $word;
430d5b23302STom N Harris            $wlen = wordlen($word);
431d5b23302STom N Harris
432d5b23302STom N Harris            // check for wildcards
433d5b23302STom N Harris            if (substr($xword, 0, 1) == '*') {
434d5b23302STom N Harris                $xword = substr($xword, 1);
43500803e56STom N Harris                $caret = true;
436d5b23302STom N Harris                $wlen -= 1;
437d5b23302STom N Harris            }
438d5b23302STom N Harris            if (substr($xword, -1, 1) == '*') {
439d5b23302STom N Harris                $xword = substr($xword, 0, -1);
44000803e56STom N Harris                $dollar = true;
441d5b23302STom N Harris                $wlen -= 1;
442d5b23302STom N Harris            }
44300803e56STom N Harris            if ($wlen < IDX_MINWORDLENGTH && !$caret && !$dollar && !is_numeric($xword))
44400803e56STom N Harris                continue;
44500803e56STom N Harris            if (!isset($tokens[$xword]))
446d5b23302STom N Harris                $tokenlength[$wlen][] = $xword;
44700803e56STom N Harris            if ($caret || $dollar) {
44800803e56STom N Harris                $re = preg_quote($xword, '/');
44900803e56STom N Harris                if ($caret) $re = '^'.$re;
45000803e56STom N Harris                if ($dollar) $re = $re.'$';
45100803e56STom N Harris                $tokens[$xword][] = array($word, '/'.$re.'/');
45200803e56STom N Harris                if (!isset($tokenwild[$xword]))
45300803e56STom N Harris                    $tokenwild[$xword] = $wlen;
45400803e56STom N Harris            } else {
455d5b23302STom N Harris                $tokens[$xword][] = array($word, null);
456d5b23302STom N Harris            }
45700803e56STom N Harris        }
458d5b23302STom N Harris        asort($tokenwild);
45900803e56STom N Harris        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
460d5b23302STom N Harris        // $tokenlength = array( base word length => base word ... )
461d5b23302STom N Harris        // $tokenwild = array( base word => base word length ... )
462d5b23302STom N Harris        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
46300803e56STom N Harris        $indexes_known = $this->_indexLengths($length_filter);
464d5b23302STom N Harris        if (!empty($tokenwild)) sort($indexes_known);
465d5b23302STom N Harris        // get word IDs
466d5b23302STom N Harris        $wids = array();
467d5b23302STom N Harris        foreach ($indexes_known as $ixlen) {
46800803e56STom N Harris            $word_idx = $this->_getIndex('w', $ixlen);
469d5b23302STom N Harris            // handle exact search
470d5b23302STom N Harris            if (isset($tokenlength[$ixlen])) {
471d5b23302STom N Harris                foreach ($tokenlength[$ixlen] as $xword) {
47200803e56STom N Harris                    $wid = array_search($xword, $word_idx);
47300803e56STom N Harris                    if ($wid !== false) {
474d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
475d5b23302STom N Harris                        foreach ($tokens[$xword] as $w)
476d5b23302STom N Harris                            $result[$w[0]][] = "$ixlen*$wid";
477d5b23302STom N Harris                    }
478d5b23302STom N Harris                }
479d5b23302STom N Harris            }
480d5b23302STom N Harris            // handle wildcard search
481d5b23302STom N Harris            foreach ($tokenwild as $xword => $wlen) {
482d5b23302STom N Harris                if ($wlen >= $ixlen) break;
483d5b23302STom N Harris                foreach ($tokens[$xword] as $w) {
484d5b23302STom N Harris                    if (is_null($w[1])) continue;
485d5b23302STom N Harris                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
486d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
487d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
488d5b23302STom N Harris                    }
489d5b23302STom N Harris                }
490d5b23302STom N Harris            }
491d5b23302STom N Harris        }
492d5b23302STom N Harris        return $wids;
493d5b23302STom N Harris    }
494d5b23302STom N Harris
495d5b23302STom N Harris    /**
49600803e56STom N Harris     * Return a list of all pages
497488dd6ceSAndreas Gohr     *
49800803e56STom N Harris     * @param string    $key    list only pages containing the metadata key (optional)
49900803e56STom N Harris     * @return array            list of page names
50000803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
50100803e56STom N Harris     */
50200803e56STom N Harris    public function getPages($key=null) {
50300803e56STom N Harris        $page_idx = $this->_getIndex('page', '');
50400803e56STom N Harris        if (is_null($key)) return $page_idx;
50500803e56STom N Harris    }
50600803e56STom N Harris
50700803e56STom N Harris    /**
50800803e56STom N Harris     * Return a list of words sorted by number of times used
50900803e56STom N Harris     *
51000803e56STom N Harris     * @param int       $min    bottom frequency threshold
51100803e56STom N Harris     * @param int       $max    upper frequency limit. No limit if $max<$min
51200803e56STom N Harris     * @param string    $key    metadata key to list. Uses the fulltext index if not given
51300803e56STom N Harris     * @return array            list of words as the keys and frequency as values
51400803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
51500803e56STom N Harris     */
51600803e56STom N Harris    public function histogram($min=1, $max=0, $key=null) {
51700803e56STom N Harris    }
51800803e56STom N Harris
51900803e56STom N Harris    /**
52000803e56STom N Harris     * Lock the indexer.
52100803e56STom N Harris     *
52200803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
52300803e56STom N Harris     */
52400803e56STom N Harris    private function _lock() {
52500803e56STom N Harris        global $conf;
52600803e56STom N Harris        $status = true;
52700803e56STom N Harris        $lock = $conf['lockdir'].'/_indexer.lock';
52800803e56STom N Harris        while (!@mkdir($lock, $conf['dmode'])) {
52900803e56STom N Harris            usleep(50);
53000803e56STom N Harris            if (time() - @filemtime($lock) > 60*5) {
53100803e56STom N Harris                // looks like a stale lock, remove it
53200803e56STom N Harris                @rmdir($lock);
53300803e56STom N Harris                $status = "stale lock removed";
53400803e56STom N Harris            } else {
53500803e56STom N Harris                return false;
53600803e56STom N Harris            }
53700803e56STom N Harris        }
53800803e56STom N Harris        if ($conf['dperm'])
53900803e56STom N Harris            chmod($lock, $conf['dperm']);
54000803e56STom N Harris        return $status;
54100803e56STom N Harris    }
54200803e56STom N Harris
54300803e56STom N Harris    /**
54400803e56STom N Harris     * Release the indexer lock.
54500803e56STom N Harris     *
54600803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
54700803e56STom N Harris     */
54800803e56STom N Harris    private function _unlock() {
54900803e56STom N Harris        global $conf;
55000803e56STom N Harris        @rmdir($conf['lockdir'].'/_indexer.lock');
55100803e56STom N Harris        return true;
55200803e56STom N Harris    }
55300803e56STom N Harris
55400803e56STom N Harris    /**
55500803e56STom N Harris     * Retrieve the entire index.
55600803e56STom N Harris     *
55700803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
55800803e56STom N Harris     */
55900803e56STom N Harris    private function _getIndex($idx, $suffix) {
56000803e56STom N Harris        global $conf;
56100803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
562*d64516f5SMichael Hamann        if (!@file_exists($fn)) return array();
563*d64516f5SMichael Hamann        return file($fn, FILE_IGNORE_NEW_LINES);
56400803e56STom N Harris    }
56500803e56STom N Harris
56600803e56STom N Harris    /**
56700803e56STom N Harris     * Replace the contents of the index with an array.
56800803e56STom N Harris     *
56900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
57000803e56STom N Harris     */
57100803e56STom N Harris    private function _saveIndex($idx, $suffix, &$lines) {
57200803e56STom N Harris        global $conf;
57300803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
57400803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
57500803e56STom N Harris        if (!$fh) return false;
57600803e56STom N Harris        fwrite($fh, join("\n", $lines));
57700803e56STom N Harris        fclose($fh);
57800803e56STom N Harris        if (isset($conf['fperm']))
57900803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
58000803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
58100803e56STom N Harris        if ($suffix !== '')
58200803e56STom N Harris            $this->_cacheIndexDir($idx, $suffix, empty($lines));
58300803e56STom N Harris        return true;
58400803e56STom N Harris    }
58500803e56STom N Harris
58600803e56STom N Harris    /**
58700803e56STom N Harris     * Retrieve a line from the index.
58800803e56STom N Harris     *
58900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
59000803e56STom N Harris     */
59100803e56STom N Harris    private function _getIndexKey($idx, $suffix, $id) {
59200803e56STom N Harris        global $conf;
59300803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
59400803e56STom N Harris        if (!@file_exists($fn)) return '';
59500803e56STom N Harris        $fh = @fopen($fn, 'r');
59600803e56STom N Harris        if (!$fh) return '';
59700803e56STom N Harris        $ln = -1;
59800803e56STom N Harris        while (($line = fgets($fh)) !== false) {
59900803e56STom N Harris            if (++$ln == $id) break;
60000803e56STom N Harris        }
60100803e56STom N Harris        fclose($fh);
60200803e56STom N Harris        return rtrim((string)$line);
60300803e56STom N Harris    }
60400803e56STom N Harris
60500803e56STom N Harris    /**
60600803e56STom N Harris     * Write a line into the index.
60700803e56STom N Harris     *
60800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
60900803e56STom N Harris     */
61000803e56STom N Harris    private function _saveIndexKey($idx, $suffix, $id, $line) {
61100803e56STom N Harris        global $conf;
61200803e56STom N Harris        if (substr($line, -1) != "\n")
61300803e56STom N Harris            $line .= "\n";
61400803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
61500803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
61600803e56STom N Harris        if (!fh) return false;
61700803e56STom N Harris        $ih = @fopen($fn.'.idx', 'r');
61800803e56STom N Harris        if ($ih) {
61900803e56STom N Harris            $ln = -1;
62000803e56STom N Harris            while (($curline = fgets($ih)) !== false) {
62100803e56STom N Harris                fwrite($fh, (++$ln == $id) ? $line : $curline);
62200803e56STom N Harris            }
62300803e56STom N Harris            if ($id > $ln)
62400803e56STom N Harris                fwrite($fh, $line);
62500803e56STom N Harris            fclose($ih);
62600803e56STom N Harris        } else {
62700803e56STom N Harris            fwrite($fh, $line);
62800803e56STom N Harris        }
62900803e56STom N Harris        fclose($fh);
63000803e56STom N Harris        if (isset($conf['fperm']))
63100803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
63200803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
63300803e56STom N Harris        if ($suffix !== '')
63400803e56STom N Harris            $this->_cacheIndexDir($idx, $suffix);
63500803e56STom N Harris        return true;
63600803e56STom N Harris    }
63700803e56STom N Harris
63800803e56STom N Harris    /**
63900803e56STom N Harris     * Retrieve or insert a value in the index.
64000803e56STom N Harris     *
64100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
64200803e56STom N Harris     */
64300803e56STom N Harris    private function _addIndexKey($idx, $suffix, $value) {
64400803e56STom N Harris        $index = $this->_getIndex($idx, $suffix);
64500803e56STom N Harris        $id = array_search($value, $index);
64600803e56STom N Harris        if ($id === false) {
64700803e56STom N Harris            $id = count($index);
64800803e56STom N Harris            $index[$id] = $value;
64900803e56STom N Harris            if (!$this->_saveIndex($idx, $suffix, $index)) {
65000803e56STom N Harris                trigger_error("Failed to write $idx index", E_USER_ERROR);
65100803e56STom N Harris                return false;
65200803e56STom N Harris            }
65300803e56STom N Harris        }
65400803e56STom N Harris        return $id;
65500803e56STom N Harris    }
65600803e56STom N Harris
65700803e56STom N Harris    private function _cacheIndexDir($idx, $suffix, $delete=false) {
65800803e56STom N Harris        global $conf;
65900803e56STom N Harris        if ($idx == 'i')
66000803e56STom N Harris            $cachename = $conf['indexdir'].'/lengths';
66100803e56STom N Harris        else
66200803e56STom N Harris            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
66300803e56STom N Harris        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
66400803e56STom N Harris        if ($lengths === false) $lengths = array();
66500803e56STom N Harris        $old = array_search((string)$suffix, $lengths);
66600803e56STom N Harris        if (empty($lines)) {
66700803e56STom N Harris            if ($old === false) return;
66800803e56STom N Harris            unset($lengths[$old]);
66900803e56STom N Harris        } else {
67000803e56STom N Harris            if ($old !== false) return;
67100803e56STom N Harris            $lengths[] = $suffix;
67200803e56STom N Harris            sort($lengths);
67300803e56STom N Harris        }
67400803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
67500803e56STom N Harris        if (!$fh) {
67600803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
67700803e56STom N Harris            return;
67800803e56STom N Harris        }
67900803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
68000803e56STom N Harris        @fclose($fh);
68100803e56STom N Harris        if (isset($conf['fperm']))
68200803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
68300803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
68400803e56STom N Harris    }
68500803e56STom N Harris
68600803e56STom N Harris    /**
68700803e56STom N Harris     * Get the list of lengths indexed in the wiki.
68800803e56STom N Harris     *
68900803e56STom N Harris     * Read the index directory or a cache file and returns
69000803e56STom N Harris     * a sorted array of lengths of the words used in the wiki.
69100803e56STom N Harris     *
69200803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
69300803e56STom N Harris     */
69400803e56STom N Harris    private function _listIndexLengths() {
69500803e56STom N Harris        global $conf;
69600803e56STom N Harris        $cachename = $conf['indexdir'].'/lengths';
69700803e56STom N Harris        clearstatcache();
69800803e56STom N Harris        if (@file_exists($cachename.'.idx')) {
69900803e56STom N Harris            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
70000803e56STom N Harris            if ($lengths !== false) {
70100803e56STom N Harris                $idx = array();
70200803e56STom N Harris                foreach ($lengths as $length)
70300803e56STom N Harris                    $idx[] = (int)$length;
70400803e56STom N Harris                return $idx;
70500803e56STom N Harris            }
70600803e56STom N Harris        }
70700803e56STom N Harris
70800803e56STom N Harris        $dir = @opendir($conf['indexdir']);
70900803e56STom N Harris        if ($dir === false)
71000803e56STom N Harris            return array();
71100803e56STom N Harris        $lengths[] = array();
71200803e56STom N Harris        while (($f = readdir($dir)) !== false) {
71300803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
71400803e56STom N Harris                $i = substr($f, 1, -4);
71500803e56STom N Harris                if (is_numeric($i))
71600803e56STom N Harris                    $lengths[] = (int)$i;
71700803e56STom N Harris            }
71800803e56STom N Harris        }
71900803e56STom N Harris        closedir($dir);
72000803e56STom N Harris        sort($lengths);
72100803e56STom N Harris        // save this in a file
72200803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
72300803e56STom N Harris        if (!$fh) {
72400803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
72500803e56STom N Harris            return;
72600803e56STom N Harris        }
72700803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
72800803e56STom N Harris        @fclose($fh);
72900803e56STom N Harris        if (isset($conf['fperm']))
73000803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
73100803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
73200803e56STom N Harris
73300803e56STom N Harris        return $lengths;
73400803e56STom N Harris    }
73500803e56STom N Harris
73600803e56STom N Harris    /**
73700803e56STom N Harris     * Get the word lengths that have been indexed.
73800803e56STom N Harris     *
73900803e56STom N Harris     * Reads the index directory and returns an array of lengths
74000803e56STom N Harris     * that there are indices for.
74100803e56STom N Harris     *
74200803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
74300803e56STom N Harris     */
74400803e56STom N Harris    private function _indexLengths($filter) {
74500803e56STom N Harris        global $conf;
74600803e56STom N Harris        $idx = array();
74700803e56STom N Harris        if (is_array($filter)) {
74800803e56STom N Harris            // testing if index files exist only
74900803e56STom N Harris            $path = $conf['indexdir']."/i";
75000803e56STom N Harris            foreach ($filter as $key => $value) {
75100803e56STom N Harris                if (@file_exists($path.$key.'.idx'))
75200803e56STom N Harris                    $idx[] = $key;
75300803e56STom N Harris            }
75400803e56STom N Harris        } else {
75500803e56STom N Harris            $lengths = idx_listIndexLengths();
75600803e56STom N Harris            foreach ($lengths as $key => $length) {
75700803e56STom N Harris                // keep all the values equal or superior
75800803e56STom N Harris                if ((int)$length >= (int)$filter)
75900803e56STom N Harris                    $idx[] = $length;
76000803e56STom N Harris            }
76100803e56STom N Harris        }
76200803e56STom N Harris        return $idx;
76300803e56STom N Harris    }
76400803e56STom N Harris
76500803e56STom N Harris    /**
76600803e56STom N Harris     * Insert or replace a tuple in a line.
76700803e56STom N Harris     *
76800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
76900803e56STom N Harris     */
77000803e56STom N Harris    private function _updateTuple($line, $id, $count) {
77100803e56STom N Harris        $newLine = $line;
77200803e56STom N Harris        if ($newLine !== '')
77300803e56STom N Harris            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
77400803e56STom N Harris        $newLine = trim($newLine, ':');
77500803e56STom N Harris        if ($count) {
776*d64516f5SMichael Hamann            if (strlen($newLine) > 0)
77700803e56STom N Harris                return "$id*$count:".$newLine;
77800803e56STom N Harris            else
77900803e56STom N Harris                return "$id*$count".$newLine;
78000803e56STom N Harris        }
78100803e56STom N Harris        return $newLine;
78200803e56STom N Harris    }
78300803e56STom N Harris
78400803e56STom N Harris    /**
78500803e56STom N Harris     * Split a line into an array of tuples.
78600803e56STom N Harris     *
78700803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
78800803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
78900803e56STom N Harris     */
79000803e56STom N Harris    private function _parseTuples(&$keys, $line) {
79100803e56STom N Harris        $result = array();
79200803e56STom N Harris        if ($line == '') return $result;
79300803e56STom N Harris        $parts = explode(':', $line);
79400803e56STom N Harris        foreach ($parts as $tuple) {
79500803e56STom N Harris            if ($tuple == '') continue;
79600803e56STom N Harris            list($key, $cnt) = explode('*', $tuple);
797*d64516f5SMichael Hamann            if (!$cnt) continue;
79800803e56STom N Harris            $key = $keys[$key];
79900803e56STom N Harris            if (!$key) continue;
80000803e56STom N Harris            $result[$key] = $cnt;
80100803e56STom N Harris        }
80200803e56STom N Harris        return $result;
80300803e56STom N Harris    }
80400803e56STom N Harris}
80500803e56STom N Harris
80600803e56STom N Harris/**
80700803e56STom N Harris * Create an instance of the indexer.
80800803e56STom N Harris *
80900803e56STom N Harris * @return object               a Doku_Indexer
81000803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
81100803e56STom N Harris */
8129b41be24STom N Harrisfunction idx_get_indexer() {
81300803e56STom N Harris    static $Indexer = null;
81400803e56STom N Harris    if (is_null($Indexer)) {
81500803e56STom N Harris        $Indexer = new Doku_Indexer();
81600803e56STom N Harris    }
81700803e56STom N Harris    return $Indexer;
81800803e56STom N Harris}
81900803e56STom N Harris
82000803e56STom N Harris/**
82100803e56STom N Harris * Returns words that will be ignored.
82200803e56STom N Harris *
82300803e56STom N Harris * @return array                list of stop words
82400803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
82500803e56STom N Harris */
82600803e56STom N Harrisfunction & idx_get_stopwords() {
82700803e56STom N Harris    static $stopwords = null;
82800803e56STom N Harris    if (is_null($stopwords)) {
82900803e56STom N Harris        global $conf;
83000803e56STom N Harris        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
83100803e56STom N Harris        if(@file_exists($swfile)){
83200803e56STom N Harris            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
83300803e56STom N Harris        }else{
83400803e56STom N Harris            $stopwords = array();
83500803e56STom N Harris        }
83600803e56STom N Harris    }
83700803e56STom N Harris    return $stopwords;
83800803e56STom N Harris}
83900803e56STom N Harris
84000803e56STom N Harris/**
84100803e56STom N Harris * Adds/updates the search index for the given page
84200803e56STom N Harris *
84300803e56STom N Harris * Locking is handled internally.
84400803e56STom N Harris *
84500803e56STom N Harris * @param string        $page   name of the page to index
8469b41be24STom N Harris * @param boolean       $verbose    print status messages
84700803e56STom N Harris * @return boolean              the function completed successfully
84800803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
84900803e56STom N Harris */
8509b41be24STom N Harrisfunction idx_addPage($page, $verbose=false) {
8519b41be24STom N Harris    // check if indexing needed
8529b41be24STom N Harris    $idxtag = metaFN($page,'.indexed');
8539b41be24STom N Harris    if(@file_exists($idxtag)){
8549b41be24STom N Harris        if(trim(io_readFile($idxtag)) == idx_get_version()){
8559b41be24STom N Harris            $last = @filemtime($idxtag);
8569b41be24STom N Harris            if($last > @filemtime(wikiFN($ID))){
8579b41be24STom N Harris                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
8589b41be24STom N Harris                return false;
8599b41be24STom N Harris            }
8609b41be24STom N Harris        }
8619b41be24STom N Harris    }
8629b41be24STom N Harris
86300803e56STom N Harris    $body = '';
86400803e56STom N Harris    $data = array($page, $body);
86500803e56STom N Harris    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
86600803e56STom N Harris    if ($evt->advise_before()) $data[1] = $data[1] . " " . rawWiki($page);
86700803e56STom N Harris    $evt->advise_after();
86800803e56STom N Harris    unset($evt);
86900803e56STom N Harris    list($page,$body) = $data;
87000803e56STom N Harris
8719b41be24STom N Harris    $Indexer = idx_get_indexer();
8729b41be24STom N Harris    $result = $Indexer->addPageWords($page, $body);
8739b41be24STom N Harris    if ($result == "locked") {
8749b41be24STom N Harris        if ($verbose) print("Indexer: locked".DOKU_LF);
8759b41be24STom N Harris        return false;
8769b41be24STom N Harris    }
8779b41be24STom N Harris    if ($result)
8789b41be24STom N Harris        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
8799b41be24STom N Harris    if ($verbose) {
8809b41be24STom N Harris        print("Indexer: finished".DOKU_LF);
8819b41be24STom N Harris        return true;
8829b41be24STom N Harris    }
8839b41be24STom N Harris    return $result;
88400803e56STom N Harris}
88500803e56STom N Harris
88600803e56STom N Harris/**
88700803e56STom N Harris * Find tokens in the fulltext index
88800803e56STom N Harris *
88900803e56STom N Harris * Takes an array of words and will return a list of matching
89000803e56STom N Harris * pages for each one.
891488dd6ceSAndreas Gohr *
89263773904SAndreas Gohr * Important: No ACL checking is done here! All results are
89363773904SAndreas Gohr *            returned, regardless of permissions
89463773904SAndreas Gohr *
8959b41be24STom N Harris * @param arrayref      $words  list of words to search for
89600803e56STom N Harris * @return array                list of pages found, associated with the search terms
897488dd6ceSAndreas Gohr */
8989b41be24STom N Harrisfunction idx_lookup(&$words) {
8999b41be24STom N Harris    $Indexer = idx_get_indexer();
90000803e56STom N Harris    return $Indexer->lookup($words);
901488dd6ceSAndreas Gohr}
902488dd6ceSAndreas Gohr
903488dd6ceSAndreas Gohr/**
90400803e56STom N Harris * Split a string into tokens
905488dd6ceSAndreas Gohr *
906488dd6ceSAndreas Gohr */
90700803e56STom N Harrisfunction idx_tokenizer($string, $wc=false) {
9089b41be24STom N Harris    $Indexer = idx_get_indexer();
90900803e56STom N Harris    return $Indexer->tokenizer($string, $wc);
910488dd6ceSAndreas Gohr}
91100803e56STom N Harris
91200803e56STom N Harris/* For compatibility */
913488dd6ceSAndreas Gohr
914f5eb7cf0SAndreas Gohr/**
91500803e56STom N Harris * Read the list of words in an index (if it exists).
916f5eb7cf0SAndreas Gohr *
9174e1bf408STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
918f5eb7cf0SAndreas Gohr */
91900803e56STom N Harrisfunction idx_getIndex($idx, $suffix) {
9201c07b9e6STom N Harris    global $conf;
92100803e56STom N Harris    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
92200803e56STom N Harris    if (!@file_exists($fn)) return array();
92300803e56STom N Harris    return file($fn);
92400803e56STom N Harris}
925f5eb7cf0SAndreas Gohr
92600803e56STom N Harris/**
92700803e56STom N Harris * Get the list of lengths indexed in the wiki.
92800803e56STom N Harris *
92900803e56STom N Harris * Read the index directory or a cache file and returns
93000803e56STom N Harris * a sorted array of lengths of the words used in the wiki.
93100803e56STom N Harris *
93200803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
93300803e56STom N Harris */
93400803e56STom N Harrisfunction idx_listIndexLengths() {
93500803e56STom N Harris    global $conf;
93600803e56STom N Harris    // testing what we have to do, create a cache file or not.
93700803e56STom N Harris    if ($conf['readdircache'] == 0) {
93800803e56STom N Harris        $docache = false;
9391c07b9e6STom N Harris    } else {
94000803e56STom N Harris        clearstatcache();
94100803e56STom N Harris        if (@file_exists($conf['indexdir'].'/lengths.idx')
94200803e56STom N Harris        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
94300803e56STom N Harris            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
94400803e56STom N Harris                $idx = array();
94500803e56STom N Harris                foreach ($lengths as $length) {
94600803e56STom N Harris                    $idx[] = (int)$length;
94700803e56STom N Harris                }
94800803e56STom N Harris                return $idx;
949f5eb7cf0SAndreas Gohr            }
9501c07b9e6STom N Harris        }
95100803e56STom N Harris        $docache = true;
95200803e56STom N Harris    }
9534e1bf408STom N Harris
95400803e56STom N Harris    if ($conf['readdircache'] == 0 || $docache) {
95500803e56STom N Harris        $dir = @opendir($conf['indexdir']);
95600803e56STom N Harris        if ($dir === false)
95700803e56STom N Harris            return array();
95800803e56STom N Harris        $idx[] = array();
95900803e56STom N Harris        while (($f = readdir($dir)) !== false) {
96000803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
96100803e56STom N Harris                $i = substr($f, 1, -4);
96200803e56STom N Harris                if (is_numeric($i))
96300803e56STom N Harris                    $idx[] = (int)$i;
96400803e56STom N Harris            }
96500803e56STom N Harris        }
96600803e56STom N Harris        closedir($dir);
96700803e56STom N Harris        sort($idx);
96800803e56STom N Harris        // save this in a file
96900803e56STom N Harris        if ($docache) {
97000803e56STom N Harris            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
97100803e56STom N Harris            @fwrite($handle, implode("\n", $idx));
97200803e56STom N Harris            @fclose($handle);
97300803e56STom N Harris        }
97400803e56STom N Harris        return $idx;
97500803e56STom N Harris    }
97600803e56STom N Harris
97700803e56STom N Harris    return array();
97800803e56STom N Harris}
97900803e56STom N Harris
98000803e56STom N Harris/**
98100803e56STom N Harris * Get the word lengths that have been indexed.
98200803e56STom N Harris *
98300803e56STom N Harris * Reads the index directory and returns an array of lengths
98400803e56STom N Harris * that there are indices for.
98500803e56STom N Harris *
98600803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
98700803e56STom N Harris */
98800803e56STom N Harrisfunction idx_indexLengths($filter) {
98900803e56STom N Harris    global $conf;
99000803e56STom N Harris    $idx = array();
99100803e56STom N Harris    if (is_array($filter)) {
99200803e56STom N Harris        // testing if index files exist only
99300803e56STom N Harris        $path = $conf['indexdir']."/i";
99400803e56STom N Harris        foreach ($filter as $key => $value) {
99500803e56STom N Harris            if (@file_exists($path.$key.'.idx'))
99600803e56STom N Harris                $idx[] = $key;
99700803e56STom N Harris        }
998f5eb7cf0SAndreas Gohr    } else {
99900803e56STom N Harris        $lengths = idx_listIndexLengths();
100000803e56STom N Harris        foreach ($lengths as $key => $length) {
100100803e56STom N Harris            // keep all the values equal or superior
100200803e56STom N Harris            if ((int)$length >= (int)$filter)
100300803e56STom N Harris                $idx[] = $length;
1004f5eb7cf0SAndreas Gohr        }
100500803e56STom N Harris    }
100600803e56STom N Harris    return $idx;
1007f5eb7cf0SAndreas Gohr}
1008f5eb7cf0SAndreas Gohr
100900803e56STom N Harris/**
101000803e56STom N Harris * Clean a name of a key for use as a file name.
101100803e56STom N Harris *
101200803e56STom N Harris * Romanizes non-latin characters, then strips away anything that's
101300803e56STom N Harris * not a letter, number, or underscore.
101400803e56STom N Harris *
101500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
101600803e56STom N Harris */
101700803e56STom N Harrisfunction idx_cleanName($name) {
101800803e56STom N Harris    $name = utf8_romanize(trim((string)$name));
101900803e56STom N Harris    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
102000803e56STom N Harris    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
102100803e56STom N Harris    return strtolower($name);
1022f5eb7cf0SAndreas Gohr}
1023f5eb7cf0SAndreas Gohr
102400803e56STom N Harris//Setup VIM: ex: et ts=4 :
1025