xref: /dokuwiki/inc/indexer.php (revision bbc85ee4bc98fadf89707309f923f8ae2c16f727)
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    /**
213e1e1a7e0SMichael Hamann     * Add/update keys to/of 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>
225e1e1a7e0SMichael Hamann     * @author Michael Hamann <michael@content-space.de>
22644ca0adfSAndreas Gohr     */
22700803e56STom N Harris    public function addMetaKeys($page, $key, $value=null) {
22800803e56STom N Harris        if (!is_array($key)) {
22900803e56STom N Harris            $key = array($key => $value);
23000803e56STom N Harris        } elseif (!is_null($value)) {
23100803e56STom N Harris            // $key is array, but $value is not null
23200803e56STom N Harris            trigger_error("array passed to addMetaKeys but value is not null", E_USER_WARNING);
23300803e56STom N Harris        }
23400803e56STom N Harris
235e1e1a7e0SMichael Hamann        if (!$this->_lock())
236e1e1a7e0SMichael Hamann            return "locked";
237b4ce25e9SAndreas Gohr
238488dd6ceSAndreas Gohr        // load known documents
23900803e56STom N Harris        $pid = $this->_addIndexKey('page', '', $page);
24000803e56STom N Harris        if ($pid === false) {
24100803e56STom N Harris            $this->_unlock();
242579b0f7eSTNHarris            return false;
24344ca0adfSAndreas Gohr        }
24400803e56STom N Harris
24500803e56STom N Harris        foreach ($key as $name => $values) {
24600803e56STom N Harris            $metaname = idx_cleanName($name);
24700803e56STom N Harris            $metaidx = $this->_getIndex($metaname, '_i');
24800803e56STom N Harris            $metawords = $this->_getIndex($metaname, '_w');
24900803e56STom N Harris            $addwords = false;
250e1e1a7e0SMichael Hamann
251e1e1a7e0SMichael Hamann            if (!is_array($values)) $values = array($values);
252e1e1a7e0SMichael Hamann
253e1e1a7e0SMichael Hamann            $val_idx = $this->_getIndexKey($metaname, '_p', $pid);
254e1e1a7e0SMichael Hamann            if ($val_idx != '') {
255e1e1a7e0SMichael Hamann                $val_idx = explode(':', $val_idx);
256e1e1a7e0SMichael Hamann                // -1 means remove, 0 keep, 1 add
257e1e1a7e0SMichael Hamann                $val_idx = array_combine($val_idx, array_fill(0, count($val_idx), -1));
258e1e1a7e0SMichael Hamann            } else {
259e1e1a7e0SMichael Hamann                $val_idx = array();
260e1e1a7e0SMichael Hamann            }
261e1e1a7e0SMichael Hamann
262e1e1a7e0SMichael Hamann
26300803e56STom N Harris            foreach ($values as $val) {
26400803e56STom N Harris                $val = (string)$val;
26500803e56STom N Harris                if ($val !== "") {
26600803e56STom N Harris                    $id = array_search($val, $metawords);
26700803e56STom N Harris                    if ($id === false) {
26800803e56STom N Harris                        $id = count($metawords);
26900803e56STom N Harris                        $metawords[$id] = $val;
27000803e56STom N Harris                        $addwords = true;
271d5b23302STom N Harris                    }
272e1e1a7e0SMichael Hamann                    // test if value is already in the index
273e1e1a7e0SMichael Hamann                    if (isset($val_idx[$id]) && $val_idx[$id] <= 0)
274e1e1a7e0SMichael Hamann                        $val_idx[$id] = 0;
275e1e1a7e0SMichael Hamann                    else // else add it
276e1e1a7e0SMichael Hamann                        $val_idx[$id] = 1;
27744ca0adfSAndreas Gohr                }
278579b0f7eSTNHarris            }
279e1e1a7e0SMichael Hamann
28000803e56STom N Harris            if ($addwords)
28100803e56STom N Harris                $this->_saveIndex($metaname.'_w', '', $metawords);
282e1e1a7e0SMichael Hamann            $vals_changed = false;
283e1e1a7e0SMichael Hamann            foreach ($val_idx as $id => $action) {
284e1e1a7e0SMichael Hamann                if ($action == -1) {
285e1e1a7e0SMichael Hamann                    $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 0);
286e1e1a7e0SMichael Hamann                    $vals_changed = true;
287e1e1a7e0SMichael Hamann                    unset($val_idx[$id]);
288e1e1a7e0SMichael Hamann                } elseif ($action == 1) {
289e1e1a7e0SMichael Hamann                    $metaidx[$id] = $this->_updateTuple($metaidx[$id], $pid, 1);
290e1e1a7e0SMichael Hamann                    $vals_changed = true;
291e1e1a7e0SMichael Hamann                }
292e1e1a7e0SMichael Hamann            }
293e1e1a7e0SMichael Hamann
294e1e1a7e0SMichael Hamann            if ($vals_changed) {
29500803e56STom N Harris                $this->_saveIndex($metaname.'_i', '', $metaidx);
296e1e1a7e0SMichael Hamann                $val_idx = implode(':', array_keys($val_idx));
297e1e1a7e0SMichael Hamann                $this->_saveIndexKey($metaname.'_p', '', $pid, $val_idx);
298b6344591STom N Harris            }
299e1e1a7e0SMichael Hamann
30000803e56STom N Harris            unset($metaidx);
30100803e56STom N Harris            unset($metawords);
302a0c5c349STom N Harris        }
303e1e1a7e0SMichael Hamann
304e1e1a7e0SMichael Hamann        $this->_unlock();
305579b0f7eSTNHarris        return true;
30644ca0adfSAndreas Gohr    }
30744ca0adfSAndreas Gohr
30844ca0adfSAndreas Gohr    /**
30900803e56STom N Harris     * Remove a page from the index
31044ca0adfSAndreas Gohr     *
31100803e56STom N Harris     * Erases entries in all known indexes.
31244ca0adfSAndreas Gohr     *
31300803e56STom N Harris     * @param string    $page   a page name
31400803e56STom N Harris     * @return boolean          the function completed successfully
31500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
31644ca0adfSAndreas Gohr     */
31700803e56STom N Harris    public function deletePage($page) {
318*bbc85ee4STom N Harris        if (!$this->_lock())
319*bbc85ee4STom N Harris            return "locked";
320*bbc85ee4STom N Harris
321*bbc85ee4STom N Harris        // load known documents
322*bbc85ee4STom N Harris        $page_idx = $this->_getIndexKey('page', '', $page);
323*bbc85ee4STom N Harris        if ($page_idx === false) {
324*bbc85ee4STom N Harris            $this->_unlock();
325*bbc85ee4STom N Harris            return false;
326*bbc85ee4STom N Harris        }
327*bbc85ee4STom N Harris
328*bbc85ee4STom N Harris        // Remove obsolete index entries
329*bbc85ee4STom N Harris        $pageword_idx = $this->_getIndexKey('pageword', '', $pid);
330*bbc85ee4STom N Harris        if ($pageword_idx !== '') {
331*bbc85ee4STom N Harris            $delwords = explode(':',$pageword_idx);
332*bbc85ee4STom N Harris            $upwords = array();
333*bbc85ee4STom N Harris            foreach ($delwords as $word) {
334*bbc85ee4STom N Harris                if ($word != '') {
335*bbc85ee4STom N Harris                    list($wlen,$wid) = explode('*', $word);
336*bbc85ee4STom N Harris                    $wid = (int)$wid;
337*bbc85ee4STom N Harris                    $upwords[$wlen][] = $wid;
338*bbc85ee4STom N Harris                }
339*bbc85ee4STom N Harris            }
340*bbc85ee4STom N Harris            foreach ($upwords as $wlen => $widx) {
341*bbc85ee4STom N Harris                $index = $this->_getIndex('i', $wlen);
342*bbc85ee4STom N Harris                foreach ($widx as $wid) {
343*bbc85ee4STom N Harris                    $index[$wid] = $this->_updateTuple($index[$wid], $pid, 0);
344*bbc85ee4STom N Harris                }
345*bbc85ee4STom N Harris                $this->_saveIndex('i', $wlen, $index);
346*bbc85ee4STom N Harris            }
347*bbc85ee4STom N Harris        }
348*bbc85ee4STom N Harris        // Save the reverse index
349*bbc85ee4STom N Harris        if (!$this->_saveIndexKey('pageword', '', $pid, "")) {
350*bbc85ee4STom N Harris            $this->_unlock();
351*bbc85ee4STom N Harris            return false;
352*bbc85ee4STom N Harris        }
353*bbc85ee4STom N Harris
354*bbc85ee4STom N Harris        // XXX TODO: delete meta keys
355*bbc85ee4STom N Harris
356*bbc85ee4STom N Harris        $this->_unlock();
357*bbc85ee4STom N Harris        return true;
358d5b23302STom N Harris    }
35944ca0adfSAndreas Gohr
360d5b23302STom N Harris    /**
36100803e56STom N Harris     * Split the text into words for fulltext search
362d5b23302STom N Harris     *
36300803e56STom N Harris     * TODO: does this also need &$stopwords ?
364d5b23302STom N Harris     *
36500803e56STom N Harris     * @param string    $text   plain text
36600803e56STom N Harris     * @param boolean   $wc     are wildcards allowed?
36700803e56STom N Harris     * @return array            list of words in the text
368d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
369d5b23302STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
370d5b23302STom N Harris     */
37100803e56STom N Harris    public function tokenizer($text, $wc=false) {
37222952965SYoBoY        global $conf;
37300803e56STom N Harris        $words = array();
37400803e56STom N Harris        $wc = ($wc) ? '' : '\*';
37500803e56STom N Harris        $stopwords =& idx_get_stopwords();
37600803e56STom N Harris
37700803e56STom N Harris        if ($conf['external_tokenizer'] && $conf['tokenizer_cmd'] != '') {
37800803e56STom N Harris            if (0 == io_exec($conf['tokenizer_cmd'], $text, $output))
37900803e56STom N Harris                $text = $output;
38022952965SYoBoY        } else {
38100803e56STom N Harris            if (preg_match('/[^0-9A-Za-z ]/u', $text)) {
38200803e56STom N Harris                // handle asian chars as single words (may fail on older PHP version)
38300803e56STom N Harris                $asia = @preg_replace('/('.IDX_ASIAN.')/u', ' \1 ', $text);
38400803e56STom N Harris                if (!is_null($asia)) $text = $asia; // recover from regexp falure
38522952965SYoBoY            }
38622952965SYoBoY        }
38700803e56STom N Harris        $text = strtr($text, "\r\n\t", '   ');
38800803e56STom N Harris        if (preg_match('/[^0-9A-Za-z ]/u', $text))
38900803e56STom N Harris            $text = utf8_stripspecials($text, ' ', '\._\-:'.$wc);
39022952965SYoBoY
39100803e56STom N Harris        $wordlist = explode(' ', $text);
39200803e56STom N Harris        foreach ($wordlist as $word) {
39300803e56STom N Harris            $word = (preg_match('/[^0-9A-Za-z]/u', $word)) ?
39400803e56STom N Harris                utf8_strtolower($word) : strtolower($word);
39500803e56STom N Harris            if (!is_numeric($word) && strlen($word) < IDX_MINWORDLENGTH) continue;
39600803e56STom N Harris            if (array_search($word, $stopwords) !== false) continue;
39700803e56STom N Harris            $words[] = $word;
39822952965SYoBoY        }
39900803e56STom N Harris        return $words;
40022952965SYoBoY    }
40122952965SYoBoY
40222952965SYoBoY    /**
40300803e56STom N Harris     * Find pages in the fulltext index containing the words,
404579b0f7eSTNHarris     *
40500803e56STom N Harris     * The search words must be pre-tokenized, meaning only letters and
40600803e56STom N Harris     * numbers with an optional wildcard
407579b0f7eSTNHarris     *
40800803e56STom N Harris     * The returned array will have the original tokens as key. The values
40900803e56STom N Harris     * in the returned list is an array with the page names as keys and the
41000803e56STom N Harris     * number of times that token appeas on the page as value.
41100803e56STom N Harris     *
4129b41be24STom N Harris     * @param arrayref  $tokens list of words to search for
41300803e56STom N Harris     * @return array            list of page names with usage counts
41400803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
41500803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
416579b0f7eSTNHarris     */
4179b41be24STom N Harris    public function lookup(&$tokens) {
41800803e56STom N Harris        $result = array();
41900803e56STom N Harris        $wids = $this->_getIndexWords($tokens, $result);
42000803e56STom N Harris        if (empty($wids)) return array();
42100803e56STom N Harris        // load known words and documents
42200803e56STom N Harris        $page_idx = $this->_getIndex('page', '');
42300803e56STom N Harris        $docs = array();
42400803e56STom N Harris        foreach (array_keys($wids) as $wlen) {
42500803e56STom N Harris            $wids[$wlen] = array_unique($wids[$wlen]);
42600803e56STom N Harris            $index = $this->_getIndex('i', $wlen);
42700803e56STom N Harris            foreach($wids[$wlen] as $ixid) {
42800803e56STom N Harris                if ($ixid < count($index))
42900803e56STom N Harris                    $docs["$wlen*$ixid"] = $this->_parseTuples($page_idx, $index[$ixid]);
430d5b23302STom N Harris            }
431d5b23302STom N Harris        }
43200803e56STom N Harris        // merge found pages into final result array
43300803e56STom N Harris        $final = array();
43400803e56STom N Harris        foreach ($result as $word => $res) {
43500803e56STom N Harris            $final[$word] = array();
43600803e56STom N Harris            foreach ($res as $wid) {
43700803e56STom N Harris                $hits = &$docs[$wid];
43800803e56STom N Harris                foreach ($hits as $hitkey => $hitcnt) {
43900803e56STom N Harris                    // make sure the document still exists
44000803e56STom N Harris                    if (!page_exists($hitkey, '', false)) continue;
44100803e56STom N Harris                    if (!isset($final[$word][$hitkey]))
44200803e56STom N Harris                        $final[$word][$hitkey] = $hitcnt;
44300803e56STom N Harris                    else
44400803e56STom N Harris                        $final[$word][$hitkey] += $hitcnt;
445d5b23302STom N Harris                }
446579b0f7eSTNHarris            }
447579b0f7eSTNHarris        }
44800803e56STom N Harris        return $final;
449579b0f7eSTNHarris    }
450579b0f7eSTNHarris
451579b0f7eSTNHarris    /**
45200803e56STom N Harris     * Find pages containing a metadata key.
453d5b23302STom N Harris     *
45400803e56STom N Harris     * The metadata values are compared as case-sensitive strings. Pass a
45500803e56STom N Harris     * callback function that returns true or false to use a different
45600803e56STom N Harris     * comparison function
457d5b23302STom N Harris     *
45800803e56STom N Harris     * @param string    $key    name of the metadata key to look for
45900803e56STom N Harris     * @param string    $value  search term to look for
46000803e56STom N Harris     * @param callback  $func   comparison function
461e1e1a7e0SMichael Hamann     * @return array            lists with page names, keys are query values
46200803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
463cd763a5bSMichael Hamann     * @author Michael Hamann <michael@content-space.de>
46400803e56STom N Harris     */
46500803e56STom N Harris    public function lookupKey($key, $value, $func=null) {
466cd763a5bSMichael Hamann        $metaname = idx_cleanName($key);
467cd763a5bSMichael Hamann
468cd763a5bSMichael Hamann        // get all words in order to search the matching ids
469cd763a5bSMichael Hamann        $words = $this->_getIndex($metaname, '_w');
470cd763a5bSMichael Hamann
471cd763a5bSMichael Hamann        // the matching ids for the provided value(s)
472cd763a5bSMichael Hamann        $value_ids = array();
473cd763a5bSMichael Hamann
474cd763a5bSMichael Hamann        if (!is_array($value)) $value = array($value);
475cd763a5bSMichael Hamann
476cd763a5bSMichael Hamann        foreach ($value as $val) {
477cd763a5bSMichael Hamann            if (is_null($func)) {
478cd763a5bSMichael Hamann                if (($i = array_search($val, $words)) !== false)
479cd763a5bSMichael Hamann                    $value_ids[$i] = $val;
480cd763a5bSMichael Hamann            } else {
481cd763a5bSMichael Hamann                foreach ($words as $i => $word) {
482cd763a5bSMichael Hamann                    if (call_user_func_array($func, array($word, $value)))
483cd763a5bSMichael Hamann                        $value_ids[$i] = $val;
484cd763a5bSMichael Hamann                }
485cd763a5bSMichael Hamann            }
486cd763a5bSMichael Hamann        }
487cd763a5bSMichael Hamann
488cd763a5bSMichael Hamann        unset($words); // free the used memory
489cd763a5bSMichael Hamann
490cd763a5bSMichael Hamann        // load all lines and pages so the used lines can be taken and matched with the pages
491cd763a5bSMichael Hamann        $lines = $this->_getIndex($metaname, '_i');
492cd763a5bSMichael Hamann        $page_idx = $this->_getIndex('page', '');
493cd763a5bSMichael Hamann
494cd763a5bSMichael Hamann        $result = array();
495cd763a5bSMichael Hamann        foreach ($value_ids as $value_id => $val) {
496cd763a5bSMichael Hamann            // parse the tuples of the form page_id*1:page2_id*1 and so on, return value
497cd763a5bSMichael Hamann            // is an array with page_id => 1, page2_id => 1 etc. so take the keys only
498cd763a5bSMichael Hamann            $result[$val] = array_keys($this->_parseTuples($page_idx, $lines[$value_id]));
499cd763a5bSMichael Hamann        }
500cd763a5bSMichael Hamann        return $result;
50100803e56STom N Harris    }
50200803e56STom N Harris
50300803e56STom N Harris    /**
50400803e56STom N Harris     * Find the index ID of each search term.
50500803e56STom N Harris     *
50600803e56STom N Harris     * The query terms should only contain valid characters, with a '*' at
50700803e56STom N Harris     * either the beginning or end of the word (or both).
50800803e56STom N Harris     * The $result parameter can be used to merge the index locations with
50900803e56STom N Harris     * the appropriate query term.
51000803e56STom N Harris     *
5119b41be24STom N Harris     * @param arrayref  $words  The query terms.
51200803e56STom N Harris     * @param arrayref  $result Set to word => array("length*id" ...)
513d5b23302STom N Harris     * @return array            Set to length => array(id ...)
514d5b23302STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
515d5b23302STom N Harris     */
5169b41be24STom N Harris    private function _getIndexWords(&$words, &$result) {
517d5b23302STom N Harris        $tokens = array();
518d5b23302STom N Harris        $tokenlength = array();
519d5b23302STom N Harris        $tokenwild = array();
520d5b23302STom N Harris        foreach ($words as $word) {
521d5b23302STom N Harris            $result[$word] = array();
52200803e56STom N Harris            $caret = false;
52300803e56STom N Harris            $dollar = false;
524d5b23302STom N Harris            $xword = $word;
525d5b23302STom N Harris            $wlen = wordlen($word);
526d5b23302STom N Harris
527d5b23302STom N Harris            // check for wildcards
528d5b23302STom N Harris            if (substr($xword, 0, 1) == '*') {
529d5b23302STom N Harris                $xword = substr($xword, 1);
53000803e56STom N Harris                $caret = true;
531d5b23302STom N Harris                $wlen -= 1;
532d5b23302STom N Harris            }
533d5b23302STom N Harris            if (substr($xword, -1, 1) == '*') {
534d5b23302STom N Harris                $xword = substr($xword, 0, -1);
53500803e56STom N Harris                $dollar = true;
536d5b23302STom N Harris                $wlen -= 1;
537d5b23302STom N Harris            }
53800803e56STom N Harris            if ($wlen < IDX_MINWORDLENGTH && !$caret && !$dollar && !is_numeric($xword))
53900803e56STom N Harris                continue;
54000803e56STom N Harris            if (!isset($tokens[$xword]))
541d5b23302STom N Harris                $tokenlength[$wlen][] = $xword;
54200803e56STom N Harris            if ($caret || $dollar) {
54300803e56STom N Harris                $re = preg_quote($xword, '/');
54400803e56STom N Harris                if ($caret) $re = '^'.$re;
54500803e56STom N Harris                if ($dollar) $re = $re.'$';
54600803e56STom N Harris                $tokens[$xword][] = array($word, '/'.$re.'/');
54700803e56STom N Harris                if (!isset($tokenwild[$xword]))
54800803e56STom N Harris                    $tokenwild[$xword] = $wlen;
54900803e56STom N Harris            } else {
550d5b23302STom N Harris                $tokens[$xword][] = array($word, null);
551d5b23302STom N Harris            }
55200803e56STom N Harris        }
553d5b23302STom N Harris        asort($tokenwild);
55400803e56STom N Harris        // $tokens = array( base word => array( [ query term , regexp ] ... ) ... )
555d5b23302STom N Harris        // $tokenlength = array( base word length => base word ... )
556d5b23302STom N Harris        // $tokenwild = array( base word => base word length ... )
557d5b23302STom N Harris        $length_filter = empty($tokenwild) ? $tokenlength : min(array_keys($tokenlength));
55800803e56STom N Harris        $indexes_known = $this->_indexLengths($length_filter);
559d5b23302STom N Harris        if (!empty($tokenwild)) sort($indexes_known);
560d5b23302STom N Harris        // get word IDs
561d5b23302STom N Harris        $wids = array();
562d5b23302STom N Harris        foreach ($indexes_known as $ixlen) {
56300803e56STom N Harris            $word_idx = $this->_getIndex('w', $ixlen);
564d5b23302STom N Harris            // handle exact search
565d5b23302STom N Harris            if (isset($tokenlength[$ixlen])) {
566d5b23302STom N Harris                foreach ($tokenlength[$ixlen] as $xword) {
56700803e56STom N Harris                    $wid = array_search($xword, $word_idx);
56800803e56STom N Harris                    if ($wid !== false) {
569d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
570d5b23302STom N Harris                        foreach ($tokens[$xword] as $w)
571d5b23302STom N Harris                            $result[$w[0]][] = "$ixlen*$wid";
572d5b23302STom N Harris                    }
573d5b23302STom N Harris                }
574d5b23302STom N Harris            }
575d5b23302STom N Harris            // handle wildcard search
576d5b23302STom N Harris            foreach ($tokenwild as $xword => $wlen) {
577d5b23302STom N Harris                if ($wlen >= $ixlen) break;
578d5b23302STom N Harris                foreach ($tokens[$xword] as $w) {
579d5b23302STom N Harris                    if (is_null($w[1])) continue;
580d5b23302STom N Harris                    foreach(array_keys(preg_grep($w[1], $word_idx)) as $wid) {
581d5b23302STom N Harris                        $wids[$ixlen][] = $wid;
582d5b23302STom N Harris                        $result[$w[0]][] = "$ixlen*$wid";
583d5b23302STom N Harris                    }
584d5b23302STom N Harris                }
585d5b23302STom N Harris            }
586d5b23302STom N Harris        }
587d5b23302STom N Harris        return $wids;
588d5b23302STom N Harris    }
589d5b23302STom N Harris
590d5b23302STom N Harris    /**
59100803e56STom N Harris     * Return a list of all pages
592488dd6ceSAndreas Gohr     *
59300803e56STom N Harris     * @param string    $key    list only pages containing the metadata key (optional)
59400803e56STom N Harris     * @return array            list of page names
59500803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
59600803e56STom N Harris     */
59700803e56STom N Harris    public function getPages($key=null) {
59800803e56STom N Harris        $page_idx = $this->_getIndex('page', '');
59900803e56STom N Harris        if (is_null($key)) return $page_idx;
60000803e56STom N Harris    }
60100803e56STom N Harris
60200803e56STom N Harris    /**
60300803e56STom N Harris     * Return a list of words sorted by number of times used
60400803e56STom N Harris     *
60500803e56STom N Harris     * @param int       $min    bottom frequency threshold
60600803e56STom N Harris     * @param int       $max    upper frequency limit. No limit if $max<$min
60700803e56STom N Harris     * @param string    $key    metadata key to list. Uses the fulltext index if not given
60800803e56STom N Harris     * @return array            list of words as the keys and frequency as values
60900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
61000803e56STom N Harris     */
61100803e56STom N Harris    public function histogram($min=1, $max=0, $key=null) {
61200803e56STom N Harris    }
61300803e56STom N Harris
61400803e56STom N Harris    /**
61500803e56STom N Harris     * Lock the indexer.
61600803e56STom N Harris     *
61700803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
61800803e56STom N Harris     */
61900803e56STom N Harris    private function _lock() {
62000803e56STom N Harris        global $conf;
62100803e56STom N Harris        $status = true;
62200803e56STom N Harris        $lock = $conf['lockdir'].'/_indexer.lock';
62300803e56STom N Harris        while (!@mkdir($lock, $conf['dmode'])) {
62400803e56STom N Harris            usleep(50);
62500803e56STom N Harris            if (time() - @filemtime($lock) > 60*5) {
62600803e56STom N Harris                // looks like a stale lock, remove it
62700803e56STom N Harris                @rmdir($lock);
62800803e56STom N Harris                $status = "stale lock removed";
62900803e56STom N Harris            } else {
63000803e56STom N Harris                return false;
63100803e56STom N Harris            }
63200803e56STom N Harris        }
63300803e56STom N Harris        if ($conf['dperm'])
63400803e56STom N Harris            chmod($lock, $conf['dperm']);
63500803e56STom N Harris        return $status;
63600803e56STom N Harris    }
63700803e56STom N Harris
63800803e56STom N Harris    /**
63900803e56STom N Harris     * Release the indexer lock.
64000803e56STom N Harris     *
64100803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
64200803e56STom N Harris     */
64300803e56STom N Harris    private function _unlock() {
64400803e56STom N Harris        global $conf;
64500803e56STom N Harris        @rmdir($conf['lockdir'].'/_indexer.lock');
64600803e56STom N Harris        return true;
64700803e56STom N Harris    }
64800803e56STom N Harris
64900803e56STom N Harris    /**
65000803e56STom N Harris     * Retrieve the entire index.
65100803e56STom N Harris     *
65200803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
65300803e56STom N Harris     */
65400803e56STom N Harris    private function _getIndex($idx, $suffix) {
65500803e56STom N Harris        global $conf;
65600803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
657d64516f5SMichael Hamann        if (!@file_exists($fn)) return array();
658d64516f5SMichael Hamann        return file($fn, FILE_IGNORE_NEW_LINES);
65900803e56STom N Harris    }
66000803e56STom N Harris
66100803e56STom N Harris    /**
66200803e56STom N Harris     * Replace the contents of the index with an array.
66300803e56STom N Harris     *
66400803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
66500803e56STom N Harris     */
66600803e56STom N Harris    private function _saveIndex($idx, $suffix, &$lines) {
66700803e56STom N Harris        global $conf;
66800803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
66900803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
67000803e56STom N Harris        if (!$fh) return false;
67100803e56STom N Harris        fwrite($fh, join("\n", $lines));
67200803e56STom N Harris        fclose($fh);
67300803e56STom N Harris        if (isset($conf['fperm']))
67400803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
67500803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
67600803e56STom N Harris        if ($suffix !== '')
67700803e56STom N Harris            $this->_cacheIndexDir($idx, $suffix, empty($lines));
67800803e56STom N Harris        return true;
67900803e56STom N Harris    }
68000803e56STom N Harris
68100803e56STom N Harris    /**
68200803e56STom N Harris     * Retrieve a line from the index.
68300803e56STom N Harris     *
68400803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
68500803e56STom N Harris     */
68600803e56STom N Harris    private function _getIndexKey($idx, $suffix, $id) {
68700803e56STom N Harris        global $conf;
68800803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
68900803e56STom N Harris        if (!@file_exists($fn)) return '';
69000803e56STom N Harris        $fh = @fopen($fn, 'r');
69100803e56STom N Harris        if (!$fh) return '';
69200803e56STom N Harris        $ln = -1;
69300803e56STom N Harris        while (($line = fgets($fh)) !== false) {
69400803e56STom N Harris            if (++$ln == $id) break;
69500803e56STom N Harris        }
69600803e56STom N Harris        fclose($fh);
69700803e56STom N Harris        return rtrim((string)$line);
69800803e56STom N Harris    }
69900803e56STom N Harris
70000803e56STom N Harris    /**
70100803e56STom N Harris     * Write a line into the index.
70200803e56STom N Harris     *
70300803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
70400803e56STom N Harris     */
70500803e56STom N Harris    private function _saveIndexKey($idx, $suffix, $id, $line) {
70600803e56STom N Harris        global $conf;
70700803e56STom N Harris        if (substr($line, -1) != "\n")
70800803e56STom N Harris            $line .= "\n";
70900803e56STom N Harris        $fn = $conf['indexdir'].'/'.$idx.$suffix;
71000803e56STom N Harris        $fh = @fopen($fn.'.tmp', 'w');
71100803e56STom N Harris        if (!fh) return false;
71200803e56STom N Harris        $ih = @fopen($fn.'.idx', 'r');
71300803e56STom N Harris        if ($ih) {
71400803e56STom N Harris            $ln = -1;
71500803e56STom N Harris            while (($curline = fgets($ih)) !== false) {
71600803e56STom N Harris                fwrite($fh, (++$ln == $id) ? $line : $curline);
71700803e56STom N Harris            }
7184373c7b5SMichael Hamann            if ($id > $ln) {
7194373c7b5SMichael Hamann                while ($id > ++$ln)
7204373c7b5SMichael Hamann                    fwrite($fh, "\n");
72100803e56STom N Harris                fwrite($fh, $line);
7224373c7b5SMichael Hamann            }
72300803e56STom N Harris            fclose($ih);
72400803e56STom N Harris        } else {
7254373c7b5SMichael Hamann            $ln = -1;
7264373c7b5SMichael Hamann            while ($id > ++$ln)
7274373c7b5SMichael Hamann                fwrite($fh, "\n");
72800803e56STom N Harris            fwrite($fh, $line);
72900803e56STom N Harris        }
73000803e56STom N Harris        fclose($fh);
73100803e56STom N Harris        if (isset($conf['fperm']))
73200803e56STom N Harris            chmod($fn.'.tmp', $conf['fperm']);
73300803e56STom N Harris        io_rename($fn.'.tmp', $fn.'.idx');
73400803e56STom N Harris        if ($suffix !== '')
73500803e56STom N Harris            $this->_cacheIndexDir($idx, $suffix);
73600803e56STom N Harris        return true;
73700803e56STom N Harris    }
73800803e56STom N Harris
73900803e56STom N Harris    /**
74000803e56STom N Harris     * Retrieve or insert a value in the index.
74100803e56STom N Harris     *
74200803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
74300803e56STom N Harris     */
74400803e56STom N Harris    private function _addIndexKey($idx, $suffix, $value) {
74500803e56STom N Harris        $index = $this->_getIndex($idx, $suffix);
74600803e56STom N Harris        $id = array_search($value, $index);
74700803e56STom N Harris        if ($id === false) {
74800803e56STom N Harris            $id = count($index);
74900803e56STom N Harris            $index[$id] = $value;
75000803e56STom N Harris            if (!$this->_saveIndex($idx, $suffix, $index)) {
75100803e56STom N Harris                trigger_error("Failed to write $idx index", E_USER_ERROR);
75200803e56STom N Harris                return false;
75300803e56STom N Harris            }
75400803e56STom N Harris        }
75500803e56STom N Harris        return $id;
75600803e56STom N Harris    }
75700803e56STom N Harris
75800803e56STom N Harris    private function _cacheIndexDir($idx, $suffix, $delete=false) {
75900803e56STom N Harris        global $conf;
76000803e56STom N Harris        if ($idx == 'i')
76100803e56STom N Harris            $cachename = $conf['indexdir'].'/lengths';
76200803e56STom N Harris        else
76300803e56STom N Harris            $cachename = $conf['indexdir'].'/'.$idx.'lengths';
76400803e56STom N Harris        $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
76500803e56STom N Harris        if ($lengths === false) $lengths = array();
76600803e56STom N Harris        $old = array_search((string)$suffix, $lengths);
76700803e56STom N Harris        if (empty($lines)) {
76800803e56STom N Harris            if ($old === false) return;
76900803e56STom N Harris            unset($lengths[$old]);
77000803e56STom N Harris        } else {
77100803e56STom N Harris            if ($old !== false) return;
77200803e56STom N Harris            $lengths[] = $suffix;
77300803e56STom N Harris            sort($lengths);
77400803e56STom N Harris        }
77500803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
77600803e56STom N Harris        if (!$fh) {
77700803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
77800803e56STom N Harris            return;
77900803e56STom N Harris        }
78000803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
78100803e56STom N Harris        @fclose($fh);
78200803e56STom N Harris        if (isset($conf['fperm']))
78300803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
78400803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
78500803e56STom N Harris    }
78600803e56STom N Harris
78700803e56STom N Harris    /**
78800803e56STom N Harris     * Get the list of lengths indexed in the wiki.
78900803e56STom N Harris     *
79000803e56STom N Harris     * Read the index directory or a cache file and returns
79100803e56STom N Harris     * a sorted array of lengths of the words used in the wiki.
79200803e56STom N Harris     *
79300803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
79400803e56STom N Harris     */
79500803e56STom N Harris    private function _listIndexLengths() {
79600803e56STom N Harris        global $conf;
79700803e56STom N Harris        $cachename = $conf['indexdir'].'/lengths';
79800803e56STom N Harris        clearstatcache();
79900803e56STom N Harris        if (@file_exists($cachename.'.idx')) {
80000803e56STom N Harris            $lengths = @file($cachename.'.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
80100803e56STom N Harris            if ($lengths !== false) {
80200803e56STom N Harris                $idx = array();
80300803e56STom N Harris                foreach ($lengths as $length)
80400803e56STom N Harris                    $idx[] = (int)$length;
80500803e56STom N Harris                return $idx;
80600803e56STom N Harris            }
80700803e56STom N Harris        }
80800803e56STom N Harris
80900803e56STom N Harris        $dir = @opendir($conf['indexdir']);
81000803e56STom N Harris        if ($dir === false)
81100803e56STom N Harris            return array();
81200803e56STom N Harris        $lengths[] = array();
81300803e56STom N Harris        while (($f = readdir($dir)) !== false) {
81400803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
81500803e56STom N Harris                $i = substr($f, 1, -4);
81600803e56STom N Harris                if (is_numeric($i))
81700803e56STom N Harris                    $lengths[] = (int)$i;
81800803e56STom N Harris            }
81900803e56STom N Harris        }
82000803e56STom N Harris        closedir($dir);
82100803e56STom N Harris        sort($lengths);
82200803e56STom N Harris        // save this in a file
82300803e56STom N Harris        $fh = @fopen($cachename.'.tmp', 'w');
82400803e56STom N Harris        if (!$fh) {
82500803e56STom N Harris            trigger_error("Failed to write index cache", E_USER_ERROR);
82600803e56STom N Harris            return;
82700803e56STom N Harris        }
82800803e56STom N Harris        @fwrite($fh, implode("\n", $lengths));
82900803e56STom N Harris        @fclose($fh);
83000803e56STom N Harris        if (isset($conf['fperm']))
83100803e56STom N Harris            chmod($cachename.'.tmp', $conf['fperm']);
83200803e56STom N Harris        io_rename($cachename.'.tmp', $cachename.'.idx');
83300803e56STom N Harris
83400803e56STom N Harris        return $lengths;
83500803e56STom N Harris    }
83600803e56STom N Harris
83700803e56STom N Harris    /**
83800803e56STom N Harris     * Get the word lengths that have been indexed.
83900803e56STom N Harris     *
84000803e56STom N Harris     * Reads the index directory and returns an array of lengths
84100803e56STom N Harris     * that there are indices for.
84200803e56STom N Harris     *
84300803e56STom N Harris     * @author YoBoY <yoboy.leguesh@gmail.com>
84400803e56STom N Harris     */
84500803e56STom N Harris    private function _indexLengths($filter) {
84600803e56STom N Harris        global $conf;
84700803e56STom N Harris        $idx = array();
84800803e56STom N Harris        if (is_array($filter)) {
84900803e56STom N Harris            // testing if index files exist only
85000803e56STom N Harris            $path = $conf['indexdir']."/i";
85100803e56STom N Harris            foreach ($filter as $key => $value) {
85200803e56STom N Harris                if (@file_exists($path.$key.'.idx'))
85300803e56STom N Harris                    $idx[] = $key;
85400803e56STom N Harris            }
85500803e56STom N Harris        } else {
85600803e56STom N Harris            $lengths = idx_listIndexLengths();
85700803e56STom N Harris            foreach ($lengths as $key => $length) {
85800803e56STom N Harris                // keep all the values equal or superior
85900803e56STom N Harris                if ((int)$length >= (int)$filter)
86000803e56STom N Harris                    $idx[] = $length;
86100803e56STom N Harris            }
86200803e56STom N Harris        }
86300803e56STom N Harris        return $idx;
86400803e56STom N Harris    }
86500803e56STom N Harris
86600803e56STom N Harris    /**
86700803e56STom N Harris     * Insert or replace a tuple in a line.
86800803e56STom N Harris     *
86900803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
87000803e56STom N Harris     */
87100803e56STom N Harris    private function _updateTuple($line, $id, $count) {
87200803e56STom N Harris        $newLine = $line;
87300803e56STom N Harris        if ($newLine !== '')
87400803e56STom N Harris            $newLine = preg_replace('/(^|:)'.preg_quote($id,'/').'\*\d*/', '', $newLine);
87500803e56STom N Harris        $newLine = trim($newLine, ':');
87600803e56STom N Harris        if ($count) {
877d64516f5SMichael Hamann            if (strlen($newLine) > 0)
87800803e56STom N Harris                return "$id*$count:".$newLine;
87900803e56STom N Harris            else
88000803e56STom N Harris                return "$id*$count".$newLine;
88100803e56STom N Harris        }
88200803e56STom N Harris        return $newLine;
88300803e56STom N Harris    }
88400803e56STom N Harris
88500803e56STom N Harris    /**
88600803e56STom N Harris     * Split a line into an array of tuples.
88700803e56STom N Harris     *
88800803e56STom N Harris     * @author Tom N Harris <tnharris@whoopdedo.org>
88900803e56STom N Harris     * @author Andreas Gohr <andi@splitbrain.org>
89000803e56STom N Harris     */
89100803e56STom N Harris    private function _parseTuples(&$keys, $line) {
89200803e56STom N Harris        $result = array();
89300803e56STom N Harris        if ($line == '') return $result;
89400803e56STom N Harris        $parts = explode(':', $line);
89500803e56STom N Harris        foreach ($parts as $tuple) {
89600803e56STom N Harris            if ($tuple == '') continue;
89700803e56STom N Harris            list($key, $cnt) = explode('*', $tuple);
898d64516f5SMichael Hamann            if (!$cnt) continue;
89900803e56STom N Harris            $key = $keys[$key];
90000803e56STom N Harris            if (!$key) continue;
90100803e56STom N Harris            $result[$key] = $cnt;
90200803e56STom N Harris        }
90300803e56STom N Harris        return $result;
90400803e56STom N Harris    }
90500803e56STom N Harris}
90600803e56STom N Harris
90700803e56STom N Harris/**
90800803e56STom N Harris * Create an instance of the indexer.
90900803e56STom N Harris *
91000803e56STom N Harris * @return object               a Doku_Indexer
91100803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
91200803e56STom N Harris */
9139b41be24STom N Harrisfunction idx_get_indexer() {
91400803e56STom N Harris    static $Indexer = null;
91500803e56STom N Harris    if (is_null($Indexer)) {
91600803e56STom N Harris        $Indexer = new Doku_Indexer();
91700803e56STom N Harris    }
91800803e56STom N Harris    return $Indexer;
91900803e56STom N Harris}
92000803e56STom N Harris
92100803e56STom N Harris/**
92200803e56STom N Harris * Returns words that will be ignored.
92300803e56STom N Harris *
92400803e56STom N Harris * @return array                list of stop words
92500803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
92600803e56STom N Harris */
92700803e56STom N Harrisfunction & idx_get_stopwords() {
92800803e56STom N Harris    static $stopwords = null;
92900803e56STom N Harris    if (is_null($stopwords)) {
93000803e56STom N Harris        global $conf;
93100803e56STom N Harris        $swfile = DOKU_INC.'inc/lang/'.$conf['lang'].'/stopwords.txt';
93200803e56STom N Harris        if(@file_exists($swfile)){
93300803e56STom N Harris            $stopwords = file($swfile, FILE_IGNORE_NEW_LINES);
93400803e56STom N Harris        }else{
93500803e56STom N Harris            $stopwords = array();
93600803e56STom N Harris        }
93700803e56STom N Harris    }
93800803e56STom N Harris    return $stopwords;
93900803e56STom N Harris}
94000803e56STom N Harris
94100803e56STom N Harris/**
94200803e56STom N Harris * Adds/updates the search index for the given page
94300803e56STom N Harris *
94400803e56STom N Harris * Locking is handled internally.
94500803e56STom N Harris *
94600803e56STom N Harris * @param string        $page   name of the page to index
9479b41be24STom N Harris * @param boolean       $verbose    print status messages
94800803e56STom N Harris * @return boolean              the function completed successfully
94900803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
95000803e56STom N Harris */
9519b41be24STom N Harrisfunction idx_addPage($page, $verbose=false) {
9529b41be24STom N Harris    // check if indexing needed
9539b41be24STom N Harris    $idxtag = metaFN($page,'.indexed');
9549b41be24STom N Harris    if(@file_exists($idxtag)){
9559b41be24STom N Harris        if(trim(io_readFile($idxtag)) == idx_get_version()){
9569b41be24STom N Harris            $last = @filemtime($idxtag);
9579b41be24STom N Harris            if($last > @filemtime(wikiFN($ID))){
9589b41be24STom N Harris                if ($verbose) print("Indexer: index for $page up to date".DOKU_LF);
9599b41be24STom N Harris                return false;
9609b41be24STom N Harris            }
9619b41be24STom N Harris        }
9629b41be24STom N Harris    }
9639b41be24STom N Harris
964*bbc85ee4STom N Harris    if (!page_exists($page)) {
965*bbc85ee4STom N Harris        if (!@file_exists($idxtag)) {
966*bbc85ee4STom N Harris            if ($verbose) print("Indexer: $page does not exist, ignoring".DOKU_LF);
967*bbc85ee4STom N Harris            return false;
968*bbc85ee4STom N Harris        }
969*bbc85ee4STom N Harris        $Indexer = idx_get_indexer();
970*bbc85ee4STom N Harris        $result = $Indexer->deletePage($page);
971*bbc85ee4STom N Harris        if ($result === "locked") {
972*bbc85ee4STom N Harris            if ($verbose) print("Indexer: locked".DOKU_LF);
973*bbc85ee4STom N Harris            return false;
974*bbc85ee4STom N Harris        }
975*bbc85ee4STom N Harris        @unlink($idxtag);
976*bbc85ee4STom N Harris        return $result;
977*bbc85ee4STom N Harris    }
978*bbc85ee4STom N Harris    $indexenabled = p_get_metadata($page, 'internal index', false);
979*bbc85ee4STom N Harris    if ($indexenabled === false) {
980*bbc85ee4STom N Harris        $result = false;
981*bbc85ee4STom N Harris        if (@file_exists($idxtag)) {
982*bbc85ee4STom N Harris            $Indexer = idx_get_indexer();
983*bbc85ee4STom N Harris            $result = $Indexer->deletePage($page);
984*bbc85ee4STom N Harris            if ($result === "locked") {
985*bbc85ee4STom N Harris                if ($verbose) print("Indexer: locked".DOKU_LF);
986*bbc85ee4STom N Harris                return false;
987*bbc85ee4STom N Harris            }
988*bbc85ee4STom N Harris            @unlink($idxtag);
989*bbc85ee4STom N Harris        }
990*bbc85ee4STom N Harris        if ($verbose) print("Indexer: index disabled for $page".DOKU_LF);
991*bbc85ee4STom N Harris        return $result;
992*bbc85ee4STom N Harris    }
993*bbc85ee4STom N Harris
99400803e56STom N Harris    $body = '';
99500803e56STom N Harris    $data = array($page, $body);
99600803e56STom N Harris    $evt = new Doku_Event('INDEXER_PAGE_ADD', $data);
99700803e56STom N Harris    if ($evt->advise_before()) $data[1] = $data[1] . " " . rawWiki($page);
99800803e56STom N Harris    $evt->advise_after();
99900803e56STom N Harris    unset($evt);
100000803e56STom N Harris    list($page,$body) = $data;
100100803e56STom N Harris
10029b41be24STom N Harris    $Indexer = idx_get_indexer();
10039b41be24STom N Harris    $result = $Indexer->addPageWords($page, $body);
1004e1e1a7e0SMichael Hamann    if ($result === "locked") {
10059b41be24STom N Harris        if ($verbose) print("Indexer: locked".DOKU_LF);
10069b41be24STom N Harris        return false;
10079b41be24STom N Harris    }
1008320f489aSMichael Hamann
1009320f489aSMichael Hamann    if ($result) {
1010320f489aSMichael Hamann        $data = array('page' => $page, 'metadata' => array());
1011320f489aSMichael Hamann
1012*bbc85ee4STom N Harris        $data['metadata']['title'] = p_get_metadata($page, 'title', false);
1013*bbc85ee4STom N Harris        if (($references = p_get_metadata($page, 'relation references', false)) !== null)
1014320f489aSMichael Hamann            $data['metadata']['relation_references'] = array_keys($references);
1015320f489aSMichael Hamann
1016320f489aSMichael Hamann        $evt = new Doku_Event('INDEXER_METADATA_INDEX', $data);
1017320f489aSMichael Hamann        if ($evt->advise_before()) {
1018320f489aSMichael Hamann            $result = $Indexer->addMetaKeys($page, $data['metadata']);
1019320f489aSMichael Hamann            if ($result === "locked") {
1020320f489aSMichael Hamann                if ($verbose) print("Indexer: locked".DOKU_LF);
1021320f489aSMichael Hamann                return false;
1022320f489aSMichael Hamann            }
1023320f489aSMichael Hamann        }
1024320f489aSMichael Hamann        $evt->advise_after();
1025320f489aSMichael Hamann        unset($evt);
1026320f489aSMichael Hamann    }
1027320f489aSMichael Hamann
10289b41be24STom N Harris    if ($result)
10299b41be24STom N Harris        io_saveFile(metaFN($page,'.indexed'), idx_get_version());
10309b41be24STom N Harris    if ($verbose) {
10319b41be24STom N Harris        print("Indexer: finished".DOKU_LF);
10329b41be24STom N Harris        return true;
10339b41be24STom N Harris    }
10349b41be24STom N Harris    return $result;
103500803e56STom N Harris}
103600803e56STom N Harris
103700803e56STom N Harris/**
103800803e56STom N Harris * Find tokens in the fulltext index
103900803e56STom N Harris *
104000803e56STom N Harris * Takes an array of words and will return a list of matching
104100803e56STom N Harris * pages for each one.
1042488dd6ceSAndreas Gohr *
104363773904SAndreas Gohr * Important: No ACL checking is done here! All results are
104463773904SAndreas Gohr *            returned, regardless of permissions
104563773904SAndreas Gohr *
10469b41be24STom N Harris * @param arrayref      $words  list of words to search for
104700803e56STom N Harris * @return array                list of pages found, associated with the search terms
1048488dd6ceSAndreas Gohr */
10499b41be24STom N Harrisfunction idx_lookup(&$words) {
10509b41be24STom N Harris    $Indexer = idx_get_indexer();
105100803e56STom N Harris    return $Indexer->lookup($words);
1052488dd6ceSAndreas Gohr}
1053488dd6ceSAndreas Gohr
1054488dd6ceSAndreas Gohr/**
105500803e56STom N Harris * Split a string into tokens
1056488dd6ceSAndreas Gohr *
1057488dd6ceSAndreas Gohr */
105800803e56STom N Harrisfunction idx_tokenizer($string, $wc=false) {
10599b41be24STom N Harris    $Indexer = idx_get_indexer();
106000803e56STom N Harris    return $Indexer->tokenizer($string, $wc);
1061488dd6ceSAndreas Gohr}
106200803e56STom N Harris
106300803e56STom N Harris/* For compatibility */
1064488dd6ceSAndreas Gohr
1065f5eb7cf0SAndreas Gohr/**
106600803e56STom N Harris * Read the list of words in an index (if it exists).
1067f5eb7cf0SAndreas Gohr *
10684e1bf408STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
1069f5eb7cf0SAndreas Gohr */
107000803e56STom N Harrisfunction idx_getIndex($idx, $suffix) {
10711c07b9e6STom N Harris    global $conf;
107200803e56STom N Harris    $fn = $conf['indexdir'].'/'.$idx.$suffix.'.idx';
107300803e56STom N Harris    if (!@file_exists($fn)) return array();
107400803e56STom N Harris    return file($fn);
107500803e56STom N Harris}
1076f5eb7cf0SAndreas Gohr
107700803e56STom N Harris/**
107800803e56STom N Harris * Get the list of lengths indexed in the wiki.
107900803e56STom N Harris *
108000803e56STom N Harris * Read the index directory or a cache file and returns
108100803e56STom N Harris * a sorted array of lengths of the words used in the wiki.
108200803e56STom N Harris *
108300803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
108400803e56STom N Harris */
108500803e56STom N Harrisfunction idx_listIndexLengths() {
108600803e56STom N Harris    global $conf;
108700803e56STom N Harris    // testing what we have to do, create a cache file or not.
108800803e56STom N Harris    if ($conf['readdircache'] == 0) {
108900803e56STom N Harris        $docache = false;
10901c07b9e6STom N Harris    } else {
109100803e56STom N Harris        clearstatcache();
109200803e56STom N Harris        if (@file_exists($conf['indexdir'].'/lengths.idx')
109300803e56STom N Harris        && (time() < @filemtime($conf['indexdir'].'/lengths.idx') + $conf['readdircache'])) {
109400803e56STom N Harris            if (($lengths = @file($conf['indexdir'].'/lengths.idx', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) !== false) {
109500803e56STom N Harris                $idx = array();
109600803e56STom N Harris                foreach ($lengths as $length) {
109700803e56STom N Harris                    $idx[] = (int)$length;
109800803e56STom N Harris                }
109900803e56STom N Harris                return $idx;
1100f5eb7cf0SAndreas Gohr            }
11011c07b9e6STom N Harris        }
110200803e56STom N Harris        $docache = true;
110300803e56STom N Harris    }
11044e1bf408STom N Harris
110500803e56STom N Harris    if ($conf['readdircache'] == 0 || $docache) {
110600803e56STom N Harris        $dir = @opendir($conf['indexdir']);
110700803e56STom N Harris        if ($dir === false)
110800803e56STom N Harris            return array();
110900803e56STom N Harris        $idx[] = array();
111000803e56STom N Harris        while (($f = readdir($dir)) !== false) {
111100803e56STom N Harris            if (substr($f, 0, 1) == 'i' && substr($f, -4) == '.idx') {
111200803e56STom N Harris                $i = substr($f, 1, -4);
111300803e56STom N Harris                if (is_numeric($i))
111400803e56STom N Harris                    $idx[] = (int)$i;
111500803e56STom N Harris            }
111600803e56STom N Harris        }
111700803e56STom N Harris        closedir($dir);
111800803e56STom N Harris        sort($idx);
111900803e56STom N Harris        // save this in a file
112000803e56STom N Harris        if ($docache) {
112100803e56STom N Harris            $handle = @fopen($conf['indexdir'].'/lengths.idx', 'w');
112200803e56STom N Harris            @fwrite($handle, implode("\n", $idx));
112300803e56STom N Harris            @fclose($handle);
112400803e56STom N Harris        }
112500803e56STom N Harris        return $idx;
112600803e56STom N Harris    }
112700803e56STom N Harris
112800803e56STom N Harris    return array();
112900803e56STom N Harris}
113000803e56STom N Harris
113100803e56STom N Harris/**
113200803e56STom N Harris * Get the word lengths that have been indexed.
113300803e56STom N Harris *
113400803e56STom N Harris * Reads the index directory and returns an array of lengths
113500803e56STom N Harris * that there are indices for.
113600803e56STom N Harris *
113700803e56STom N Harris * @author YoBoY <yoboy.leguesh@gmail.com>
113800803e56STom N Harris */
113900803e56STom N Harrisfunction idx_indexLengths($filter) {
114000803e56STom N Harris    global $conf;
114100803e56STom N Harris    $idx = array();
114200803e56STom N Harris    if (is_array($filter)) {
114300803e56STom N Harris        // testing if index files exist only
114400803e56STom N Harris        $path = $conf['indexdir']."/i";
114500803e56STom N Harris        foreach ($filter as $key => $value) {
114600803e56STom N Harris            if (@file_exists($path.$key.'.idx'))
114700803e56STom N Harris                $idx[] = $key;
114800803e56STom N Harris        }
1149f5eb7cf0SAndreas Gohr    } else {
115000803e56STom N Harris        $lengths = idx_listIndexLengths();
115100803e56STom N Harris        foreach ($lengths as $key => $length) {
115200803e56STom N Harris            // keep all the values equal or superior
115300803e56STom N Harris            if ((int)$length >= (int)$filter)
115400803e56STom N Harris                $idx[] = $length;
1155f5eb7cf0SAndreas Gohr        }
115600803e56STom N Harris    }
115700803e56STom N Harris    return $idx;
1158f5eb7cf0SAndreas Gohr}
1159f5eb7cf0SAndreas Gohr
116000803e56STom N Harris/**
116100803e56STom N Harris * Clean a name of a key for use as a file name.
116200803e56STom N Harris *
116300803e56STom N Harris * Romanizes non-latin characters, then strips away anything that's
116400803e56STom N Harris * not a letter, number, or underscore.
116500803e56STom N Harris *
116600803e56STom N Harris * @author Tom N Harris <tnharris@whoopdedo.org>
116700803e56STom N Harris */
116800803e56STom N Harrisfunction idx_cleanName($name) {
116900803e56STom N Harris    $name = utf8_romanize(trim((string)$name));
117000803e56STom N Harris    $name = preg_replace('#[ \./\\:-]+#', '_', $name);
117100803e56STom N Harris    $name = preg_replace('/[^A-Za-z0-9_]/', '', $name);
117200803e56STom N Harris    return strtolower($name);
1173f5eb7cf0SAndreas Gohr}
1174f5eb7cf0SAndreas Gohr
117500803e56STom N Harris//Setup VIM: ex: et ts=4 :
1176